Remember erasure ?
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
((List) strings).add(42); // compiler warning - ok at runtime
// String s = strings.get(0); // CCE - Compiler-generated cast
System.out.println("strings: " + strings); // strings: [42]
System.out.println(strings.contains(42)); // true
}
}
In other words:
final HashSet<Integer> hashSet = new HashSet<>();
// Set<String> cast = (Set<String>) hashSet; // error
Set<String> cast = (Set) hashSet; // warning
Remember printing (and varargs) ?
Arrays.toString(map.entrySet().toArray());
as opposed to:
int[] a = { 1, 2, 3 };
System.out.println(Arrays.asList(a)); // \[\[I@70cdd2\] // List<int[]>
Remember generics ?
How to implement an interface with an enum, where the interface extends Comparable?
public interface Foo extends Comparable<Foo> {} public enum FooImpl implements Foo {} // java.lang.Comparable cannot be inherited with different arguments: <Foo> and <FooImpl> // Solution: public interface Foo<SelfType extends Foo<SelfType>> extends Comparable<SelfType> {} public enum FooImpl implements Foo<FooImpl> {}
- Why can’t you have multiple interfaces in a bounded wildcard generic?