java - Hashmap get(key) 即使值存在也返回 null

标签 java android null hashmap

我正在尝试将数据保存在 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。这是比较引用而不是文本数据。

此外,您还需要处理 friendIdfriendNamenull 的可能性。 (所以不要无条件地对它们调用 equalshashCode。)你可能想使用 Guava在编写 hashCodeequals 时有帮助的方法。

最后,您使用可变 数据类型作为散列映射中的键。这通常是一个坏主意 - 如果您向映射添加一个键,然后以影响哈希码的方式改变对象,您以后将无法使用相同的键获取。我强烈鼓励您使用不可变类型作为映射键。

您需要确定您的相等标准是什么,并在 hashCodeequals 之间保持一致。如果这两者不一致,您很可能会看到这样的问题。

关于java - Hashmap get(key) 即使值存在也返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22816463/

相关文章:

java - Ecore 建模项目不可用

java - javax.swing.text.BadLocationException 异常不断打开

android - 在android中用两个日期对象对数组列表进行排序

Android 列表项布局

c# - 是否有理由在使用后将对象设置为空?

c# - 防止字符串转换为 Null 失败的最佳方法

java获取偶数或奇数

java - 如何修复在 Jboss 域模式下部署应用程序对数据库的重复插入?

java - 第一个 Hibernate 测试给出错误 [编辑]

iOS 自定义 View - 非常奇怪的属性行为