Project Management Professional: Core Java Interview Questions!

Tuesday, July 21, 2020

Core Java Interview Questions!


28.Will this code give error if i try to add two heterogeneous elements in the arraylist. ? and Why ?

List list1 = new ArrayList<>();

list1.add(5);

list1.add("5");

Heterogeneous:having widely dissimilar elements

*ArrayList is one of the most flexible data structure from Java Collections. Arraylist is a class which implements List interface . It is one of the widely used because of the functionality and flexibility it offers. It is designed to hold heterogeneous collections of objects

Ans.No, If we don't declare the list to be of specific type, it treats it as list of objects.

int 1 is auto boxed to Integer and "1" is String and hence both are objects.


Example below:


import java.util.List; import java.util.ArrayList; public class ListAdd { public static void main(String[] args) { /* List<String> langs = new ArrayList<>(); langs.add("Java"); langs.add("Python"); langs.add(1, "C#"); langs.add(0, "Ruby"); for (String lang : langs) { System.out.printf("%s ", lang);//PrintStream methods to format the output } System.out.println(); }*/ List list1 = new ArrayList<>(); list1.add(5); list1.add("5"); System.out.println(list1);



No comments: