主要问题
我有一个充满顶点对象的 HashMap 。基于一个整数(即 1),我想找到该顶点对象。请参阅下面的代码:
public class Playground {
public static void main(String[] args) {
Map<Vertex, String> map1 = new HashMap<Vertex, String>();
Map<Integer, String> map2 = new HashMap<Integer, String>();
Vertex v1 = new Vertex(5);
map1.put(v1, "1");
Vertex v2 = new Vertex(5);
String s = map1.get(v2);
System.out.println(s);
Integer int1 = new Integer(1);
map2.put(int1, "2");
Integer int2 = new Integer(1);
String t = map2.get(int2);
System.out.println(t);
}
}
class Vertex{
public int id;
public Vertex(int id){
this.id = id;
}
@Override
public boolean equals(Object obj) {
Vertex v = (Vertex) obj;
return (this.id == v.id);
}
}
输出:
空
2
如上所示,它适用于 Integer 对象,但不适用于用户定义的 Vertex 对象。我也重写了 equals 方法。
附加信息
我有一个文本文件。第一列表示边的尾部。第二个是边缘的头部。以下是摘录:
1 1
1 2
1 8
1 4
2 47646
2 47647
...
我预加载顶点 1 - n 因为……好吧……我无法每次都检查 map 的键集以查看顶点是否已存在。
无论如何,那么,基于这个文本文件,我需要找到id为“x”的顶点并添加一条边。
你可能会问我为什么不使用改为使用整数对象作为键。网上的许多示例都使用通用 V 对象,这是有道理的 --- 每个节点 (irl) 都会有额外的信息,无论是停靠点的名称还是其他信息。
最佳答案
您需要重写 hashCode
方法以使 JVM 正确存储和检索 HashMap 中的对象。
当对哈希集合(例如HashMap)调用put方法时,会调用关键对象的hashcode方法来决定存储该对象的桶。然后调用它的 equals 方法来查看那里是否已经存在某些东西。
类似地,当您对 HashMap 执行 get 操作时,将调用关键的 hashCode 方法来查找存储桶并检索对象。
由于您尚未重写 Vertex 类中的 hashcode 方法,因此使用默认的 hashcode 实现。因此,具有相同 id 值的两个 Vertex 对象可能具有不同的哈希码。
阅读此相关文章以了解如何重写 equals 和 hashcode 方法:
What issues should be considered when overriding equals and hashCode in Java?
您可以在 Google 上找到同一主题的不同文章。一个好的谷歌结果:
http://javarevisited.blogspot.in/2011/02/how-to-write-equals-method-in-java.html
关于java - 如何在 HashMap 中查找对象而不引用实际对象? (从文本文件加载有向图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17977296/