Java Generics: extends, super and wildcards explained

Today we continue our mini-series on Java Generics. In previous posts we have investigated

Java type parameters are used as type placeholders.

public class List<X>  { }
A List<X> is a container for X objects, and X can be instantiated with any class: you can have List<Object>, List<String>, and List<Number>.

Introducing bounds: extends

You often want to restrict the set of types that can be used in instantiation. If you create a class Garage, you want it to hold only Vehicle objects.

The syntax you use in Java is like this:

public class Garage<X extends Vehicle> { }
Every time you instantiate the Garage, the type parameter has to be a subclass of Vehicle.

class Car extends Vehicle { }
class Motorcycle extends Vehicle { }
class Fruit extends Object { }
Thus Garage<Car> and Garage<Motorcycle> are OK but Garage<Fruit> is not OK.

You can specify more than one bound with extends:

class Vehicle { }
interface PassengerVehicle { }
interface MotorVehicle { }
class ParkingGarage<X extends Vehicle & MotorVehicle & PassengerVehicle>
You can specify at most one class in the bound (obviously, as you can only inherit from one class in Java) and as many interfaces as you want.

The bound can refer to the typing parameter:

class BST<X extends Comparable<X>> {}
BST class can only be instantiated with classes X which implement the Comparable<X> interface.

Bounds in method parameters

Java method can be parametrized, too. The syntax is as follows:

<T> T getRandomElement(List<T> list) {}
As with class definitions, you often want to restrict the type parameter in the method. A method which takes a list of Vehicles and returns the fastest vehicle in the list can have the following type.
<T extends Vehicle> T getFastest(List<T> list) { }
You can pass as argument a list of any vehicles. List<Car> is OK, List<Motorcycle> is OK, List<Vehicle> is OK, too. List<Number> is not OK.

Note that the following declaration wouldn't do the trick.

Vehicle getFastest2(List<Vehicle> list) { }
The argument to the method getFastest2 has to be exactly a List<Vehicle>, and not a List<Car>, because List<Car> is not a subtype of List<Vehicle>,

Wilcards

Take a look at the following declaration.

<T extends Vehicle> int totalFuel(List<T> list) { }
The parameter T occurs only once in the method signature, in an argument. You can imagine that the method body does not use the name T either. In this case you can use an alternative syntax, called wildcards, denoted with ?:
int totalFuel(List<? extends Vehicle> list) { }
The two signatures for totalFuel are equivalent. The meaning of <? extends Vehicle> is: I don't care what the type parameter is, as long as it is a subclass of Vehicle.

Introducing bounds: super

There is also dual bound, called super. As you guess it is used to denote that you can pass only superclasses of the bound. There are some differences between extends and super, though.

You can't use super in class declaration

The super bound is not allowed in class definition.

//this code does not compile !
class Forbidden<X super Vehicle> { }
Why? Because such construction doesn't make sense. For example, you can't erase the type parameter with Vehicle because the class Forbidden could be instantiated with Object. So you have to erase type parameters to Object anyway. If think about class Forbidden<Object>, it can take any value in place of X, not only superclasses of Vehicle. There's no point in using super bound, it wouldn't get us anything. Thus it is not allowed.

Wildcards

The syntax for wildcards is also similar to extends:

int totalValue(Valuer<? super Vehicle> valuer)
The method has to take a comparator which is able to compare Vehicles. If it compares Objects as well, that's fine too.

When to use extends and super

Wildcards are most useful in method parameters. They allow for the necessary flexibility in method interfaces.

People are often confused when to use extends and when to use super bounds. The rule of thumb is the get-put principle. If you get something from a parametrized container, use extends.

int totalFuel(List<? extends Vehicle> list) { 
	int total = 0;
	for(Vehicle v : list) {
		total += v.getFuel();
	}
	return total;
}
The method totalFuel gets Vehicles from the list, asks them about how much fuel they have, and computes the total.

If you put objects into a parametrized container, use super.

int totalValue(Valuer<? super Vehicle> valuer) {
	int total = 0;
	for(Vehicle v : vehicles) {
		total += valuer.evaluate(v);
	}
	return total;
}
The method totalValue puts Vehicles into the Valuer.

