0

Consider this snipped code:

public class MaxSizeHandler extends AbstractValueHandler<Collection> {      
}

and I use eclipse, and It warns me to add infer generic arguments type for Collection and the code changes like this:

public class MaxSizeHandler extends AbstractValueHandler<Collection<?>> {       
}

My question is what's the problem if I don't put it, or what's the advantage if I put it?

Cœur
  • 37,241
  • 25
  • 195
  • 267
AKZ
  • 856
  • 2
  • 12
  • 30

4 Answers4

5

Passing a raw Collection will imply that the Collection is not parametrized, hence you lose the ability to strongly type (i.e. at compile time) what goes in the Collection.

Passing a Collection<?> is not substantially different, as the wildcard will match anything extending Object.

Of course, it will remove the warning.

The best way would be to pass a Collection<MyObject> or a Collection<? extends MyObject>, etc.

Mena
  • 47,782
  • 11
  • 87
  • 106
1

you need to mention Collection type before itself in generic format like below :

public class MaxSizeHandler extends AbstractValueHandler<Collection<? extends T>> {      
}

T-> type of collections Otherwise java compiler will take as default type of collection.

Raju Sharma
  • 2,496
  • 3
  • 23
  • 41
0

Adding the correct type will allow the class to return the correct type of value, is there a specific type of Object your Collection will hold i.e Integer, then use AbstractValueHandler<Collection<Integer>>.

jpdymond
  • 1,517
  • 1
  • 8
  • 10
0

Depending how you're using the MaxSizeHandler class it may make sense to make this class itself generic. For example, if you need to iterate over the collection:

public class MaxSizeHandler<T>
       extends AbstractValueHandler<Collection<? extends T>> {
  public void handle(Collection<? extends T> coll) {
    for(T item : coll) {
      // ...
    }
  }
}

or if you need to add new items to the collection:

public class MaxSizeHandler<T>
       extends AbstractValueHandler<Collection<? super T>> {
  public void handle(Collection<? super T> coll) {
    T item = createAnItem();
    coll.add(item);
  }
}

(These are just toy examples, as you haven't said what kind of methods AbstractValueHandler declares)

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183