Tip of the day #11

Still on Effective Java, If you use raw types, you lose all the safety and expressiveness benefits of generics. So always create List<Declare your object> list and never List list. Catch your errors earlier and not in the execution time.

What is a raw type?

A raw type is the name of a generic class or interface without any type arguments

Let’s imagine a class Vehicle, and a generic class Garage that will receive any type of vehicle.

Garage<Vehicle> garage = new Garage<>();

Garage is the raw type of Garage. But why is it bad to use raw types?

If you use raw types, you lose all the safety and expressiveness benefits of generics.

Garage garage = new Garage();
garage.add("car");

The compiler will not complain about the type of the object that you are adding to the garage, but when you try to get the object from the garage, you will get a ClassCastException.

This still exists for compatibility reasons (long ago - before JDK 5.0), but it is not recommended to use it.

If you want to know more about it, search for generics and type erasure.

To give you an idea, let’s see one example:

List<Integer> list = new ArrayList<>();
list.add(11);
int first = list.get(0);

The compiler will generate the following bytecode:

List list = new ArrayList();
list.add(Integer.valueOf(11));
Integer first = (Integer) list.get(0);

cool, right?

How to

Take a look in repo-tip-10 to see a real example of today’s tip.