Java集合-5. (List)已知有一个Worker 类如下: 完成下面的要求 1) 创建一个List,在List 中增加三个工人,基本信息如下: 姓名 年龄 工资 zhang3 18 3000 li4 25 3500 wang5 22 3200 2) 在li4 之前插入一个工人,信息为:姓名:zhao6,年龄:24,工资3300 3) 删除wang5 的信息 4) 利用for 循
第六题
5. (List)已知有一个Worker 类如下:
public class Worker
{ private int age;
private String name;
private double salary;
public Worker (){}
public Worker (String name, int age, double salary)
{ this.name = name;
this.age = age;
this.salary = salary; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getSalary(){ return salary; }
public void setSalary(double salary){ this.salary = salary; }
public void work(){
System.out.println(name + “ work”); } }
完成下面的要求
1) 创建一个List,在List 中增加三个工人,基本信息如下:
姓名 年龄 工资
zhang3 18 3000
li4 25 3500
wang5 22 3200
2) 在li4 之前插入一个工人,信息为:姓名:zhao6,年龄:24,工资3300
3) 删除wang5 的信息
4) 利用for 循环遍历,打印List 中所有工人的信息
5) 利用迭代遍历,对List 中所有的工人调用work 方法。
package Test03; public class Worker { private int age; private String name; private double salary; public Worker() { } public Worker(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public void work() { System.out.println(name + " work"); }
@Override
public String toString() {
return "Worker [age=" + age + ", name=" + name + ", salary=" + salary + "]";
}
}
package Test03; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class TestWorker { public static void main(String[] args) { List<Worker> list = new ArrayList<>(); list.add(new Worker("张三",18,3000)); list.add(new Worker("李四",25,3500)); list.add(new Worker("王五",22,3200)); list.add(1,new Worker("赵六",24,3300)); list.remove(3); for(int i = 0;i<list.size();i++) { System.out.println(list.get(i)); } System.out.println("迭代器方式"); Iterator<Worker> it= list.iterator(); //判断能否移动 while(it.hasNext()) { //移动指针到下一条数据,同事获取数据 Worker p=it.next(); System.out.println(p.toString()); } } }