The title is pretty self-explanatory.
Will the raw type of, for example, ArrayList
act the same as ArrayList<Object>
?

- 16,609
- 6
- 58
- 83

- 497
- 9
- 31
-
Define "act the same". Do you mean run-time? Then read about [type erasure](http://docs.oracle.com/javase/tutorial/java/generics/erasure.html). – PM 77-1 Nov 10 '13 at 17:22
-
Generics is a compile time feature. At runtime it makes little difference. – Peter Lawrey Nov 10 '13 at 17:51
2 Answers
Not quite. Take a look at
MyClass myClass1 = new MyClass<Integer>();
//MyClass<Object> myClass2 = new MyClass<Integer>();//compilation error
MyClass<?> myClass3 = new MyClass<Integer>();//this time it compiles
myClass1.setter(1);
//myClass3.setter(1);//compilation error
In case of myClass2
it will not compile because you are declaring reference to holder of Objects
but you are passing holder of Integers
and generics are not covariant
Also if you change <Object>
to <?>
wildcard like in case of myClass3
you wouldn't be able to use its setter with any object (beside null) like myClass3.someSetter(1)
because MyClass<?>
can be reference to MyClass<Anything>
that can hold any type of objects, and passing 1
to holder of Strings
would not be safe.
In terms of method signatures, the erased E
is its bound Object
, so it is ok to say that the raw ArrayList
has member methods similar to ArrayList<Object>
In terms of subtyping, raw type is more like wildcard type; ArrayList
is a super type of ArrayList<x>
for any x
. On the other hand, ArrayList<x>
can be converted to raw ArrayList
without raising any compiler error/warning.
This is all for backward compatibility. You should avoid raw types anyway so you don't need to know these useless information.

- 19,446
- 5
- 33
- 61