Add object to ArrayList at specified index

前端 未结 14 1416
南笙
南笙 2020-11-30 18:59

I think it\'s a fairly simple question, but I can\'t figure out how to do this properly.

I\'ve got an empty arraylist:

ArrayList list =         


        
      
      
      
14条回答
  •  自闭症患者
    2020-11-30 19:40

    You can do it like this:

    list.add(1, object1)
    list.add(2, object3)
    list.add(2, object2)
    

    After you add object2 to position 2, it will move object3 to position 3.

    If you want object3 to be at position3 all the time I'd suggest you use a HashMap with position as key and object as a value.

提交回复
热议问题