It's useful to know that extends bound is much more common than super.

One more tip: if you are intimidated by wildcards (which is natural in the beginning), try to write the explicitly parametrized version first. In typical usage the two versions are equivalent. Eventually, you'll figure out when you can get rid of type parameters and use wildcards.

Read the whole article

Comments

The Next Language to Learn

I develop Java applications and have 12 years of Java programming, but I've never really liked the language. Java is bureaucratic. Java is baroque. Java doesn't have syntax support for lists and maps, and I use lists and maps use more often than I do multiplication! Yes, this is web programming: building a bridge between the database and HTML. Java has a strength that cannot be simply overlooked. It runs everywhere. Yeah, almost everywhere ;). It's well known, and despite it's awkwardness, it is useful. It's a language for business solutions. Just like English for sales people ;).

As I said, I use mostly Java at work. Mostly but not only. I've used other languages. Here is a short list, and how these languages make me feel:

  • bash - wheel (hashmap) reinventor
  • php - google-and-paste script monkey
  • perl - a wizard before, an Egyptologist after
  • lisp - a MUD addict
  • ruby - a hipster, really don't know why
  • python - a zen-master-like purity neophyte
  • erlang - didn't try, functional paradigm is too scary
  • C# - ehhh, I've seen this before, didn't I?

Every language in that list has its own distinctive taste. It's really easy to become a fan. Or become a fanatic if you are addicted to that flavor. Each of these languages occupies its own niche. One may suit some people, and totally do not suit others. Java doesn't taste good, but it is not so bad for most people. It is 'edible' like baby food.

Don't think these other languages supersede Java in business solutions, even though some people think they do. For me, it's the same as if Subversion tried to supersede CVS. It was an obvious choice for some time. Then Git came and the paradigm shift hit the masses. I'm still waiting for that change in the language world. Java is almost 20 years old. Yes, there changes from version to version, but I consider these changes cancerous. Period. Too much is added, while nothing is removed.

I had no hope. I knew that new languages are born, but didn't pay attention to the latest and greatest press releases. One day had some spare time and I saw a paper on a coworker's desk. It's was about Google's new language. C'mon yet another languange. C'mon yet more stuff from Google. C'mon yet another blah blah. I started reading. Bang! My nisgivings were addressed in the paper in plain English. My objections were as a ... solved problems. I'm not alone I thought, haha. The Go language is on the list of languages to learn. To learn it means to make software using it.

What do I like in Go? It's not a syntax, not a type hierarchy, even not a name. It's a design decision "let's make big software development easier". That's all.

Dependencies are a nightmare to solve. Circular dependencies are nightmare^2. Go has no circular dependencies. Clever eh? Java has 'public/protected/private' keyword to define visibility, I heard rumors that they going to add sacred keyword in Java 10 ;). In Go, a capital letter makes the identifier public. There is added concurrency support to the language core. Nice. Garbage collection is obvious nowadays.

In Go you can't extend another class. Inheritance is not possible. God bless that decision. Really hated debugging method calls in a huge class hierarchy. Read the answer for a question I tried to forward a method to super, but it occasionally doesn't work. Why? in the famous The Java IAQ: Infrequently Answered Questions. You will know why I avoid inheritance.

In Go there are no exceptions. No more "check vs. no-check" dispute. No more jumping while reading the code, just reading it linear just as it is written. In Common Lisp there is a mechanism called restarts that I don't miss a bit in my daily coding. The same will be with exceptions.

The last thing is a formatter. It's not simply a formatter that puts the same spaces in a block. That formatter can transform code. Automated refactorings are on the way.

I don't have time to experience Go. Can't tell you more about it. I think I have to wait for a something big to implement. "Hello world" programs are useless in testing.

Do you have experience with Go? What do you think is Go will supersede Java in business solutions?

PS. Right now I've googled who wrote that article to put it as a reference. Rob Pike wrote it and his is working for Google.

Read the whole article

Comments

An interview with Łukasz Mróz, a programmer and a DB architect with OneWebSQL experience

Łukasz Mróz has been working at e-point since August 2011. He began as a Java programmer and after a few months he switched to being a DB Architect. Today he shares with us his unique perspective on OneWebSQL - both as a programmer and as a DB Architect.

