鉴于以下课程
public class Foo
{
public int FooId { get; set; }
public string FooName { get; set; }
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
if (fooItem == null)
{
return false;
}
return fooItem.FooId == this.FooId;
}
public override int GetHashCode()
{
// Which is preferred?
return base.GetHashCode();
//return this.FooId.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
我已经覆盖了该Equals
方法,因为它Foo
代表了Foo
s表的一行.哪个是覆盖的首选方法GetHashCode
?
覆盖为什么重要GetHashCode
?
根据我的理解,我认为:
我对么?
现在,如果我是正确的,我有以下问题:HashMap
内部使用对象的哈希码.因此,如果两个对象可以具有相同的哈希码,那么它如何HashMap
使用它所使用的键?
有人可以解释HashMap
内部如何使用对象的哈希码吗?
我有一个班级IComparable
:
public class a : IComparable
{
public int Id { get; set; }
public string Name { get; set; }
public a(int id)
{
this.Id = id;
}
public int CompareTo(object obj)
{
return this.Id.CompareTo(((a)obj).Id);
}
}
Run Code Online (Sandbox Code Playgroud)
当我将这个类的对象列表添加到哈希集时:
a a1 = new a(1);
a a2 = new a(2);
HashSet<a> ha = new HashSet<a>();
ha.add(a1);
ha.add(a2);
ha.add(a1);
Run Code Online (Sandbox Code Playgroud)
一切都很好,ha.count
是2
的,但:
a a1 = new a(1);
a a2 = new a(2);
HashSet<a> ha = new HashSet<a>();
ha.add(a1); …
Run Code Online (Sandbox Code Playgroud) 我想做一些测试,这些测试需要一些具有相同哈希码的字符串,但不是相同的字符串.我找不到任何例子,所以我决定写一个简单的程序来为我做.
下面的代码反复生成两个随机字符串,直到它们生成相同的哈希码.
static Random r = new Random();
static void Main(string[] args)
{
string str1, str2;
do
{
str1 = GenerateString();
str2 = GenerateString();
} while (str1.GetHashCode() != str2.GetHashCode() && str1 != str2);
Console.WriteLine("{0}\n{1}", str1, str2);
}
static string GenerateString()
{
string s = "";
while (s.Length < 6)
{
s += (char)r.Next(char.MaxValue);
}
return s;
}
Run Code Online (Sandbox Code Playgroud)
这段代码似乎有效(理论上),但可能需要几个世纪才能完成.所以我反过来考虑从一个哈希码生成两个字符串.
我知道从哈希码中检索字符串是不可能的,但是可以从中生成可能的字符串吗?
我正在使用Visual Studio 2015社区版.版本:14.0.23107.0D14REL.
.NET Framework:4.6.00081.
我不明白编译器如何足够聪明,可以构建一个O(1)查找MyObject
,我可以在其中放置任何内容
public class MyObject
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
我理解如何为有限数量的非原语如:
public class MyObject
{
int i { get; set; }
char c { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但它怎么可能知道如何执行任何实现MyObject
呢?