Tuesday, January 16, 2018

difference between java ArrayList<> add and set method

Below is the example of how the .add and .set method of ArrayList works when using the index & value attribute.

add(int index, E element)
Inserts the specified element at the specified position in this list.
Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

set(int index, E element)
Replaces the element at the specified position in this list with the specified element.


import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
        List<String> listStr = new ArrayList<>();
        listStr.add("1 ");
        listStr.add("2 ");
       listStr.add("3 ");
        listStr.add("4 ");
        listStr.add("5 ");
        listStr.add("6 ");
        listStr.add("7 ");
        listStr.add("8 ");
       
        listStr.forEach(System.out::print);
        List<String> listStr1 =  listStr.stream().collect(Collectors.toList());
        System.out.println("\n *** ADD **** ");
        addAtIndex(listStr1, 5, new String("NewIndxVal "));
        listStr1.forEach(System.out::print);
        System.out.println("\n *** SET **** ");
        List<String> listStr2 = listStr;
         listStr2.forEach(System.out::print);
         System.out.println("");
        setAtIndex(listStr2, 5, new String("NewIndxVal "));
        listStr2.forEach(System.out::print);

     }
    
     public static <T> List<T> addAtIndex (List<T> strList, int idx, T value){
        
         strList.add(idx,value);
        
         return strList;
     }
      public static <T> List<T> setAtIndex (List<T> strList, int idx, T value){
        
         strList.set(idx,value);
        
         return strList;
     }

}

output:
Hello World
1 2 3 4 5 6 7 8 
 *** ADD **** 
1 2 3 4 5 NewIndxVal 6 7 8 
 *** SET **** 
1 2 3 4 5 6 7 8 
1 2 3 4 5 NewIndxVal 7 8