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

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

问题描述

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

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<object> list = new ArrayList<object>();

我有一些要添加的对象,并且每个对象都必须位于特定位置.然而,它们必须以每种可能的顺序添加.当我尝试这个时,它不起作用,我得到一个 IndexOutOfBoundsException:

I've got some objects I want to add and each object has to be at a certain position. It is necessary however that they can be added in each possible order. When I try this, it doesn't work and I get an IndexOutOfBoundsException:

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

我所尝试的是用 null 填充 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?

推荐答案

你可以这样做:

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天全站免登陆