6

I need your help will you please tell me what difference between add() and set() in ArrayList. I Wrote a program uising set() and add() try to find out try to fing find out what are differences I search on the net but could not find my suitable answer

public class arraylistDemo 
{

    public static void main(String[] args) throws Exception
{

        ArrayList al = new ArrayList();
        al.add(10);
        al.add("A");
        al.add("B");
        al.add(null);


        al.set(0, 11);
        System.out.println("After Add "+""+al);

        al.add(1, "AA");
        System.out.println("Using add method"+ " " +al);

        al.set(1, "AA");
        System.out.println("Using set method"+ " " +al);
    }

}

O/P- Using add method [11, AA, B, null] Using set method [11, AC, B, null]

user1803551
  • 12,965
  • 5
  • 47
  • 74
sud0074
  • 99
  • 1
  • 1
  • 8

2 Answers2

10

From List:

add(E e)

Appends the specified element to the end of this list (optional operation).


add(int index, E element)

Inserts the specified element at the specified position in this list (optional operation).


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


Use a debugger and step one line at a time to see how your list changes. You will see that it does exactly what the Javadoc states.

Community
  • 1
  • 1
user1803551
  • 12,965
  • 5
  • 47
  • 74
7

The add() method adds a value to the end of the list. set() is used to replace an existing value in a specific index in the list.

Ahmed Alzubaidi
  • 109
  • 1
  • 2
  • yaa u r right but please check my code with output both are working same way they replace the value – sud0074 Jan 16 '16 at 20:04