The below example will help you to add new element in arrayList. So, when we have new element list item shifts the element currently at that postion and any subsequent elements to the right which will help to insert new element at the specified postion in this list.
In below example I have created AddNew class and created arraylist, to add new element first I increased the arraylist then added new element and element postion where we require, like in below example I have added new element on second postion. You can see below program it will clearly describe you how to add new element in ArrayList.
public class AddNew{
public static void main(String[]args){
//Create an empty array list with an initial capacity
ArrayList<Integer>arraylist= new ArrayList<Integer>(7);
//use add()method to add element in the list
arraylist.add(10);
arraylist.add(20);
arraylist.add(30);
arraylist.add(40);
arraylist.add(50);
arraylist.add(60);
//adding element 15 at second postion
arraylist.add(1,15);
//print all the elemnets available in list
for(Integer number :arraylist){
System.out.println("Number="+number);
}
}
}
Output-
Number = 10
Number = 15
Number = 20
Number = 30
Number = 40
Number = 50
Number = 60
0 Comment(s)