Question

Type Variables' bounds can only appear in the declaration of classes, interface, methods and constructors?

Or can I bound a type variable when they are used as type arguments?

Edit: Example:

class MyClass<T extends Number> { // T is bounded by the interface Number
    // can a bounded Type Parameter appear anywhere else,
    // besides the Type parameter declaration?
}
Was it helpful?

Solution

The Java Language Specification seems to agree with you:

A type variable (§4.4) is an unqualified identifier. Type variables are introduced by generic class declarations (§8.1.2) generic interface declarations (§9.1.2) generic method declarations (§8.4.4) and by generic constructor declarations (§8.8.4).

OTHER TIPS

Consider this static method:

public static <T> List<T> filter(final List<T> orig, final Predicate<T> pred) {
  return new ArrayList<T>() {{
    for (T t : orig) if (pred.allow(t)) add(t);
  }};
}

The "value" of "T" is "bound" by each call. Now, it's not really bound at the time the method is invoked; it's "bound" at compile time by inspection of the static particulars of each invocation as it appears elsewhere.

Thus if somewhere I call it like this:

final List<Integer> numbers = Whatever.filter(origList, new Predicate<Integer>() {
  public boolean allow(Integer i) {
    return i != null && i.intValue() > 0;
  }
});

then "T" is "Integer".

Yes. Type Bounds are applied in the declaration of Type Variable.

In other words - when Type Variable appears for the first time.

public class MyClass<T extends MyItem> { // <- Type declaration

   private T item; // <-  Type usage

   public <K extends T> K getSubitem() {
   //      ^            ^ 
   //  declaration    usage   
     ...
     Arrays.<K>asList(); // <- Type Usage not a type declaration
   } 

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top