Index

Overview


If a class has generic parameters we want to declare the class with parameters.

If we ignore the generics we can get successful compiles, but are chances of runtime errors increase (and the latter are worse).

Let's show some examples.

Variables With Generics


Here is a simple class "GenericFoo" that has a
generic paramter "T".
public class GenericFoo<T> {
	
	private T elem;

	public GenericFoo(T elem) {
		super();
		this.elem = elem;
	}

	public T getElem() {
		return elem;
	}

	@Override
	public String toString() {
		return this.elem.toString();
	}
	
}


Here we incorrectly declare and construct a variable without using generics (we are ingoring the specified generics).
public void useWithoutGenerics()  {
	//Foo has a generic parameter
	//But we ignore it here
	GenericFoo foo = new GenericFoo(10);
	prn(foo);
}

Here we declare and construct the variable correctly. We pass "Integer" to GenericFoo as the generic parameter.
public void useWithGenerics1()  {
	GenericFoo<Integer> foo;
	foo = new GenericFoo<>(10);
	prn(foo);
}

Here we declare and construct the variable correctly. We pass "Integer" to GenericFoo as the generic parameter.
public void useWithGenerics2()  {
	Rectangle rec;
	rec = new Rectangle(10,  5);
	GenericFoo<Rectangle> foo;
	foo = new GenericFoo<>(rec);
	prn(foo);
}



Method Return With Generics


Here we incorrectly declare and construct a variable without using generics (we are ingoring the specified generics).
public GenericFoo getFoo1()  {
	return new GenericFoo(10);
}

Here we correctly declare and construct a variable with using generics.
public GenericFoo<Integer> getFoo2()  {
	return new GenericFoo<>(10);
}



Method Parameters With Generics


Here we incorrectly declare a method parameter without using generics (we are ingoring the specified generics).
public void printFoo1(GenericFoo foo)  {
	prn(foo);
}

Here we correctly declare a method parameter using generics.
public void printFoo2(GenericFoo<Integer> foo)  {
	prn(foo);
}



Utilizing Compiler Warnings


Generic problems are easy to miss. The Java compiler is a good friend that helps to find these problems.

If you are using an IDE, you can have it show you compile warnings (most IDE's do this by default).

If using basic Java, see this to show compile warnings...

Generic warnings may come in different flavors. One common one includes text such as: