What is the difference between add() and set() in List ?

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.

Example:
import java.util.*;
class demo
{
public static void main(String[] args){
ArrayList al=new ArrayList();
al.add("bhabani");
al.add("bbc");
al.add("atul");
al.add("khan");
al.add("ghosh");
al.set(3,"arvind");
System.out.println(al);

}
};
Output:
[bhabani, bbc, atul, arvind, ghosh]

No comments:

Post a Comment