How to insert an object in an ArrayList at a specific position

后端 未结 7 1196
挽巷
挽巷 2020-11-29 22:08

Suppose I have an ArrayList of objects of size n. Now I want to insert an another object at specific position, let\'s say at index position k (is greater than 0 and less tha

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 22:26

    For example:

    I want to move the element from 23th to 1th(index == 0) in the arrayList, so I put 23th element to a temp value, and removing from list, insert it to 1th in list. It's worked, but not more efficient.

     List 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);
            }
        }
    

提交回复
热议问题