Add object to ArrayList at specified index

前端 未结 14 1343
南笙
南笙 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:51

    How about this little while loop as a solution?

    private ArrayList<Object> list = new ArrayList<Object>();
    
    private void addObject(int i, Object object) {
        while(list.size() < i) {
            list.add(list.size(), null);
        }
        list.add(i, object);
    }
    ....
    
    addObject(1, object1)
    addObject(3, object3)
    addObject(2, object2)
    
    0 讨论(0)
  • If you are using the Android flavor of Java, might I suggest using a SparseArray. It's a more memory efficient mapping of integers to objects and easier to iterate over than a Map

    0 讨论(0)
提交回复
热议问题