zoukankan      html  css  js  c++  java
  • HashSet中存方用户自己定义数据类型数据,重写equals方法和hashCode方法

    import java.util.Set;
    import java.util.HashSet;
    
    
    public class SetTest {
    	public static void main(String[] args) {
    		/*
    		 *对于用户自己定义类型的数据放在容器(Set)中
    		 *务必重写equals和hashCode方法
    		 *要不然stu1和stu2放在容器中,和觉得是两个不同的元素
    		 **/
    		
    		//set中存放的元素是无序的
    		//set中存储的元素是不能够反复的(依据equals方法和hashCode方法推断)
    		Set set = new HashSet();
    		Student stu1 = new Student(1, "aaa");
    		Student stu2 = new Student(1, "aaa");
    		Student stu3 = new Student(2, "ccc");
    		Student stu4 = new Student(8, "fff");
    		
    		set.add(stu1);
    		set.add(stu2);
    		set.add(stu3);
    		set.add(stu4);
    		
    		System.out.println(set);
    	}
    }
    
    class Student {
    	private int id;
    	private String name;
    	
    	public Student(int id, String name) {
    		this.id = id;
    		this.name = name;
    	}
    	
    	@Override
    	public String toString() {
    		return this.id + " " + this.name;
    	}
    	
    	
    	@Override
    	public boolean equals(Object obj) {		
    		Student stu = (Student) obj;
    		
    		return this.id == stu.id && this.name.equals(stu.name);
    	}
    	
    	
    	@Override 
    	public int hashCode() {
    		return this.id*this.name.hashCode();
    	}
    }
    
    输出结果:
    [8 fff, 1 aaa, 2 ccc]
    


    假设不重写hashCode和equals方法

    import java.util.Set;
    import java.util.HashSet;
    
    
    public class SetTest {
    	public static void main(String[] args) {
    		/*
    		 *对于用户自己定义类型的数据放在容器(Set)中
    		 *务必重写equals和hashCode方法
    		 *要不然stu1和stu2放在容器中,和觉得是两个不同的元素
    		 **/
    		
    		//set中存放的元素是无序的
    		//set中存储的元素是不能够反复的(依据equals方法和hashCode方法推断)
    		Set set = new HashSet();
    		Student stu1 = new Student(1, "aaa");
    		Student stu2 = new Student(1, "aaa");
    		Student stu3 = new Student(2, "ccc");
    		Student stu4 = new Student(8, "fff");
    		
    		set.add(stu1);
    		set.add(stu2);
    		set.add(stu3);
    		set.add(stu4);
     
    		System.out.println(set);
    	}
    }
    
    class Student {
    	private int id;
    	private String name;
    	
    	public Student(int id, String name) {
    		this.id = id;
    		this.name = name;
    	}
    	
    	@Override
    	public String toString() {
    		return this.id + " " + this.name;
    	}	
    }
    输出结果:
    [1 aaa, 1 aaa, 8 fff, 2 ccc]
    




  • 相关阅读:
    [loss]Triphard loss优雅的写法
    [Pytorch]Pytorch中tensor常用语法
    [pytorch]pytorch loss function 总结
    [Pytorch]Pytorch的tensor变量类型转换
    [Pytorch]Pytorch中图像的基本操作(TenCrop)
    caffe深度学习网络(.prototxt)在线可视化工具:Netscope Editor
    samba网络共享
    openwrt开发笔记三:uci移植及API调用
    openwrt开发笔记二:树莓派刷openwrt
    git跟踪忽略规则文件.gitignore
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/6862429.html
Copyright © 2011-2022 走看看