Monday, 23 January 2017

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

public class Check {

       public static void main(String[] args) {

              List list = new ArrayList<>();
//If we don't declare the list to be of specific type, it treats it as list of objects.
              list.add(2);
              list.add("2");
              System.out.println(list);
// int 2 is auto boxed to Integer and "2" is String and hence both are objects.
              Iterator iter = list.iterator();

              while (iter.hasNext()) {

                     Object object = (Object) iter.next();

                     System.out.println(object);
                     //output is 2 and 2

              }

       }




 output  will be 
[2, 2]
2
2

No comments:

Post a Comment