- Check the type in compile time
a. Simple example of code
ArrayList<Tv> tvList = new ArrayList<Tv>();
tvList.add(new Tv());
tvList.add(new Audio()); // compile error
- To catch a runtime error in advance, applied
Tv
objecte name intoArrayList
so that compiler will detect the error of code prior to run it.
ArrayList<Tv> tvList = new ArrayList<Tv>();
tvList.add(new Tv());
Tv t = tvList.get(0);
// TV t = (Tv) tvList.get(0); not necessary to the type casting
- The type of reference variable should be equal to its constructor. For example,
ArrayList<Tv> list = new ArrayList<Tv>() ; // OK
ArrayList<Product> list = new ArrayList<Tv>() ; // Error
- Polymorphism of generics
List<Tv> list = new ArrayList<Tv>() ;
List<Tv> list = new LinkedList<tv>() ;
- List is the parent of ArrayList and LinkedList
-
Another features of
Generics
in Javaa. Iterator
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
...
Iterator <Student> it = list.itrator() ;
while(it.hasNext()){
Student s = it.next() ; // (Student)it.next() is not required to transfer the type
}
HashMap<String, Student> map = new HashMap<String, Student>() ; // new HashMap<> () is possible.
public class HashMap extends AbstractMap {
...
public Student get(Object key) { ... }
public Student put(String key, Student value) { ... }
public Student remove(Object kye) { ... }
...
}
For HashMap <Key, Value> , it applies diferent types in
<>
-
By
extends
, java can assign the type from parent to children types. -
For example,
class FruitBox< T extends Fruit > { ArrayList<T> list = new ArrayList<T> () ; ... } FruitBox<Apple> appleBox = new FruitBox<Apple>() ; // Allowed FruitBox<Toy> toyBox = new FruitBox<Toy>() ; // Error interface Eatable {} class FruitBox<T extends Eatable> { ... }
Exception
is a run-time error. It consists of IOException, ClassNotFoundException, RuntimeException and so on.- Inside
RuntimeException
, there are several errors such asArithmeticException, ClassCastExceoption,NullPointerException
and so on.