HashSet存储学生对象并遍历
需求: 创建一个存储学生对象的集合,存储多个学生对象,使用程序实现在控制台遍历该集合 要求: 学生对象的成员变量值相同,我们就认为是同一个对象
public class Student {
private String name;
private int age;
public Student ( ) {
}
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) {
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 ;
}
}
public class HashSetTest {
public static void main ( String[ ] args) {
HashSet< Student> hs = new HashSet < > ( ) ;
Student s1 = new Student ( "小明" , 18 ) ;
Student s2 = new Student ( "小蓝" , 22 ) ;
Student s3 = new Student ( "小红" , 20 ) ;
Student s4 = new Student ( "小明" , 18 ) ;
hs. add ( s1) ;
hs. add ( s2) ;
hs. add ( s3) ;
hs. add ( s4) ;
for ( Student s : hs) {
System. out. println ( s. getName ( ) + "," + s. getAge ( ) ) ;
}
}
}