7

我需要一个集合类,它同时具有:快速索引和散列访问。现在我有 ArrayList。它具有良好的索引访问权限,但他的contains方法性能不佳。HashSet 有很好的contains实现,但没有索引访问。哪个系列两者兼备?可能来自 Apache 的东西?或者我应该创建自己的集合类,它同时具有:用于索引访问的 ArrayList 和用于contains检查的 HashSet?

只是为了澄清:我需要两者get(int index)contains(Object o)

4

4 回答 4

1

如果索引访问性能不是问题,则最接近的匹配是 LinkedHashSet,其 API 表明它是

Set 接口的哈希表和链表实现,具有可预测的迭代顺序。

至少我不认为性能会比LinkedListPerformance差。否则,除了您的 ArrayList + HashTable 解决方案,我别无选择

于 2013-02-22T12:10:04.443 回答
0

我不知道确切的查找时间,但也许你可以使用Map interface的一些实现。你可以用map.put(objectHash, obj).

然后你可以验证你有一个特定的对象:

boolean contained = map.containsValue(obj);

您可以使用哈希在地图中查找对象:

MyObject object = map.get(objectHash);

但是,唯一的缺点是您需要知道此查找调用中的哈希值,这可能不在您的实现中。

于 2013-02-22T13:53:02.433 回答
0

这样做;使用哈希技术和列表的组合来获得两全其美:)

class DataStructure<Integer>{
   Hash<Integer,Integer> hash = new HashMap<Integer, Integer>();
   List<Integer> list = new ArrayList<Integer>();

    public void add(Integer i){
        hash.add(i,i);
        list.add(i);
    }
    public Integer get(int index){
        return list.get(index);
    }
   ...
} //used Integers to make it simpler

所以反对;您保留在HashMap/HashSet以及ArrayList中。

所以如果你想使用

 contains method : call hashed contains method.

 get an object with index: use array to return the value

只要确保你有这两个集合同步。并注意两种数据结构中的更新/删除。

于 2013-02-22T13:05:41.660 回答
0

如果您从头到尾遍历索引,我认为这可能会满足您的需求:LinkedHashSet

如果您需要通过索引和哈希访问进行随机访问,如果没有其他人有更好的建议,我想您可以制作自己的集合,两者兼而有之。

于 2013-02-22T12:02:47.803 回答