• HashSet 注意点


    HashSet 通过哈希算法来存取集合中的对象,有很好的存取和查找性能 。 

    自定义Customer 类型,想通过比较name和age过滤重复的 。

    package test.java;
    
    public class Customer {
    
        String name;
        int age;
    
        public Customer(String name,int age){    //构造方法没有返回值
            this.name=name;
            this.age=age;
        }
        public boolean equals(Object o){
            if(this==o) return true;
            if(!(o instanceof Customer)){
                return false;
            }
            Customer other= (Customer ) o;  // 记得!!!
            return (this.name.equals( other.name)&&this.age==other.age);
    
        }
    
       /* public int hashCode(){
            int result ;
            result=(name==null)?0:name.hashCode();
            result=29*result+age;
            return result;
        }*/
    }
    package test.java;
    import java.util.HashSet;
    import java.util.Set;
    
    public class test {
        public static void main(String[] args) {
            Customer a=new Customer("Tom",25);
            Customer b=new Customer("Tom",25);
            Set<Customer> set=new HashSet<Customer>();
            set.add(a );
            set.add(b);
            System.out.println(set.size());
        }
    }

    当Customer咩有覆盖hashCode方法时,集合长度是2,覆盖了hasdCode时才是1 。

    为了保证HashSet的正常工作,如果Customer覆盖了equals方法,也应该覆盖hashCode方法,并且保证两个相等的Customer对象的哈希码也是一样的。详见《面向对象编程》 P442

  • 相关阅读:
    面试准备
    论文投稿Cover letter
    Pycharm 快捷键
    linux下常用命令:
    Qt中数据模块学习
    Qt 多线程和网络编程学习
    VS高效开发快捷键
    良好编码风格习惯整理
    Qt QAxObject操作excel文件过程总结(转):
    Qt开发中的实用笔记三--关于各种类的零碎知识点:
  • 原文地址:https://www.cnblogs.com/assult/p/4283021.html
Copyright © 2020-2023  润新知