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]