Professional Documents
Culture Documents
Generics in 5-Minutes
There is a wayto get around it. i.e. You can pass an ArrayList<Dog> to an
argument of ArrayList<Animal> with some manipulation in generic.
Java 5 onwards we have generics. They aren't only for making type safe
collections but collections as the overwhelming reason and motivation
for adding generics to the language.
By using generics syntax—which means putting the type in angle
brackets <String>, we're telling the compiler that this collection can
hold only String objects.So, now
That what you put IN is guaranteed,
You can also guarantee what comes OUT, and
That means you can get rid of the cast when you get something
from the collection.
The compiler already knows that myList contains only things that can
be assigned to a String reference, so now there's no need for a cast.
You can declare a type parameter for a method argument, which then
makes the argument a type safe
reference:
Dog d = getDogList().get(0);
We can put an Animal and its subtype to List of generic type Animal.
List<Animal> animalList = new ArrayList<Animal>();
animalList.add(new Animal("No Name"));
animalList.add(new Dog("Jimmy A Dog"));
Challenges :
How to deal with legacy code built without generics?
Polymorphism
Type Erasure
At runtime, ALL collection code—both legacy and generics—looks exactly like
the pre-generic version of collections. None of typing information exists at
runtime.Through a process called "type erasure," the compiler does all of its
verifications on your generic code and then strips the type information out of
the class bytecode.
Generic code is strictly for the compiler.
classTestGenerics <T> { }
The <T> is a placeholder for the type you pass in.
T stands for "type", but any valid Java identifier would work here.
Class TestGenerics<T> {
T anInstance;
T[] listofT;
TestGenerics(T anIns){
anInstance = anIns;
}
T getInstance(){
Return anInstance;
}
}
T getInstance(){
returnanimal;
}
}
Generic Methods
It's possible to define a parameterized type (instance of any type) at
a method level,without being class generic.
BURN IT IN MIND :
In order to use a type variable <T>, you must declared it either
As the class parameter type or
In the method, before the return type.
It’s tempting to forget that the method argument is NOT where you
declare the type parameter variable T.