In Java, variable type restrictions can only be present in a declaration of type Variable, right?

Can variable type restrictions only appear in declarations of classes, interfaces, methods, and constructors?

Or can you bind 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?
}
+3
source share
3 answers

The Java Language specification seems to agree with you:

A type variable (ยง4.4) is an unqualified identifier. Type variables are introduced by the general declaration class (ยง8.1.2), the general interface declarations (ยง9.1.2), the declarations of generalized methods (ยง8.4.4) and the generic declaration constructor (ยง8.8.4).

+2
source

:

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);
  }};
}

"" "" "" . ; "" , .

, - :

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

"T" - " ".

+2

Yes. Type boundaries are applied in the declaration of a type variable.

In other words, when Type Variable first appears.

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
   } 

}
+1
source

Source: https://habr.com/ru/post/1787294/


All Articles