日期:2014-05-20  浏览次数:20808 次

Java HasMap的问题
有一个类:
Java code
@Entity
@Table(name = "QBMS_BANK")
public class QuestionBank extends BaseEntity {

    private static final long serialVersionUID = 8276628395037978969L;

    @Column(name = "NAME", unique = true)
    @Size(max = 100)
    @NotNull
    private String name;

    @OneToMany(mappedBy = "bank", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    @MapKey(name = "user")
    private Map<User, QuestionBankUserPermission> userPermissions;

    public String getName() {
        return name;
    }

    public Map<User, QuestionBankUserPermission> getUserPermissions() {
        return userPermissions;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setUserPermissions(
            Map<User, QuestionBankUserPermission> userPermissions) {
        this.userPermissions = userPermissions;
    }
}


我在逻辑代码中如下:

Java code
QuestionBankUserPermission userPermission = bank
                    .getUserPermissions().get(user);
            System.err.println("userPermission->" + userPermission);

userPermission拿到的值为null

然后我执行代码:
Java code
if(bank.getUserPermissions().containsKey(user)){
                System.err.println("yes");
            }

没有打印到yes

然后我执行代码:

Java code
for (Map.Entry<User, QuestionBankUserPermission> entry : bank
                    .getUserPermissions().entrySet()) {
                if (entry.getKey().equals(user)) {
                    System.err.println("existed the same key");
                }
            }

可以打印existed the same key

这是为什么呢?为什么我通过迭代Map.Entry就可以判断到key有equals但为何containsKey(user)却是false

而且直接通过get又不能获取到值呢?

分数不多,希望大侠们帮帮忙,苦逼好久了!

------解决方案--------------------
containsKey不光要满足key的equals,还要满足key的hashCode一样

所以
你的Map中存在某个key,它和user满足key.equals(user),但是不满足key.hashCode()==user.hashCode(); 所以containsKey()的时候就找不到
equals和hashCode同时满足,是大多数set的实现需要的
------解决方案--------------------
User必须实现hashcode以及equals方法。
看看是否只实现了equals而未实现hashcode方法