It is incorrect:
-using wildcards in type variable declaration, eg.
public <?> void methods() {
....
}
public <? extends T> void methods() {
....
}
public <? super Comparable> void method() {
....
}
- using super:
public <T super Comparable> T get() {
....
}
It is correct:
public <T> T get() {
....
}
public <T extends Comparable> T get() {
....
}
------------------------------------------------------------------------------------------------------------
2. Return types
Notice also that the last example method can return only T - type object.
public <T extends Comparable> T get() {
return (T) new String(""); //correct
}
public <T extends Comparable> T get() {
return new String(""); //incorrect
}
public <T extends Comparable> T get(T t) {
return t; //correct
}
3.
It is correct, int[] is a Object!
List<?> l = new ArrayList<int[]>();
This one is incorrect:
List<?> l = new ArrayList<int>();
------------------------------------------------------------------------------------------------------------
4. Compiler warning is thrown every time one tries to assign non-generic element to generic one.
public static void main(String... s) {
List<Object> l = null;
ArrayList l2 = null;
l = l2; //warning
}
the exception is ? :
public static void main(String... s) {
List<?> l = null;
ArrayList l2 = null;
l = l2; //no warning
}
------------------------------------------------------------------------------------------------------------
5. Cannot create objects using wildcards, eg.:
new ArrayList<?>();
new ArrayList<? extends Number>();
new ArrayList<? super Number>();
new HashMap<String, ? extends Number>();
------------------------------------------------------------------------------------------------------------
6. One has to declare the type before return type and after method modifiers, e.g.:
public static <E> void add(E e) {}
public <E> static void add(E e) {} //incorrect
public static void <E> add(E e) {} //incorrect
Brak komentarzy:
Prześlij komentarz