How to insert an object into an ArrayList in a specific place

Suppose I have an ArrayList of objects of size n. Now I want to insert another object at a certain position, say, at the index position k (greater than 0 and less than n), and I want other objects at the index position and after k to move one index position forward. So is there any way to do this directly in Java. Actually, I want to keep the list sorted when adding a new object.

+61
java arraylist
Aug 16 2018-11-11T00:
source share
4 answers

To insert a value into an ArrayList at a specific index, use:

public void add(int index, E element) 

This method will shift the subsequent list items. but you cannot guarantee that the list will remain sorted, since the new object you are inserting may be in the wrong position according to the sort order.




To replace an item at a specified position, use:

 public E set(int index, E element) 

This method replaces the element at the specified position in the list with the specified element and returns the element earlier at the specified position.

+116
Aug 16 2018-11-11T00:
source share

Here is a simple example of an array to insert at a specific index

 ArrayList<Integer> str=new ArrayList<Integer>(); str.add(0); str.add(1); str.add(2); str.add(3); //Result = [0, 1, 2, 3] str.add(1, 11); str.add(2, 12); //Result = [0, 11, 12, 1, 2, 3] 
+36
Jan 03 '14 at 12:48
source share

Actually a way to do this according to your specific question: arrayList.add(1,"INSERTED ELEMENT"); where 1 is the position

+1
May 31 '13 at 5:34
source share

For example:

I want to move an element from the 23rd to the 1st (index == 0) in arrayList, so I put the 23rd element on temp and removing it from the list, insert it into the 1st list. It worked, but not more efficiently.

  List<ItemBean> list = JSON.parseArray(channelJsonStr,ItemBean.class); for (int index = 0; index < list.size(); index++) { if (list.get(index).getId() == 23) { // id 23 ItemBean bean = list.get(index); list.remove(index); list.add(0, bean); } } 
0
Sep 02 '16 at 6:26
source share



All Articles