当前位置:编程学习 > JAVA >>

[Java] 使用散列时,重写HashCode和Equals

1. 源起


    有的时候数据对象经常会放到HashMap或者HashSet里面,希望根据ID来表示数据对象,这就需要覆盖hashCode和equals方法。


2. 代码
   

public class Goods {  
    public Goods(int id) {  
        this.id = id;  
    }  
  
    public int id;  
    public String name;  
    public String image;  
    public double price;  
  
    public static void main(String[] args) {  
        Set<Goods> set = new HashSet<Goods>();  
        Goods a = new Goods(0);  
        Goods b = new Goods(0);  
        set.add(a);  
        set.add(b);  
        HashMap<Goods, Integer> map = new HashMap<Goods, Integer>();  
        map.put(a, 0);  
        map.put(b, 0);  
        System.out.println("Goods");  
        System.out.println("set num = " + set.size());  
        System.out.println("map key set num = " + map.keySet().size());  
        System.out.println("a.hashCode() = " + a.hashCode());  
        System.out.println("b.hashCode() = " + b.hashCode());  
    }  
};  

 

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,