Difference between revisions of "Core Java - Collections - Interview Questions and Answers"

(Created page with "===What happens when you compile and run the below program?=== <syntaxhighlight lang="java"> package com.javatutorial.quiz; import java.util.ArrayList; import java.util.Arra...")
 
 
Line 28: Line 28:
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
Output:
 +
 +
<source>
 +
[3,10,3], followed by exception
 +
 +
Arrays.asList() returns a fixed-size list backed by the specified array. Therefore, the arraylist can't grow.
 +
So, when add() is called, an exception is thrown.
 +
</source>

Latest revision as of 09:04, 13 June 2018

What happens when you compile and run the below program?

package com.javatutorial.quiz;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class Quiz38 {
 
    public static void main(String[] args) {
 
        List<Integer> list = new ArrayList<Integer>();
        
        Integer[] arr = {2,10,3};
        
        list = Arrays.asList(arr);
        
        list.set(0, 3);
        
        System.out.println(list);
        
        list.add(1);
        
        System.out.println(list);
    }
 
}

Output:

[3,10,3], followed by exception

 Arrays.asList() returns a fixed-size list backed by the specified array. Therefore, the arraylist can't grow.
So, when add() is called, an exception is thrown.