About generics

Arrays in Java have always been type-safe : for example, an Array declared as type String (String []) cannot accept Integers (or ints) or anything other than Strings. But before Java 5 there was no syntax for declaring a type-safe collection (it was like List myList = new ArrayList() ). And with no way to specify a type for collection, the compiler could not enforce you to put only things of the specified type into the collection. As of Java 5, we can use generics, though they aren’t only for making type-safe collections, think of collections as the overwhelming reason and motication for adding generics to the language.

Generics enforce the type of collections. For example:

List<String> myList = new ArrayList<String>();
myList.add("Fred"); // OK, it will hold Strings
myList.add(new Dog()); // compiler error!

In generics the type of the variable declaration must match the type you pass to the actual object type. Subtypes and supertypes are not accepted. These are wrong:

List<Object> myList = new ArrayList<Jbutton>(); // NO!
List<Number> numbers = new ArrayList<Integer>(); // NO!
// remember that Integer is a subtype of Number

And these are fine:

List<JButton> bList = new ArrayList<JButton>(); // yes
List<Object> oList = new ArrayList<Object>(); // yes
List<Integer> iList = new ArrayList<Integer>(); // yes

Polymorphism does not work for generics as it does for arrays. With arrays you are allowed to do this:

import java.util.*;
class Parent { }
class Child extends Parent { }
public class TestPoly {
public static void main(String[] args) {
Parent[] myArray = new Child[3]; // yes
}
}

which means you’re also allowed to do this:

Object[] myArray = new JButton[3]; // yes

but this is not allowed:

List<Object> list = new ArrayList<JButton>(); // NO!

Leave a Reply

Your email address will not be published. Required fields are marked *