java - 一旦删除了 ArrayList 中的某些对象,如何访问其中的特定对象?

标签 java arraylist

我有一个对象的 ArrayList(我们称之为 SampleObjects),然后我随机删除一些对象。下面是一些简化的代码来说明我的意思:

ArrayList<SampleObject> sample = new ArrayList<SampleObject>();
sample.add(new SampleObject); //call this object A, current index 0
sample.add(new SampleObject); //call this object B, current index 1
sample.add(new SampleObject); //call this object C, current index 2

如果我删除对象 B 样本.删除(1);

这导致对象 C 现在的索引为 1。稍后我怎样才能具体引用对象 C 呢?如果我有一个大的 ArrayList,我能想到的唯一解决方案是创建一个跟踪示例 ArrayList 中当前索引的数组。有更好的解决办法吗?

最佳答案

我认为您正在寻找 Map 。然后您可以通过某个键检索项目。

根据评论更新,用户:@DwB

The key of the map can be an Integer, so you could refer to A by "0", B by "1", and C by "2". C would still be "2" after deleting element B

希望有帮助。

关于java - 一旦删除了 ArrayList 中的某些对象,如何访问其中的特定对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18856778/

相关文章:

java - java中字符串数组到数组列表的问题

java程序无法在系统中创建文件夹,为什么?

java - Jenkins 的代码覆盖率

java - 如何使用注释将 struts2 Action 的实例化委托(delegate)给 spring

java - 每个 Namedcache 的 Coherence 分布式缓存过期

java - 创建一个 ArrayList,每个值都有一个 hashmap

java - Android:AsyncTask 可以重新创建自己吗?

java - 将数组列表存储在作为该数组列表一部分的对象中

java - 如何在 spring <form :input>? 中显示从数据库获取的值

java - 在从sql数据库列表中检索到的新记录中添加