zoukankan      html  css  js  c++  java
  • 每天学会一点点(重写equals一定要重写hashcode)

    package com.example.demo.javaError;
    
    import java.util.HashMap;
    
    /**
     * Created by yyy on 2019/01/24.
     */
    public class MyTest {
        private static class Person{
            int idCard;
            String name;
    
            public Person(int idCard, String name) {
                this.idCard = idCard;
                this.name = name;
            }
            @Override
            public boolean equals(Object o) {
                if (this == o) {
                    return true;
                }
                if (o == null || getClass() != o.getClass()){
                    return false;
                }
                Person person = (Person) o;
                //两个对象是否等值,通过idCard来确定
                return this.idCard == person.idCard;
            }
            @Override
            public int hashCode()
            {
                int hash = 7;
                hash = 31*hash+idCard;
    //            hash = 31*hash+name.hashCode();
                return hash;
                
            }
    
        }
        public static void main(String []args){
            HashMap<Person,String> map = new HashMap<Person, String>();
            Person person = new Person(1234,"乔峰");
            //put到hashmap中去
            map.put(person,"天龙八部");
            //get取出,从逻辑上讲应该能输出“天龙八部”
            System.out.println("结果:"+map.get(new Person(1234,"萧峰")));
        }
    }
  • 相关阅读:
    日志_测试代码_Qt532
    SetParent
    【转】QT获取系统时间,以及设置日期格式
    JNI打通java和c
    Python 对图片进行人脸识别
    Python写黑客小工具,360免杀
    简单选择排序
    插入排序
    双向链表的实现
    记录安卓开发中的问题
  • 原文地址:https://www.cnblogs.com/heqiyoujing/p/10317413.html
Copyright © 2011-2022 走看看