Java: Generics

Used when defining a generic class that can be used against several object types. For example ArrayList<String> is an ArrayList of strings. ArrayList<DataSource> is an ArrayList of data sources.

“<>” is known as the diamond operator.

Public class myClass<T>{
	private T id;
	public myClass(T inT){
		this.id = inT;
	}
	public <S> void myMethod(S inS){… }  // methods can have their own generic type
}

By convention:

  • E is an element
  • K is a map key
  • V is a map value
  • N is a number
  • T is a generic data type
  • S, U , V are used after T for generic data types
List<?>Any type. Cannot add entries as cannot be certain of list’s type.
List<? extends myClass>myClass and subclasses. Cannot add entries.
List<? extends Number>could be list of Number or Integer.
List<? super myClass>myClass and superclasses
List<? super String>could be a list of String or CharSequence. Cannot add CharSequence (could be List of String). Can add String or child of String (if it wasn’t final)

Overriding & Generics

Comparing Parameter Checks

Parent class:

public void myMethod(List<String> parm1)

Child class:

public void myMethod(List<String> parm1) → overridding
public void myMethod(ArrayList<String> parm1) → overloading (i.e. does not replace parent)

Comparing Return Types

Parent class:

public List<CharSequence> myMethod()

Child class:

public List<CharSequence> myMethod()  → overridding
public ArrayList<CharSequence> myMethod()  → overridding
public List<String> myMethod()  → compile error