Map集合的修改问题

作者: 新手村的0级玩家 | 来源:发表于2017-11-30 23:19 被阅读14次

    0.前言

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

    1.需求

    用Map集合存储Book 和对应的 数量 即 Map<Book, Integer>
    在已知Book.ID的情况下,对指定Book的数量增加100(Map中一定存在该book)

          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());
            }
    
    原始Map

    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结果:

    修改后的Map

    2.3问题:

    很明显的,对于Map集合而言
    Book [id=3, name=null, description=null]

    Book [id=3, name=魔戒3, description=神奇的书籍]
    不是同一个key

    3.解决方案

    3.1解决方法

    让Book重写hashCodeequals方法,让两个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重写了hashCodeequals方法,让两个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集合的修改问题

        本文链接:https://www.haomeiwen.com/subject/klibbxtx.html