insert into list java code example

Example 1: java insert into arraylist

ArrayList<Integer> str=new ArrayList<Integer>();
str.add(0);
str.add(1);
 // Result = [0, 1]
    
str.add(1, 11);
 // Result = [0, 11, 1]

Example 2: insert element into arraylist java

ArrayList<String> arrayList = new ArrayList<>();
// Adds element at the back of the list
arrayList.add("foo");
arrayList.add("bar");
// Result = ["foo", "bar"]

// Adds element at the specified index
arrayList.add(1, "baz");
// Result = ["foo", "baz", "bar"]

Example 3: insert data into list java

List<String> list = new ArrayList<String>();
list.add(s1);
list.add(s3);
list.add(1, s2);
System.out.println(list);

Tags:

Java Example