Sunday 1 November 2015

How to add element in ArrayList



You can add either a single element or a group of elements to the list.

      1)      Adding Single Elements

There are two varieties of the add() method to add a single element to the list .

    public boolean add(Object element)  
    public boolean add(int index,Object element)  

When called with only an element argument, the element is added to the end of the list. When add() is called with the both element and index arguments, the element is added at the specific index and any elements after it are pushed forward in the list.

For example:-

 List list=new ArrayList();  
 list.add(“a”);  
 list.add(“b”);  
 list.add(“c”);  
 list.add(1,“d”);  

Note:- Like Array, the index used by a List starts at zero.

Since all lists are ordered, the elements are held in the order in which they are added.Unless and until ,you specify the position to add the element as in list.add(1,“d”).
      
      2)      Adding Another Collection

You can add a group of elements to a list from another collection with the addAll() method:

    public boolean addAll(Object element)  
    public boolean addAll(int index,Object element)  

Each elemtn in the collection passed in will be added to the current list via the equivalent of calling the add() method on each element. If an index is passed to the method call, elements are added starting at that position, moving existing elements down to fit in the new elements. Otherwise, they are added to the end.

Note:- In both the cases, if list is read only, then an UnsupportedOperationException will be thrown.


Happy Learning J

No comments:

Post a Comment