创建一个存储学生对象的集合,存储多个学生对象,使用程序实现在控制台遍历该集合要求:学生对象的成员变量值相同,我们就认为是同一个对象。使用Java来写
时间: 2023-09-16 16:13:33 浏览: 160
基于java+控制台实现学生宿舍管理系统
好的,以下是一个示例代码:
首先定义一个学生类:
```java
public class Student {
private String name;
private int age;
private String id;
public Student(String name, int age, String id) {
this.name = name;
this.age = age;
this.id = id;
}
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;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Student) {
Student other = (Student) obj;
return this.name.equals(other.name) && this.age == other.age && this.id.equals(other.id);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(name, age, id);
}
}
```
这里实现了 `equals` 方法和 `hashCode` 方法,用于在集合中判断两个学生对象是否相同。
然后创建一个集合来存储多个学生对象:
```java
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 18, "1001"));
students.add(new Student("李四", 20, "1002"));
students.add(new Student("王五", 19, "1003"));
students.add(new Student("张三", 18, "1001"));
students.add(new Student("赵六", 22, "1004"));
```
接着在控制台遍历该集合:
```java
for (Student student : students) {
System.out.println("姓名:" + student.getName() + ",年龄:" + student.getAge() + ",学号:" + student.getId());
}
```
完整代码如下:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 18, "1001"));
students.add(new Student("李四", 20, "1002"));
students.add(new Student("王五", 19, "1003"));
students.add(new Student("张三", 18, "1001"));
students.add(new Student("赵六", 22, "1004"));
for (Student student : students) {
System.out.println("姓名:" + student.getName() + ",年龄:" + student.getAge() + ",学号:" + student.getId());
}
}
}
class Student {
private String name;
private int age;
private String id;
public Student(String name, int age, String id) {
this.name = name;
this.age = age;
this.id = id;
}
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;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Student) {
Student other = (Student) obj;
return this.name.equals(other.name) && this.age == other.age && this.id.equals(other.id);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(name, age, id);
}
}
```
运行代码后,输出结果如下:
```
姓名:张三,年龄:18,学号:1001
姓名:李四,年龄:20,学号:1002
姓名:王五,年龄:19,学号:1003
姓名:赵六,年龄:22,学号:1004
```
可以看到,重复的学生对象并没有被重复添加到集合中,并且在遍历时也只输出了一次。
阅读全文