Read the whole article

Comments

My Favorite Programming Videos

I love Youtube. It is my favorite Internet service. No matter what's you're interested in: free music, movies, makeup tips, fashion advice, cooking recipes, yoga, sonic boom, the inner life of a cell, or info on how to clean a fan, you'll find an awesome Youtube video on it. Today I will share with you a selection of my favorite programming videos.

Read the whole article

Comments

Impedance mismatch in the software realm

Impedance, impedance, impedance. I think I should know something about it, since I studied electronics years ago. Unfortunately, I don't remember when I was soldering something. Hmmmmm solving circuits ... is a lost art.[...]

Read the whole article

Comments

Java Generics: The Difference between Java Arrays and Generic Lists

In this post we'll investigate generic lists and how they differ from Java arrays.

A puzzle

Let's begin with a puzzle. Suppose we have a class Student which inherits from a class Person:

Read the whole article

Comments

My Top Five OneWebSQL Patterns

When I start using a new language or library, I'm a beginner. again. Most of the time it is an adventure, but sometimes I feel lost. I've got documentation, but I don't know what should I read first. I'm looking for a cookbook. Some vendors provide a cookbook; some do not, in which case hopefully we've got the Interent -- especially Google and StackOverFlow.com.[..]

Read the whole article

Comments

OneWebSQL at 33rd Degree

33rd Degree is an annual international Java conference. This year it was organized in Warsaw, on March 13-15. The OneWebSQL team was there in force, discussing developer solutions and current trends in Java application development, and attending conference sessions.

More team members could attend this year because the conference was held in Warsaw, where we all live. There was Marek from e-point Localization Platform (affectionately called Lion), Ania and Iwona from the marketing department, and Jarek from the sales department, who stood out in a suit. :) From the OneWebSQL team, we had planned that Tomek, the product manager, would be at the conference on both Wednesday and Thursday, Rafał would be there on Wednesday and I would be there on Thursday. Unfortunately, our plans didn't work out again for health issues. This time it was Rafał who got sick and missed the conference.

Read the whole article

Comments

Visit Us at 33rd Degree in Warsaw

33rd Degree, an annual Java conference starts tomorrow in Warsaw. OneWebSQL will be there as well. Visit us at the e-point booth to see live demonstrations of OneWebSQL, share your comments and thoughts on OneWebSQL and win our gadgets. We can't wait to meet you! The conference is on March 13-15, 2013. We'll be there on Wednesday and Thursday (not on Friday).

Read the whole article

Comments

Database Modeling Tip: How to Store Passwords in a Database

Today I will talk about how to store passwords in your database. This post is addressed to both programmers, regardless of the language they use, and database architects.

Read the whole article

Comments

OneWebSQL Is Going Mobile

Yes. We are implementing support for iOS and Android platforms. As always, we eat our own dog food first, and then finalize the product. Our customers can be assured that they are buying a battle proven product. …

Read the whole article

Comments

SQL Course - Part 6. Selecting Columns

If you need a reminder on how to set up the environment for this course, see the Environment and Basic Select posts.

As you know, SQL is a language to select data. It is a common situation that only some columns of a table are of interest, not all of them. For example, you want to know the titles of books in the database, and you don't care about publication year or number of pages. Run this query:

Read the whole article

Comments

News: Educational and Non-Commercial Licenses

Recently, we've released Educational and Non-Commercial Licenses for OneWebSQL.

Educational (Academic) License

OneWebSQL's Educational License is designed for students and academic institutions.

Read the whole article

Comments

Find Out What's Happening in Your PostgreSQL Database

So you want to monitor the behavior of your PostgreSQL database. Great! Let's start with a brief overview of how PostgreSQL collects statistics.

PostgreSQL has a set of statistics access functions, as well as a set of predefined statistics views. The views use the predefined statistics functions.

By default only a small number of statistics are collected. The statistics collection is controlled by the following configuration parameters:

Read the whole article

Comments

What's Up, Dear Reader?

I started thinking about this post entry. What subject should I cover? In the previous few posts I've started writing with a season theme: summer, fall or winter. I just realized that we've got this blog for 6 or 7 months up and running. This time I want to start with something different. The question comes to my mind. What's up, dear reader? I know you are there. I know you're reading this. I can't say I can hear your breath, but I can see your browser activity. I've checked a HTTP log file, clever me :)

