How does the Java compiler work?

Asked

Viewed 145 times

3

Why is the compiler of Java cannot guess which type of object will be returned 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);
    }
}

1 answer

3

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:

  1. Install an Arraylist of Object and assign the variable list.
  2. 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])

  1. 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())

  1. 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.