Question:
Explain the difference between the add() and set() methods in the ArrayList class in Java. Provide an example code snippet for each method and explain the output.
Answer:
The add() and set() methods in the ArrayList class in Java are used to manipulate the elements of the ArrayList. However, they differ in terms of their functionality and how they modify the elements in the ArrayList.
The add() method is used to add an element at a specific index in the ArrayList. It shifts the existing elements to the right and increases the size of the ArrayList. The syntax for the add() method is:
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add(1, "banana");
System.out.println(list);
Output:
[apple, banana]
In the above example, the add() method is used to add the element "banana" at index 1 in the ArrayList. The existing element "apple" is shifted to the right and the size of the ArrayList is increased to 2.
On the other hand, the set() method is used to replace an element at a specific index in the ArrayList. It does not change the size of the ArrayList but simply modifies the value of the element at the specified index. The syntax for the set() method is:
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.set(1, "orange");
System.out.println(list);
Output:
[apple, orange]
In the above example, the set() method is used to replace the element at index 1 with the value "orange" in the ArrayList. The size of the ArrayList remains the same, but the value of the element at index 1 is modified.
In summary, the add() method is used to insert a new element into the ArrayList, shifting existing elements to the right and increasing the size of the ArrayList, while the set() method is used to replace an existing element at a specific index without changing the size of the ArrayList.