Read the whole article

Comments

Java Generics: What Beginners Find Surprising

Java generics were introduced in 2004 with Java 5. It has been around for eight years now, but Java generics still pose problems for experienced developers and newcomers alike. Beginners often find Java generics to be counterintuitive. I think it must be difficult to learn Java generics if you don't have the pre-generics perspective first. It's hard to understand some of Java generics' limitations if you don't have a firm grasp of Java code without generics. Experienced developers often have only a rough idea of what Java generics do. They don't want to dig into the details and are often surprised by generics behavior. Today we'll take a look at some of those surprises.

Read the whole article

Comments

Filling the database with the test data

You have database schema. You have generated Java code (by OneWebSQL, of course). You have started developing an application. You're missing something -- the data in the database. Your database is empty. There are only tables, no rows.

Read the whole article

Comments

Database Modeling Tip: Color Your ERD Diagrams

In real-world applications, a database model can have a few hundreds of tables and views. How can you make such a diagram more readable? A solution is to color the entities in the diagram.

Read the whole article

Comments

How to Color ERD Diagrams in PowerDesigner

If you wish to color your ERD Diagrams, here is how you can do it in PowerDesigner.

Read the whole article

Comments

How to Color ERD Diagrams in Oracle Data Modeler

If you wish to color your ERD Diagrams, here is how you can do it in Oracle Data Modeler (aka Oracle SQL Developer Data Modeler).

Read the whole article

Comments

How to Color ERD Diagrams in ERwin

If you wish to color your ERD Diagrams, here is how you can do it in ERwin.

Read the whole article

Comments

How to manage DAOs in a real system

Every example in our documentation is quite simple. There are few DAOs in the code. In these examples each DAO is created in a standard Java way by calling the constructor, as shown here:

Read the whole article

Comments

How to Crash Your IDE Using Java Wildcards

In this post I will show you three ways to crash your IDE using Java wildcards. If you are impatient, just download the file InstantCrash.java, open it in your IDE and compile.

Read the whole article

Comments

How to Succeed When Decorating a Tree

Today I will talk about how hanging something on a (Java) tree can unexpectedly fail.

Suppose we have a class Bauble, with equals() and hashCode() methods properly in place.

Read the whole article

Comments

OneWebSQL is not so young

Let's face facts. OneWebSQL is not as young as you may think. It was born when the first Internet bubble which was called "Web 1.0" collapsed. Now that we've had Web2.0 for some time, OneWebSQL is a fully grown product.

Read the whole article

Comments

SQL Course - Part 5. On Nothing

If you need a reminder on how to set up the environment for this course, see the Environment and Basic Select posts.

Sometimes you don't know what to enter as a column value; for example, you don't know the publication year or the number of pages of a certain book. SQL has a special value to handle just that: NULL. NULL means "no data".

Read the whole article

Comments

Maintenance - the bitter side of life

Let's assume that it's 1012 now. One thousand years ago. Fall has come. Winter is ready at the starting gate. I'm preparing to survive the winter. I will be eating what I gathered during summertime. Enjoyment in over. The new will be limited. I'll have to rely on the fruits of my summer work.

Read the whole article

Comments

How to List All Tables and Describe Tables in Oracle, MySQL, DB2 and PostgreSQL

You often want to list all tables in a database or list columns in a table. Obviously, every database has its own syntax to list the tables and columns. Well, here it is -- all in one place for the most popular databases.

Read the whole article

Comments

OneWebSQL tips: seeing is believing

This is the first post in a new category called "OneWebSQL tips". In this category, we are going to show you some nice features of our product. Just some tricks and tips that we hope that you enjoy.

Read the whole article

Comments

OneWebSQL Team at JDD 2012

JDD is an annual Java conference organized every fall in Kraków, Poland, since 2006. This year it was held on October 25-26. As usual, e-point, the company where OneWebSQL was born, grew up, and become a product, was a sponsor of the conference; and we had a booth to promote OneWebSQL, L10n and the company in general. There were three of us: Ania from the marketing department, and Rafał and Agnieszka from the OneWebSQL Team.

