解決hashSet包含重複的自定義對象

//看某個視頻講的ide

public class Test {this

public static void main(String[] args) {

  HashSet<Student> ha=new HashSet<>();
  
  Student a1=new Student("li",12);
  
  Student a2=new Student("wa",12);
  
  Student a3=new Student("wa",12);
  
  ha.add(a1);
  
  ha.add(a2);
  
  ha.add(a3);
  
  for(Student s:ha)
  
	  System.out.println(s.name+"-->"+s.age);
	  
}

}.net

class Student{code

String name;

int age;

public Student(String name,int age){

	this.name=name;
	
	this.age=age;
}
[@Override](https://my.oschina.net/u/1162528)

public boolean equals(Object obj) {

	System.out.println("equal----------");
	
	// TODO Auto-generated method stub
	
	Student s=(Student) obj;
	
	if(this.age!=s.age)
	
		return false;
		
	if(!(this.name.equals(s.name)))
	
		return false;
		
	return true;
	
}

[@Override](https://my.oschina.net/u/1162528)
public int hashCode() {

	return 1;
}

}視頻

相關文章
相關標籤/搜索