Map集合的修改问题
2017-11-30 23:22
281 查看
0.前言
今天在对Map集合进行修改的过程中发现了一个比较有意思的点,特此整理记录如下:1.需求
用Map集合存储Book 和对应的 数量 即 MapMap<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在这种情况下不会改变
相关文章推荐
- 自定义实现JavaScript的Map对象,修改IE不兼容MAP()的问题
- C#中DataGridView绑定了DataTable后,通过代码修改DataGridView中的数据,总有一行(被修改过并被用户选中的行集合中索引为0的行)不能被UpDate回数据库的问题和解决办法
- 修改Map中确定key对应的value问题
- 当传递具有已修改行的 DataRow 集合时,更新要求有效的 UpdateCommand问题解决
- 修改IE不兼容MAP()的问题,自定义实现JavaScript的Map对象
- Java中hashCode() equals() 与将对象放入集合或者说Map时要考虑的问题
- Map集合遍历过程调用remove方法引起的问题
- Hibernate 的Set、List、Map集合操作(添加,修改,查询)
- 集合ArrayList遍历修改问题
- 解决“控件包含代码块,因此无法修改控件集合”问题的方法
- 关于对Map、List等集合操作抛出ConcurrentModificationException 异常问题
- java增强for循环遍历Map集合问题
- MyBatis的一系列问题的处理(遍历Map集合和智能标签和属性和字段不一样的解决办法 和sql片段)(三)
- Top 9 questions about Java Maps (关于java map集合的前九个问题)
- Java集合中:List、Set、map的区别和具体的使用场景和高频问题解析
- 修改Myeclipse默认的Libraries包集合(用于解决包冲突问题)
- java 集合(arraylist set map)遍历问题
- 用map集合巧妙解决实际问题。
- EL表达式取Map集合问题
- 关于Map集合的迭代输出问题