【发布时间】:2013-04-17 20:26:48
【问题描述】:
Java 中是否有一个集合,它的“put”方法返回它为对象提供的自动索引,以便及时检索/删除它?
【问题讨论】:
标签: java data-structures collections
Java 中是否有一个集合,它的“put”方法返回它为对象提供的自动索引,以便及时检索/删除它?
【问题讨论】:
标签: java data-structures collections
所有的 java.util.Map 类都包含一个put(K key, V value) method,它允许您提供一个密钥,以后可以通过该密钥检索对象。
【讨论】:
你可以用你自己的扩展包裹HashMap。您可以安全地从中删除元素,其余元素将保留其索引。
class MyHashMap<T> {
int index = 0;
HashMap<Integer, T> internalMap = new HashMap<>();
public int add(T t) {
int temp = index++;
internalMap.put(temp, t);
return temp;
}
}
如果您需要它是线程安全的,则使用 AtomicInteger 表示 index 和 ConcurrentHashMap 表示 internalMap。
【讨论】:
在向其添加(即add(element))元素后,您始终可以调用List 的size()。您仍然必须将返回的值减 1 才能获得元素的索引。
【讨论】:
list.indexOf(element)
equals() 方法,因此如果查找同一对象的另一个实例,您仍然可以在列表中找到它。因为java中的2个不同的对象实例在逻辑上可能仍然引用同一个对象(即相同的id,相同的用户名..等)
取决于您使用的集合。大多数集合会给你一个布尔值作为回报,告诉你元素是否被添加到集合中。但是由于有许多集合没有任何特定的顺序(并且在处理集合时该顺序可能会改变),因此索引将不再正确。
如何检索索引的一些示例:
// ArrayList, LinkedList (they put the new element at the end of the list)
list.add(myElement);
int index=list.size()-1;
// LinkedList , Stack... (with "push" the new element will be put at the beginning of the list)
list.push(myElement);
int index = 0;
如果集合有索引(不是映射),那么您可以通过调用检索该索引
int index = myCollection.indexOf(myElement);
编辑我忘了补充,这需要通过覆盖equals(Object o) 来实现相等性测试。 (谢谢 Muhammad Gelbana)/edit
这实际上是确保索引是正确的最安全的方法,即使集合发生了变化。
但当然有太多不同的集合具有不同的目标,以确定如何检索索引。例如。地图通常没有索引,而是您必须自己提供的“键”。
您当然可以创建自己的集合并确保始终拥有正确的索引。要么按照已经建议的方式实现map,要么使用数组:
public class MyCollection{
private E[] array;
public MyCollection<E>(){
array = new E[0];
}
public int put(E element){
// create a new array that can hold one more element
E[] copy = new E[array.length+1];
// copy the old array into a new array
int i=0;
for(;i<array.length;i++){
copy[i] = array[i];
}
copy[i]=element;
return i;
}
}
【讨论】: