What will happen after compilation and execution of the following code?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        try {
            ArrayList<Integer> ar = new ArrayList<Integer>();
            List temp = ar; //1
            temp.add(new java.util.Date()); //2
            temp.add(new Float(1.66));
            Iterator it = ar.iterator();
            while (it.hasNext())
                System.out.println(it.next());
            System.out.println(ar.get(0));
        } catch (Exception e) {
            System.out.println(e.getClass());
        }
    }
}
Explanation
The temp collection is not typed, so the temp.add() method runs successfully even for objects of "incorrect" type.

The only case of exception is when during the call to ar collection elements will be casted to Integer type (explicit or implicit cast). There is no such a situation in this example, therefore the loop over collection will be successful.

To avoid adding the 'incorrect' values to the collection, it will be enough to use the verification presenting like this one:

List temp = Collections.checkedList(ar, Integer.class);
Java
Java Quiz
Start Quiz

or Read more about Java Quiz

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback