添加对象的ArrayList的指定索引 [英] Add object to ArrayList at specified index

查看:393
本文介绍了添加对象的ArrayList的指定索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是一个非常简单的问题,但我不知道如何正确地做到这一点。

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

我有一个空的ArrayList

I've got an empty arraylist:

ArrayList<object> list = new ArrayList<object>();

我有一些对象我要添加的每个对象,必须在一定的地位。这是必要然而,它们可在每个可能的顺序来添加。当我尝试这一点,它不工作,我得到一个 IndexOutOfBoundsException异常

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

我曾尝试与填充的ArrayList ,然后做以上。它的工作原理,但我认为这是一个可怕的解决方案。是否有另一种方式来做到这一点?

What I have tried is filling the ArrayList with null and then doing the above. It works, but I think it's a horrible solution. Is there another way to do this?

推荐答案

您可以做到这一点是这样的:

You can do it like this:

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

在Object2的添加到位置2,它会移动object3到位置3。

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

如果你想object3是在POSITION3所有的时间我建议你使用HashMap与立场键和对象的值。

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.

这篇关于添加对象的ArrayList的指定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