Did you know that:
- classes used as generic type parameters possibly have nothing to do with each other.
public class Store<T>{...}
Store<Candy> candyStore = new Store<>{};
Store<Animal> animalStore = new Store<>{};
- Type erasure is removing the generics syntax from your code at compile time.
public static <E> boolean containsSomeThing(E [] listOfThings, E someThing){
for (E e : listOfThings){
if(e.equals(someThing)){
return true;
}
}
return false;
}
Compiles To:
public static <E> boolean containsSomeThing(E[] listOfThings, E someThing) {
Object[] var1 = listOfThings;
int var2 = listOfThings.length;
for(int var3 = 0; var3 < var2; ++var3) {
E e = var1[var3];
if (e.equals(someThing)) {
return true;
}
}
return false;
}
- a generic interface can be implemented in 3 different ways:
public interface Eatable<T>{
void eat(T t);
}
//Food class that only works with apples
class Food implements Eatable<Apple>{
public void eat(Apple a){}
}
//Food class that allows to specify the generic parameter
class Food<U> implements Eatable<U>{
public void eat(U t){}
}
//Not using generics (compiler warning)
class Food implements Eatable{
public void eat(Object t){}
}
- you CANNOT:
- call new T() cause that would be creating a new Object()
- do
private T[] e = new T[10]; - use a primative type as type parameter cause these are not objects
- call instanceof because it after compilation List<Animal> looks the same as List<Boats>
- this code will not compile because line 4 breaks the promise of adding Doubles:
List<Double> doubles = new ArrayList<>();
doubles.add(new Double(1.1));
List<Object> objectes = doubles;
objects.add("a string");
- this code won’t either because java does not know the type of the lions List when trying to add a new lion or cat:
static class Lion extends Cat {}
static class Cat {}
public static void min(String... args){
List<? extends Lion> lions = new ArrayList<Lion>();
lions.add(new Lion());
lions.add(new Cat());
}
If you want to dive into Java Generics challenge yourself by understanding this blog on Generics and Java8.