您的位置:首页 > 其它

Map集合的修改问题

2017-11-30 23:22 281 查看

0.前言

今天在对Map集合进行修改的过程中发现了一个比较有意思的点,特此整理记录如下:

1.需求

用Map集合存储Book 和对应的 数量 即 Map

Map<Book, Integer> map = new HashMap<Book, Integer>();
for (int i = 0; i < 5; i++) {
Book book = new Book();
book.setId("" + i);
book.setName("魔戒" + i);
book.setDescription("神奇的书籍");
map.put(book, i);
}
for ( Entry<Book, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey()+"  ===== "+entry.getValue());
}




2.解决方案一

2.1下意识的思路:

获取现有数量+100,存回(修改)Map集合

String id="3";
Book b=new Book();
b.setId(id);
int num=map.get(b)+100;
map.put(b, num);
for ( Entry<Book, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey()+"  ===== "+entry.getValue());
}
}


2.2结果:



2.3问题:

很明显的,对于Map集合而言

Book [id=3, name=null, description=null]




Book [id=3, name=魔戒3, description=神奇的书籍]


不是同一个key

3.解决方案

3.1解决方法

让Book重写
hashCode
equals
方法,让两个Book 只要id相等,即“相等”

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}


String id="3";
Book b=new Book();
b.setId(id);
int num=map.get(b)+100;
map.put(b, num);
for ( Entry<Book, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey()+"  ===== "+entry.getValue());
}
}


3.2存在的疑惑:

此时的对象b是

Book [id=3, name=null, description=null]


map.put(b, num);


会不会导致Map中的key存储的数据不全?????

变成
Book [id=3, name=null, description=null]


3.3代码验证



3.4 反思

Book重写了
hashCode
equals
方法,让两个Book 只要id相等,即“相等”

那么对于Map集合而言

Book [id=3, name=null, description=null]


Book [id=3, name=魔戒3, description=神奇的书籍]


是相同的key

map.put(key, value);


当key在map中存在(新key和旧key“相等”)时,只修改value,不修改key

因此Map中作为key的Book在这种情况下不会改变

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  集合map key 对象比较
相关文章推荐