-4

Question: If you have a List and it has String objects, which declaration(s) of your List does not require that objects retrieved using the get method be cast to Strings, before calling a String method? List <Object> a = new ArrayList <Object>();

I.  List<Object> a = new ArrayList <Object>(); 
II. List<String> a = new ArrayList <String>(); 
III.List a = new ArrayList(); 

I don't really understand this question. I think you must cast to a String to use it as a String, then it must be a declaration that does not return a String object as a String.

liungsdge
  • 1
  • 2
  • 6
    You should read more about [Java Generics](http://stackoverflow.com/questions/490091/java-generics) – Volune Aug 15 '14 at 13:38
  • 1
    Not that it matters here but generally if you are creating reference you should prefer interface as a type not class implementing it, so it should look more like `List list = new ArrayList();` – Pshemo Aug 15 '14 at 13:41

4 Answers4

2

Here's how you should think about the answer: What does each of the following return?

I. and III. are the same thing. Both instances will return a java.lang.Object if you call get. You'll have to cast that to a java.lang.String in order to use it.

Only II. will return a String if you call get, because of the generic declaration.

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

2 will not require explicit casting. 1 and 3 are effectively the same thing.

NRJ
  • 1,064
  • 3
  • 15
  • 32
0

The second one.

ArrayList<String> a = new ArrayList <String>(); 

This means that the arraylist can only hold string type variables. It says string in the pointy brackets. This is called generics and it allows the data you take out to be of the form you specify, in this case a String.

0

I. and III both are a list of Objects (and I. has a typo on the declaration, the correct class type is "Object"). You can store anything in them, including Strings, but as far as the compiler can tell... they're of type Object, so if you want to call a String method on an object you retrieved with the ArrayList.get(...) method you will have to cast the returned object to String.

II. is a list of Strings (the type of stored objects is specified by the generics part between <...>), the compiler knows the ArrayList will only store Strings, so the ArrayList.get() will return a String directly, without the need for a cast.

You can see an example of this exact thing in the Java Generics Tutorial.