I recently finished an online course in AP Computer Science (Java) and on the final exam there was a question that went something like this:
Which of these needs a
String
cast to useString
methods on it:
I.ArrayList a = new ArrayList();
II.ArrayList<Object> b = new ArrayList<Object>();
III.ArrayList<String> c = new ArrayList<String>();
Something about this confused me: can option I
ever even be able to be casted? It has no generic definition so, unless the Java compiler defauted to ArrayList<Object>
, what class is E
then?
This is my test code (the suppress comments are needed because this is an "unchecked" operation):
ArrayList a = new ArrayList();
@SuppressWarnings("unchecked")
a.add(new Object());
@SuppressWarnings("unchecked")
a.add(new String("test"));
@SuppressWarnings("unchecked")
a.add(null);
System.out.println((String)(a.get(0)));
No matter what is in the arguments for the add()
method, it always gives the compiler error:
test.java:14: error: <identifier> expected
a.add(new Object());
^
If I try to add an identifier anywhere on the code (e.g.: a<Object>.add(new Object())
) it gives the exact same error as before.
The question is what is actually happening when no parameter is passed to the generics parameter and can anything be added to this list in the first place, let alone cast into another object? Thanks in advance!