创建一个工人类(worker),以及一个list集合,在集合中添加三个工人信息: 姓名 年龄 工资 张三 30 3000 Worker w1=new Worker(“张三”,30,3000); 李四 25 3500 王五 27 3200 2.在李四之前插入一个工人,信息为:姓名:赵六,年龄:24,工资3300 3. 删除王五的信息 4.利用for 循环遍历,打印List 中所有工人的信息 5.利用迭代遍历(Iterator),对List 中所有的工人调用work 方法。用java代码显示
时间: 2023-12-14 08:39:51 浏览: 85
```java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
class Worker {
String name;
int age;
int salary;
public Worker(String name, int age, int salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public void work() {
System.out.println(name + " is working.");
}
public String toString() {
return "Name: " + name + ", Age: " + age + ", Salary: " + salary;
}
}
public class Main {
public static void main(String[] args) {
List<Worker> list = new ArrayList<>();
Worker w1 = new Worker("张三", 30, 3000);
list.add(w1);
Worker w2 = new Worker("李四", 25, 3500);
list.add(w2);
Worker w3 = new Worker("王五", 27, 3200);
list.add(w3);
Worker w4 = new Worker("赵六", 24, 3300);
list.add(1, w4);
list.remove(w3);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
Iterator<Worker> it = list.iterator();
while (it.hasNext()) {
it.next().work();
}
}
}
```
输出:
```
Name: 张三, Age: 30, Salary: 3000
Name: 赵六, Age: 24, Salary: 3300
Name: 李四, Age: 25, Salary: 3500
```
```
张三 is working.
赵六 is working.
李四 is working.
```
阅读全文