用java编写一个类,名字为ListDemo,在main方法中做以下工作: 定义一个可以保存Student类型对象的List类型对象list1,然后向list1中放入2个学生:new Student("张三","男",20)、new Student("李四","男",22) 遍历list1中的学生对象,并将每个学生的姓名、性别、年龄输出到显示器 3、定义一个可以保存String类型对象的List类型对象list2,然后向list2中放入2个字符串: "aaa"、"bbb" 遍历list2中的字符串对象,并输出到显示器
时间: 2024-02-29 20:52:14 浏览: 62
好的,这是Java的代码实现:
```java
import java.util.ArrayList;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
// 定义一个存储Student类型对象的List
List<Student> list1 = new ArrayList<>();
// 向list1中添加学生
list1.add(new Student("张三", "男", 20));
list1.add(new Student("李四", "男", 22));
// 遍历list1,输出每个学生的姓名、性别、年龄
for (Student s : list1) {
System.out.println("姓名:" + s.getName() + ",性别:" + s.getGender() + ",年龄:" + s.getAge());
}
// 定义一个存储String类型对象的List
List<String> list2 = new ArrayList<>();
// 向list2中添加字符串
list2.add("aaa");
list2.add("bbb");
// 遍历list2,输出每个字符串
for (String s : list2) {
System.out.println(s);
}
}
}
// 定义一个Student类
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
aaa
bbb
```
阅读全文