In Java 1.4, there was no resource for Generics. This feature was implemented from Java 1.5 (officially called Java 5).
Although you’re not noticing, the compiler is doing it this way:
- Install an Arraylist of Object and assign the variable list.
- Add a String to list
At this point, the cast is not needed because String is an instance of Object also (Any class that does not extend another class declaratively by the word extends, will automatically extend Object])
- Take the Object of list at her 0 position and print.
Although you are imagining that you are calling System.out.println(String), you are actually calling System.out.println(Object), which will internally make System.out.println(Object.toString())
- Here, you’re trying to pick up an object from list of Object and trying to assign to a String directly.
It can not, for though all String be a Object, not always all Object will be a String. In order for you to be able to do this assignment, you will need to talk to the compiler who takes the risk, making a cast:
String s = (String) list.get(0); // eu assumo o risco
If you want to declare a String List, from Java 5, you can use generrics to solve your problem (don’t forget to look at the javadoc of the List class):
List<String> strings = new ArrayList<String>();
strings.add("hello");
String hello = strings.get(0); // ok, strings é uma List<String>.
In java 5, if you try to declare a List without assigning a generic parameter, it will assume that it is a List to maintain Java 1.4 compatibility.
Useful links:
Hierarchy of the Object class