用java代码写出:新建集合,把自己本组的同学加到集合中HashSet,Student ---->name age如果有重复自动覆盖2.删除自己同姓的同学,如 删除张的同学3.输出剩下的同学
时间: 2023-05-17 20:05:09 浏览: 92
以下是用 Java 代码实现的答案:
1. 新建集合,把自己本组的同学加到集合中 HashSet,Student ---->name age 如果有重复自动覆盖
```java
HashSet<Student> students = new HashSet<>();
students.add(new Student("张三", 20));
students.add(new Student("李四", 21));
students.add(new Student("王五", 22));
students.add(new Student("张三", 23)); // 自动覆盖
```
其中,Student 类的定义如下:
```java
class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
```
2. 删除自己同姓的同学,如删除张的同学
```java
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
if (student.name.equals("张三")) {
iterator.remove();
}
}
```
3. 输出剩下的同学
```java
for (Student student : students) {
System.out.println(student.name + " " + student.age);
}
```
希望这个答案能够帮到你!
阅读全文