*(1)编写一个 Student 类,包含 name 和 age 属性,提供有参构造方法。 2)在 Student 类中,重写 toString ()方法,输出 age 和 name 的值。 * (3)在 Student 类中,重写 hashCode ()和 equals )方法。 hashCode )的返回值是 name 的哈希值与 age 的和。 * ● equals ()判断对象的 name 和 age 是否相同,相同则返 true , * 不同则返回 false 。 (4)编写一个测试类,创建一个 HashSet < Student >对象 hs , * 向 hs 中加多个 Student 对象,假设有两个 Student 对象相等。 * 输出 HashSet 集合,观察 Student 对象是否加成功。
代码如下:
package shiyan8;
import java.util.*;
class Student {
private int age;
private String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return age + ":" + name;
}
public int hashCode() {
return name.hashCode() + age;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Student stu))
return false;
return this.name.equals(stu.name) && this.age == stu.age;
}
}
public class Test {
public static void main(String[] args) {
HashSet<Student> hs = new HashSet<Student>();
hs.add(new Student(18, "ZhangSan"));
hs.add(new Student(20, "lisa"));
hs.add(new Student(22, "Ikun"));
System.out.print(hs);
}
}
运行结果: