这是我的代码:
import java.util.HashMap;
class MyString
{
String string;
MyString(String string)
{
this.string = new String(string);
}
}
public class test
{
public void test3()
{
HashMap<MyString, Byte> byteHashMap = new HashMap<MyString, Byte>();
char c = 'A';
byte b = (byte)c;
String string = new String("The Letter A");
MyString myString = new MyString(string);
byteHashMap.put(myString, b);
if (byteHashMap.containsKey(myString))
//if (byteHashMap.containsKey(new MyString(string)))
{
System.out.println("true");
}
else
{
System.out.println("false");
}
}
public static void main(String[] args)
{
test testObject = new test();
testObject.test3();
}
}
我想知道为什么代码按原样返回 true。但是,当我切换 if 语句(参见注释行)时,它返回 false。
我相信它与覆盖 MyString 类中的 equals 方法有关,但我不确定如何处理这个问题。
问候。
最佳答案
您的信念是正确的。映射结构依赖于 .equals
来确定键是否已经存在于映射中。默认情况下,对象类型具有实例相等性(意味着 a.equals(b)
为真当且仅当 a
和 b
指向相同对象)。
在您的情况下,如果 string
字段相等,您可能希望两个 MyString
实例相等。在这种情况下,您可以使用类似以下内容覆盖 equals
:
@Override
public boolean equals(Object other) {
if (other == null) { return false; }
if (!(other instanceof MyString)) { return false; }
MyString m = (MyString)other;
return this.string.equals(m.string);
}
有了这个,两个 if 语句中的任何一个都会返回 true。
您还应该覆盖 hashCode
。如果您使用 Eclipse,它可以很容易地通过 Source
菜单为您生成这两个方法。
关于Java - HashMap.containsKey 返回不正确的对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20307511/