The method of customizing the weight of Set

Judgment order: HashSet will first judge whether there is an object with the same hashcode according to the hashcode of the target class when executing add, and if so, use equals to judge whether it is the same object.

The default equals compares the address value.
When overriding the equals method, the hashCode method must be overridden.

Example: We want to determine whether it is the same student only based on the id, that is, students with the same id cannot appear in the set.

import java.util.HashSet;
import java.util.Set;

public class Main {
    
    

	public static void main(String[] args) {
    
    
		Set<Stu> set = new HashSet<>();
		for (int i = 1; i <= 5; i++) {
    
    
			set.add(new Stu(i));
		}
		for (int i = 1; i <= 3; i++) {
    
    
			set.add(new Stu(i));
		}
		System.out.println(set.toString());
	}
}

class Stu {
    
    
	int id;
	String name;
	
	public Stu(int id) {
    
    
		this.id = id;
	}
	
	public String toString() {
    
    
		return "编号:" + this.id;
	}
	/*
	@Override    必须带上重写符号
	public int hashCode() {
		return this.id;
	}
	@Override
	public boolean equals(Object s) {//必须是Object类
		Stu ss = (Stu)s;//转为Stu类
		return this.id == ss.id;
	}
	*/
}

Running result:
insert image description here
after removing the comment:
insert image description here

Guess you like

Origin blog.csdn.net/QinLaoDeMaChu/article/details/111149815