• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generic method  RSS feed

 
Robertovich Wartins
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
question about Generics.
I need to write method, which inserts number in given collection. I can write this method in two ways - what is the the correct way?

//1
public static <E extends Number> void insertThis(
Collection<? super E> collection, E number) {
collection.add(number);
}
//2
public static <E extends Number> void insertThis(
Collection<E> collection, E number) {
collection.add(number);
}
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rob,

the first is correct, the second would not compile.


The first:
would allow only combinations, where the type of the collection is as least as "big" as the type of the number you want to add. It would reject combinations where the collection is too small for the number, for example:

because the <E> in this case would be Number, and Integer (for the collection) is not a superclass of Number.

So the usage of the first is version is ok to add things in the collection.

For the second:

Would (theoretically) allow the combination

And you could add a Number into an Integer collection, that would be too big.

Therefore as a general rule in generics, it is not allowed to add anything (except null) into a collection where the type is defined with a wildcard - just too prevent you from adding big things in small collections.

When you define a collection with the use of super, however, it is allowed too add things into it, because the type that is written after the super is guaranteed to be the smallest possible.
E.g. in a List<? super Number> you can add type Number, but not lower types (Integer, Double...). The compiler would prevent you from adding an Integer and casting it to a Double. Without generics, the compiler would allow this and you'd see your fault only later, at runtime, when a class cast exception is thrown.

Yours,
Bu.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!