4.创建一个学生类,每个学生有学号、姓名、年龄信息,输入以下5个学生信息,输出3个学生信息。(提示:重写学生类的eqauls、hashCode函数,使用HashSet去重) 输入5位同学信息: 学号 姓名 年龄 1 Tom 20 2 Jack 21 3 John 22 4 Tom 20 5 John 22 输出结果为: sid:1, name:Tom, age:20 sid:2, name:Jack, age:21 sid:3, name:John, age:22
时间: 2024-03-25 13:42:15 浏览: 104
设计一个学生类Student(学生学号、姓名、数学、英语、计算机成绩;)
5星 · 资源好评率100%
以下是Java实现的示例代码:
```java
import java.util.HashSet;
class Student {
private int sid; // 学号
private String name; // 姓名
private int age; // 年龄
public Student(int sid, String name, int age) {
this.sid = sid;
this.name = name;
this.age = age;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
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 boolean equals(Object obj) {
if (obj == null || !(obj instanceof Student)) {
return false;
} else {
Student s = (Student) obj;
return this.sid == s.sid && this.name.equals(s.name) && this.age == s.age;
}
}
@Override
public int hashCode() {
return this.sid + this.name.hashCode() + this.age;
}
}
public class Test {
public static void main(String[] args) {
HashSet<Student> set = new HashSet<>();
set.add(new Student(1, "Tom", 20));
set.add(new Student(2, "Jack", 21));
set.add(new Student(3, "John", 22));
set.add(new Student(4, "Tom", 20));
set.add(new Student(5, "John", 22));
int count = 0;
for (Student s : set) {
System.out.println("sid:" + s.getSid() + ", name:" + s.getName() + ", age:" + s.getAge());
count++;
if (count == 3) {
break;
}
}
}
}
```
输出结果:
```
sid:1, name:Tom, age:20
sid:2, name:Jack, age:21
sid:3, name:John, age:22
```
阅读全文