定一个Set类型的对象set1,然后向set1中放入2个学生:new Student("张三","男",20)、new Student("李四","男",22)。 遍历set1中的学生对象,并将每个学生的姓名、性别、年龄输出到显示器。使用JAVA编写上述问题。
时间: 2023-07-19 21:16:15 浏览: 38
好的,以下是代码实现:
```java
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<Student> set1 = new HashSet<>();
set1.add(new Student("张三", "男", 20));
set1.add(new Student("李四", "男", 22));
for (Student student : set1) {
System.out.println("姓名:" + student.getName() + ",性别:" + student.getGender() + ",年龄:" + student.getAge());
}
}
}
class Student {
private String name;
private String gender;
private int age;
public Student(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
}
```
输出结果为:
```
姓名:张三,性别:男,年龄:20
姓名:李四,性别:男,年龄:22
```