Generic classes

  • Generic types
    • Advantage

Generic types

Generic types are classes or interfaces that are useable with different classes. Instantiation of these types are done with an extra type parameter.

public class ArrayList<E> extends ClassX { ... }
// <E> id class definition is called type parameter
// ClassX is a restriction which (sub)class is accepted

ArrayList<String> lijst = new ArrayList<String>();
// ArryList<String> is called parametized type of generic class ArrayList
// the 'new' ArrayList<String> is called actual typeparameter

Example

public interface MyList<E> {
  public boolean has(E e);
  public int myListSize();
  public boolean isEmpty();
  public E get(int index);
  public void removeFrom(E e);
  public void addtoMe(E e);
  public void delete();
}

public abstract class ShapeList implements MyList<Shape> {
  public float getSurface() {
    float surface = 0.0;
    for (int i = 0; i < myListSize(); i++) {
      Shape s = get(i);
      surface += s.getSurface();
    }
    return surface;
} }
// A generic class delegating functionality to the also generic ArrayList
import java.util.*; 
public class MyCollection<M> extends MyClass> { 

    private ArrayList<M> list = new ArrayList<M>(); 
    private int max; 
    
    public MyCollection(int max) { 
        this.max = max; 
      } 

    public void addElement(M myObj) { 
        if (isFull == false)
          bewoners.add(myObj); 
        } 
      } 
    public boolean isFull() { 
    return list.size() == max; } 
} 

Advantage

The advantage of generic classes compared to e.g. using the most global object class is - no need to use type casting - correct variable type is enforced as e.g. adding an element of wrong type to a generic class will lead to error already during compilation.

List<String> stringList = new ArrayList<String>();
stringList.add("ape");
stringList.add("nut");
stringList.add(new Integer(6)); // compilation error