Java – how to insert objects in an ArrayList at a specific location
Suppose I have an ArrayList of an object of size n Now I want to insert another object at a specific location, assuming that it is at index position K (greater than 0 and less than n) and I want other objects at and after index position K to move forward by one index position So is there any way to do this directly in Java In fact, I want to keep the list sorted when adding new objects
Solution
To insert a value into an ArrayList at a specific index, use:
public void add(int index,E element)
This method moves subsequent elements of the list However, you can't guarantee that the list will remain sorted, because the new objects you insert may be in the wrong position according to the sorting order
To replace an element at a specified location, use:
public E set(int index,E element)
This method replaces the element at the specified location, lists the list with the specified element, and returns the previous element at the specified location