Read the whole article

Comments

How to Quickly Start Using OneWebSQL

Many of you complain that it's difficult to start with OneWebSQL if your system is already running. If you have a DDL file that creates the database, here's what you can do.

Read the whole article

Comments

How to Balance in a Non-Orthogonal World

If you ask a random developer, how many concurrent users the application will handle, she/he will probably answer, I don't know, I think it is limited by something in my applications server, or maybe by the database. Then the developer will probably use jmeter or ab or similar utility, and give an answer. Will you take it seriously? If you do, then yes, you're in trouble.

Read the whole article

Comments

SQL Course - Part 4. Selecting in SELECT queries

In the previous post, we've learned how to select all rows from a table. However, most of the time you want to really select data in an SQL query. This means you have to be able to specify some criteria.

Read the whole article

Comments

Power vs Control

I'm a dirt bike racer, just for a few years. There is common myth among bikers who start racing. They buy big, powerful bikes; I mean most powerful in terms of engine's horsepower. In the beginning, a big bike makes you smile; it simply gives you a feel of power.

Read the whole article

Comments

SQL Course - Part 3. Selecting All Rows

Finally, after getting to know the history of SQL language and setting up the environment, we'll write our first SQL query. […] The database we've created is a very simple book library. There are four tables: […]

Read the whole article

Comments

For or Against the Nature of Things

Recently, I had a chance to develop a brand new web application -- a modern one, mostly a client side application. I've come back to the basics, and attempted to re-learn the JavaScript again. What does that this mean? […]

Read the whole article

Comments

SQL Course - Part 2. Environment

Today is the second installment in our series of posts on SQL. You may want to read "Part 1. Introduction" before you read this post. […] The basic architecture of a database is shown in the following diagram.

Read the whole article

Comments

Don't gloss over the database!

I think I'm getting old. I've been thinking about what to write for these articles, and instead of focusing on the database, on the hard stuff, I find myself thinking about the Java youngsters and what I can teach them. I'll be the old man teaching young ones how the classic database is worth their interest. Quiet please, the Guru is speaking now ;).

Read the whole article

Comments

How to Implement the equals() Method

Quoting Javadoc for equals() method: The equals method implements an equivalence relation on non-null object references. […] If your equals() method does not satisfy the requirements, horrible things can happen because you no longer have this nice partitioning. This can lead to bugs that are very subtle and very tricky to debug.

Read the whole article

Comments

Finding Your DB2 Version

Do you know how to determine what version of DB2 you're using? It's not intuitive. […] There are a couple of methods you can use to determine the version of DB2. Why not just learn one?

Read the whole article

Comments

Implementing equals() and hashCode()

Let's begin with a puzzle. What is the output of this program? [&helip;] Why? What happened? Well, it's one of the most common Java mistakes.We violated the fundamental requirement for the hashCode() method.

Read the whole article

Comments

OneWebSQL and Maven 1.x

OneWebSQL supports Maven 2.x out of box. But a few weeks ago, one of our clients sent us a question: "I don't wanna migrate to Maven 2, do you support Maven 1?" Hm, we thought, the older Maven is retired, it's still in use. Let's see how we can get this done.

Read the whole article

Comments

SQL Course Table of Contents

Links to all SQL Course posts.

Read the whole article

Comments

SQL Course - Part 1. Introduction

Today we're starting a series of posts on the SQL language.

SQL (Structured Query Language) is a language for accessing data in databases. Informally, the word "database" has two meanings:

Read the whole article

Comments

NoSQL - Do I Really Need It?

From time to time, Something New appears on the horizon. Sometimes it's been designed by a committee, sometimes by a group of astronaut architects. Sometimes I reject it by default, if it just makes me stupid, like EJB for example. But sometimes I come across something different, something that makes me think differently. Git, for example, totally changed my outlook on version control. I like paradigm shifts, especially when they make my life easier.

Read the whole article

Comments

How to Handle Exceptions in JDBC

Before we can understand the exceptions a segment of code might throw, we have to have a good understanding of what it does. So let's quickly review what happens in a standard JDBC operation.

The basic scheme of any JDBC operation is pretty straightforward: …

Read the whole article

Comments