zoukankan      html  css  js  c++  java
  • Java学习笔记--HashMap中使用object做key的问题【转】

    在HashMap中,如果需要使用多个属性组合作为key,可以将这几个属性组合成一个对象作为key。但是存在的问题是,要做get时,往往没办法保存当初put操作时的key object的reference,此时,需要让key object覆盖如下hashCode()和equals(Object obj)的实现。sample code如下:

    public class TestKeyObject {
        private long id;
        private int type;
    
        public TestKeyObject(long id, int type) {
            this.id = id;
            this.type = type;
        }
    
        public long getId() {
            return id;
        }
    
        public void setId(long id) {
            this.id = id;
        }
    
        public int getType() {
            return type;
        }
    
        public void setType(int type) {
            this.type = type;
        }
    
        //定义HashCode的计算方式
        public int hashCode() {
            int ret = new Long(id).hashCode() ^ new Integer(type).hashCode();
            // 也可以用下面这种方式计算hashCode
            // int ret = String.valueOf(id).hashCode() ^
            // String.valueOf(type).hashCode();
            System.out.println(ret);
            return ret;
        }
    
        //定义相等的条件
        public boolean equals(Object obj) {
            if (null == obj) {
                return false;
            }
            if (!(obj instanceof TestKeyObject)) {
                return false;
            }
            TestKeyObject tmpObj = (TestKeyObject) obj;
            return tmpObj.id == id && tmpObj.type == type;
        }
    
    }
  • 相关阅读:
    Hui之组件大全
    程序员交流学习平台
    PHP 常用框架
    常用浏览器
    设计必备工具、平台
    文档必备工具
    开发必备工具
    工作必备工具
    源码托管平台、软件
    前端常用框架
  • 原文地址:https://www.cnblogs.com/gnivor/p/4782915.html
Copyright © 2011-2022 走看看