HashSet to store custom objects

  • HashSet is a subclass of a subclass of class Collection collection set, the set of features within the storage element is 元素不可以重复, 无索引, 存储顺序不一致.

  • The following code illustrates the use, HashSet object implements custom storage element not to repeat (override hashCode method and 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 class
    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;
    	}
    
    }
    
  • At this time, printing will not repeat again:
    Joey -30
    Bingbing -22
    LiuYan -22
    Brigitte -27
    Brigitte -20

  • Original link:https://blog.csdn.net/qq_32059827/article/details/51580642

Published 53 original articles · won praise 13 · views 2240

Guess you like

Origin blog.csdn.net/qq_36821220/article/details/105027844