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())
        } catch (Exception e) {
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);

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Зареєструйся Зараз
або Підпишись на майбутні тести