zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    几种常用的曲线
    0188. Best Time to Buy and Sell Stock IV (H)
    0074. Search a 2D Matrix (M)
    0189. Rotate Array (E)
    0148. Sort List (M)
    0859. Buddy Strings (E)
    0316. Remove Duplicate Letters (M)
    0452. Minimum Number of Arrows to Burst Balloons (M)
    0449. Serialize and Deserialize BST (M)
    0704. Binary Search (E)
  • 原文地址:https://www.cnblogs.com/assult/p/4283021.html
Copyright © 2011-2022 走看看