【发布时间】:2014-09-15 08:02:33
【问题描述】:
我正在寻找某种可以同时满足这两个要求的集合数据结构:
- 已排序
- O(1) 查找
这是我目前得到的,但我真的希望有一个现有的、不那么尴尬的数据结构。
/**
* This MUST support both
* (1) Looking up by A - O(n)
* (2) Iteration by sorted Foo<A, B>
*/
public class MySet<Foo<A, B>> extends TreeSet<Foo<A, B>>
{
private Map<A, Foo<A, B>> temp = new HashMap<A, Foo<A, B>>();
public Foo<A, B> getNode(A a)
{
return temp.get(a);
}
@Override
public boolean add(Foo<A, B> foo)
{
temp.put(foo.getA(), foo);
return super.add(foo);
}
}
而我的Foo 类看起来像这样:
public class Foo<A, B>
{
private A a; //Can NEVER be null
private B b; //Can NEVER be null
//... constructor and stuff omitted
public int compareTo(Foo<A, B> that)
{
if (this.equals(that))
return 0;
//Compare by a first
int ret = this.a.compareTo(that);
if (ret == 0)
return 0;
//Compare by b
return this.b.compareTo(that.b);
}
public boolean equals(Object obj)
{
if (!(obj instanceof Foo))
return false;
Foo rhs = (Foo) obj;
return this.a.equals(rhs.a) && this.b.equals(rhs.b);
}
}
更新:
这是我的套装的一个用例:
MySet<Foo<SomeA, SomeB>> mySet = getTheData(); //getTheData() returns a set with a bunch of Foo objects
SomeA a = getA(); //getA() returns some instance of SomeA that I'm interested in
我希望能够检查集合并检索 Foo 对象(如果存在),这样 Foo.getA() == a;
mySet.getNode(a);
【问题讨论】:
-
为什么 O(log n) 查找不可接受?这已经相当快了。
-
实际上,这是可以接受的,但是,我将如何从 TreeSet 中即时检索一个值?我希望能够通过 foo.getA() 进行查找,而不仅仅是检查树以查看元素是否在其中。
-
你会使用 TreeMap。但是您需要通过
A查找和按Foo<A, B>排序的迭代?那么无论如何都有两个结构没有好办法。 (您可以将一个哈希表和一个排序集混合在一起,但这会是很多讨厌的工作,而且可能效率不高)。 -
按
A查找和按Foo<A, B>排序的迭代正是我所需要的!是的,我认为这需要大量将多个数据结构混合在一起。 -
好吧,如果您不经常插入,只需保留一个单独的哈希图和二叉搜索树。如果您经常插入,树集将成为瓶颈,您将不得不忍受每个操作的 Omega(log n)。
标签: java algorithm data-structures hashmap treemap