Java Raw Type and generics interaction

All three are perfectly legal, since there is no actual runtime difference between a Stack and a Stack<Integer>, but all three will result in compiler warnings.

Stack<Integer> s = new Stack()

This will result in an “unchecked conversion” warning, because it’s not safe in general to convert a raw type to a parameterized type. However, it’s perfectly safe to do so in this case: pushing Integer values will not cause any errors; pushing non-Integer values will cause a type error.

Stack s = new Stack<Integer>()

This is a legal conversion from a parameterized type to a raw type. You will be able to push value of any type. However, any such operation will result in an “unchecked call” warning.

Stack s = new Stack()

Again, this is legal, with no implicit conversion. You will be able to push value of any type. However, any such operation will result in an “unchecked call” warning.

You may also get a “raw type” warning any time you refer to the type Stack.

Leave a Comment