我正在尝试将数据保存在 HashMap 中并检索它。键对应的值存在,它仍然返回 null。我还实现了 equals() 和 hashCode() 方法。
ArrayList<Friends> friendsArrayList = new ArrayList<Friends>();
HashMap<Friends,ArrayList<FriendDetails>> friendDetailsHashMap = new HashMap<Friends, ArrayList<FriendDetails>>();
int mSelectedIndex = 0;
...
Friends f = friendsArrayList.get(mSelectedIndex);
ArrayList<MeterGroups> temp2 = friendDetailsHashMap.get(mp); //<== This is where it returns null
我的 ObjectClass Friends.java:
import java.io.Serializable;
public class Friends implements Serializable {
private String friendName;
private String friendId;
private double distanceFromCurrentLocation;
public Friends(String name, String id)
{
this.friendName = name;
this.friendId = id;
this.distanceFromCurrentLocation = getDistanceFromCurrentLocation();
}
public String getFriendName(){
return friendName;
}
public void setFriendName(String name){
this.friendName = name;
}
public void setFriendId(String id){
this.friendId = id;
}
public String getFriendId(){
return friendId;
}
public double getDistanceFromCurrentLocation(){
return 0.0;
}
public int hashCode(){
return friendName.hashCode()*friendId.hashCode();
}
public boolean equals(Object o){
if(o == null) {
return false;
}
if(!(o instanceof Friends)) {
return false;
}
Friends other = (Friends) o;
return this.friendId == other.friendId; //friendId is a unique value
}
}
最佳答案
您的equals
实现仅 使用friendId
。您的 hashCode
实现同时使用了 friendName
和 friendId
。因此可以有两个相同的对象具有不同的哈希码。
此外,您使用 ==
来比较 equals
中的字符串,而不是 equals
。这是比较引用而不是文本数据。
此外,您还需要处理 friendId
或 friendName
为 null
的可能性。 (所以不要无条件地对它们调用 equals
或 hashCode
。)你可能想使用 Guava在编写 hashCode
和 equals
时有帮助的方法。
最后,您使用可变 数据类型作为散列映射中的键。这通常是一个坏主意 - 如果您向映射添加一个键,然后以影响哈希码的方式改变对象,您以后将无法使用相同的键获取。我强烈鼓励您使用不可变类型作为映射键。
您需要确定您的相等标准是什么,并在 hashCode
和 equals
之间保持一致。如果这两者不一致,您很可能会看到这样的问题。
关于java - Hashmap get(key) 即使值存在也返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22816463/