欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HashSet存储自定义对象

程序员文章站 2024-02-27 23:12:57
...
  • HashSet是集合Collection类的子类set的子类,此集合内存储元素的特点是元素不可以重复无索引存储顺序不一致

  • 以下使用代码举例,HashSet存储自定义对象实现不让元素重复(重写hashCode和equls方法)

    import java.util.HashSet;
    
    public class HashSetDemo {
    	public static void main(String[] args) {
    		// 创建集合对象
    		HashSet<Student> hs = new HashSet<Student>();
    
    		// 创建学生对象
    		Student s1 = new Student("林青霞", 27);
    		Student s2 = new Student("柳岩", 22);
    		Student s3 = new Student("王祖贤", 30);
    		Student s4 = new Student("林青霞", 27);
    		Student s5 = new Student("林青霞", 20);
    		Student s6 = new Student("范冰冰", 22);
    
    		// 添加元素
    		hs.add(s1);
    		hs.add(s2);
    		hs.add(s3);
    		hs.add(s4);
    		hs.add(s5);
    		hs.add(s6);
    
    		// 遍历集合
    		for (Student s : hs) {
    			System.out.println(s.getName() + "---" + s.getAge());
    		}
    	}
    }
    
    • student类
    package cn.itcast_02;
    
    public class Student {
    	private String name;
    	private int age;
    
    	public Student() {
    		super();
    	}
    
    	public Student(String name, int age) {
    		super();
    		this.name = name;
    		this.age = age;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public int getAge() {
    		return age;
    	}
    
    	public void setAge(int age) {
    		this.age = age;
    	}
    
    	@Override
    	public int hashCode() {
    		final int prime = 31;
    		int result = 1;
    		result = prime * result + age;
    		result = prime * result + ((name == null) ? 0 : name.hashCode());
    		return result;
    	}
    
    	@Override
    	public boolean equals(Object obj) {
    		System.out.println(this + "---" + obj);
    		if (this == obj)
    			return true;
    		if (obj == null)
    			return false;
    		if (getClass() != obj.getClass())
    			return false;
    		Student other = (Student) obj;
    		if (age != other.age)
    			return false;
    		if (name == null) {
    			if (other.name != null)
    				return false;
    		} else if (!name.equals(other.name))
    			return false;
    		return true;
    	}
    
    }
    
  • 此时再打印不会出现重复:
    王祖贤—30
    范冰冰—22
    柳岩—22
    林青霞—27
    林青霞—20

  • 原文链接:https://blog.csdn.net/qq_32059827/article/details/51580642

相关标签: JavaSE