使用相同userName创建的2个用户在执行" map.get(user);"?时可以获得相同的结果

时间:2016-01-17 05:47:35

标签: java

好的,请参阅此User课程

public class User{
 private String userName;
 public User(String userName){
     this.userName=userName;
 }
 @Override
 public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (!(obj instanceof User))
      return false;
    User user = (User) obj;
    return user.userName.equals(this.userName);
 }
 @Override
 public int hashCode() {
    return userName.hashCode()  ;
 }
}

现在我们得到了Map

Map<User, List<String>> map=new ConcurrentHashMap<User, List<String>>();

现在我们得到了这些代码:

User  tom=new User("Tom");
List<String> tomList=new ArrayList<String>();
tomList.add("Test");
User mary=new User("Mary");
map.put(tom,tomList);
map.put(mary,new ArrayList<String>());

现在,我们创建一个新对象Tom

User  tom2=new User("Tom");
List<String> tomList=map.get(tom2);

我的问题是tomListnull还是null

如果它为null,那么我们可以使它不是null。这意味着我们可以创建具有相同userName的对象,而不是尝试找到确切的对象,我们可以map.get(user);

2 个答案:

答案 0 :(得分:0)

使用Map匹配

key.equals(k)个密钥。

或正式:
如果Map已经包含来自键的映射&#39; k&#39;价值观&#39; v&#39;这样key.equals(k),然后get(key)方法返回v,否则返回null。

在你的情况下:
User.equals()匹配 userName String属性,因此map.get(tom2)为null。 所有用户对象命名为&#34; Tom&#34;将被视为具有相同的密钥。

答案 1 :(得分:0)

您提出的行为实际上是通过equals()(和hashcode())函数由您的代码控制的。让我们来看看equals()

 @Override
 public boolean equals(Object obj) {
    //two references are considered equal to each other,
    //if they are pointing to the same Object

    //This is the default equals implementation.
    if (this == obj)
      return true;

    //Two objects cannot be equal if even their types do not match.
    if (!(obj instanceof User))
      return false;

    //If their types matched, let's start comparing them field-by-field.
    //If all fields match, then (altough they are different objects
    //in memory) they represent the same real-world entity
    //in this case user Tom.
    User user = (User) obj;
    return user.userName.equals(this.userName);
 }

通过移除equals()中的最后一部分以及hashcode()中的相应部分,您可以更改地图的行为,以期望将引用到同一个对象