Java/Maven

Ignoring Java Generics Safety

Java Generics (something like List <String>) provides a very nice way to group similar operation on different types of objects.

There is a way around it though.

In C++ the template invocation actually causes a new instance of the underlying type to be created and compiled. Java only creates the one type instance and then uses the generics as a variable when performing the type checks. Generics allow the compiler to enforce more type safety checks.

More type safety is a brilliant idea and I really like generics, so I have no practical use for this work around to fool the compiler safety checks. Let me know if you find one.


import java.util.ArrayList;
import java.util.Collection;

public class Q1{

	public static void main( String[] args ) {
		
		ArrayList<Integer> is = new ArrayList<Integer>();
		// list is [  ]
		
		is.add(2);
		// list is [ 2 ]
		
		Collection<?> ac = is;
		ac.add( null );
		
		// null is the only value that can be added to the ac list.
		// list is [ 2, null ]		
		
		(( ArrayList<String> ) ac).add("andrejserafim");
		
		// the above will give you an unchecked cast warning, 
		// but will compile and work
		
		// list is [ 2, null, "andrejserafim" ]
		
	}

}

Initially the list is tagged with ArrayList<Integer>.

The cast to Collection<?> wipes off that tag.

Then ArrayList<String> cast writes a new tag onto the list now stating it’s a list of strings.

Standard