我可以在给定一个对象y的哈希集中检索存储的值x其中x.Equals(y) [英] Can I retrieve the stored value x in a hashset given an object y where x.Equals(y)
问题描述
[TestFixture]
class HashSetExample
{
[Test]
public void eg()
{
var comparer = new OddEvenBag();
var hs = new HashSet<int>(comparer);
hs.Add(1);
Assert.IsTrue(hs.Contains(3));
Assert.IsFalse(hs.Contains(0));
// THIS LINE HERE
var containedValue = hs.First(x => comparer.Equals(x, 3)); // i want something faster than this
Assert.AreEqual(1, containedValue);
}
public class OddEvenBag : IEqualityComparer<int>
{
public bool Equals(int x, int y)
{
return x % 2 == y % 2;
}
public int GetHashCode(int obj)
{
return obj % 2;
}
}
}
包含奇数,我想知道什么奇数如果包含。显然,我想要一个合理缩放的方法,而不是简单地迭代和搜索整个集合。
As well as checking if hs contains an odd number, I want to know what odd number if contains. Obviously I want a method that scales reasonably and does not simply iterate-and-search over the entire collection.
另一种方式来重新表述问题是,我想替换(例如O(1),而不是O(n)),在此处的此行下方选择行。
Another way to rephrase the question is, I want to replace the line below THIS LINE HERE with something efficient (say O(1), instead of O(n)).
我试图实习一个大小类似于Point3D的不可变引用对象的 laaaaaaaarge 数量。看起来像使用 HashSet< Foo>
而不是字典< Foo,Foo>
可节省大约10%不,显然这不是一个改变游戏规则,但我认为它不会伤害尝试快速赢。
Towards what end? I'm trying to intern a laaaaaaaarge number of immutable reference objects similar in size to a Point3D. Seems like using a HashSet<Foo>
instead of a Dictionary<Foo,Foo>
saves about 10% in memory. No, obviously this isn't a game changer but I figured it would not hurt to try it for a quick win. Apologies if this has offended anybody.
Link to similar/identical post provided by Balazs Tihanyi in comments, put here for emphasis.
推荐答案
简单的答案是否定的,你不能。
The simple answer is no, you can't.
如果你想检索对象,你需要使用 HashSet
。在API中没有任何合适的方法来做你要求的其他方式。
If you want to retrieve the object you will need to use a HashSet
. There just isn't any suitable method in the API to do what you are asking for otherwise.
一个优化你可以做,如果你必须使用设置
这是为了首先执行包含
检查,然后只迭代 Set
如果contains返回true。仍然你几乎肯定会发现,一个 HashMap
的额外开销是微小的(因为本质上它只是另一个对象引用)。
One optimization you could make though if you must use a Set
for this is to first do a contains
check and then only iterate over the Set
if the contains returns true. Still you would almost certainly find that the extra overhead for a HashMap
is tiny (since essentially it's just another object reference).
这篇关于我可以在给定一个对象y的哈希集中检索存储的值x其中x.Equals(y)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!