How does the Java compiler work?

3

Why does the compiler of Java not be able to guess which type of object to return on the line that will cause compilation error in this program?

import java.util.*;

class Teste {

    public static void main(String[] args) {
        //The following code snippet without generics requires casting
        List list = new ArrayList();
        list.add("hello");
        System.out.println(list.get(0));

        //String s = (String) list.get(0);
        String s = list.get(0);
        System.out.println(s);
    }
}
    
asked by anonymous 24.04.2015 / 03:00

1 answer

3

In Java 1.4, there was no generics feature. This feature was implemented from java 1.5 (which officially came to be called Java 5).

Although you are not aware, the compiler is doing this:

  • Instantiate an ArrayList of Object and assign the variable list .
  • Add a String to the list
  • At this point, the cast is not necessary because String is an instance of Object as well (Any class that does not extend another class declaratively through the word extends will automatically extend Object >])

  • Get the Object of the list that is at position 0 of it and have it printed.
  • While you are imagining that you are calling System.out.println (String), you are actually calling System.out.println (Object), which internally will do System.out.println (Object.toString ())

  • Here you are trying to get an list object from Object and trying to assign a String directly.
  • You can not because String is an Object , not all Object will be a String . In order for you to be able to do this assignment, you will need to speak to the compiler who takes the risk by doing a cast :

    String s = (String) list.get(0); // eu assumo o risco
    

    If you want to declaratively do a String List, from Java 5, you can use genres to solve your problem ( do not forget to look at the javadoc class List ):

    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 compatibility with Java 1.4.

    Useful links :

    Class Hierarchy Object

        
    24.04.2015 / 03:38