2.
请按照下列要求编写程序。
(
1
)
编写一个
Student
类,包含
name
和
age
属性,提供有参构造方法。
(
2
)
在
Student
类中,重写
toString()
方法,输出
age
和
name
的值。
(
3
)
在
Student
类中,重写
hashCode()
和
equals()
方法
-
hashCode()
的返回值是
name
的
hash
值与
age
的和。
-
equals()
判断对象的
name
和
age
是否相同,相同则返回
true
不同返回
false
。
(
4
)最后编写一个测试类,创建一个
HashSet<Student>
对象
hs
,向
hs
中添加多个
Student
对象,假设有两个
Student
对象相等,输出
HashSet
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
public class Student {
public String name;
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name)+age;
}
}
class TestStudent{
public static void main(String[] args) {
Student stu=new Student("曹操",12);
Student stu1=new Student("刘备",19);
Student stu2=new Student("孙策",17);
Student stu3=new Student("孙斌",18);
Student stu4=new Student("孙斌",18);
HashSet<Student> hs=new HashSet<>();
hs.add(stu1);
hs.add(stu2);
hs.add(stu3);
hs.add(stu4);
hs.add(stu);
System.out.println(hs);
Iterator it=hs.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
for (Object i:hs
) {
System.out.println(i);
}
}
}
,观察是否添加成功。