标签:
第六题
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 方法。
packageTest03;public classWorker {private intage;privateString name;private doublesalary;publicWorker() {
}public Worker(String name, int age, doublesalary) {this.name =name;this.age =age;this.salary =salary;
}public intgetAge() {returnage;
}public void setAge(intage) {this.age =age;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}public doublegetSalary() {returnsalary;
}public void setSalary(doublesalary) {this.salary =salary;
}public voidwork() {
System.out.println(name+ " work");
}
@Override
public String toString() {
return "Worker [age=" + age + ", name=" + name + ", salary=" + salary + "]";
}
}
packageTest03;importjava.util.ArrayList;importjava.util.Iterator;importjava.util.List;public classTestWorker {public static voidmain(String[] args) {
List 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
{
System.out.println(list.get(i));
}
System.out.println("迭代器方式");
Iterator it=list.iterator();//判断能否移动
while(it.hasNext())
{//移动指针到下一条数据,同事获取数据
Worker p=it.next();
System.out.println(p.toString());
}
}
}
标签: