本文共 2152 字,大约阅读时间需要 7 分钟。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Worker {
private int age;
private String name;
private double salary;
public Worker(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public int getAge() {
return 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");
}
public static void main(String[] args) {
// 例子1
Worker work1 = new Worker("zhang3", 18, 3000);
Worker work2 = new Worker("li4", 25, 3500);
Worker work3 = new Worker("wang5", 22, 3200);
Worker work4 = new Worker("zhao6", 24, 3300);
// 定义列表list,类型是List,实际对象是ArrayList
// 类型定义为接口List,实际使用具体的实现类,属于面向接口编程,提高灵活性
List arrayList = new ArrayList<>();// 使用指定列表存放的类型是Worker类型
arrayList.add(work1);
arrayList.add(work2);
arrayList.add(work3);
arrayList.add(1, work4);
List linkedList = new LinkedList<>();// 使用指定列表存放的类型是Worker类型
System.out.println("总共有工人" + arrayList.size() + "个.");
for (int i = 0; i < arrayList.size(); i++) {
Worker worker = arrayList.get(i);// 不需要类型强转
System.out.println(worker.getName() + "\t" + worker.getAge() + "\t" + worker.getSalary());
}
// 例子2
// List不指定具体类型,不推荐
Worker work5 = new Worker("zhang3", 18, 3000);
List list2 = new ArrayList();// 使用指定列表存放的类型是Worker类型
list2.add(work5);
for (int i = 0; i < list2.size(); i++) {
Worker worker = (Worker) list2.get(i);// 从List拿到的是Object对象,需要类型强转为指定的Worker
System.out.println(worker.getName() + "\t" + worker.getAge() + "\t" + worker.getSalary());
}
// 例子3
// List不指定具体类型,存放的是Worker,实际取出来转换会出错
Worker work6 = new Worker("zhang3", 18, 3000);
List list3 = new ArrayList();// 使用指定列表存放的类型是Worker类型
list3.add(work6);
for (int i = 0; i < list3.size(); i++) {
Vehicle vehicle = (Vehicle) list3.get(i);// 从List拿到的是Worker对象,在类型强转为Vehicle会出错
}
// 例子4
// 定义列表list4,类型是ArrayList,实际对象是ArrayList,没用面向接口,不推荐
Worker work7 = new Worker("zhang3", 18, 3000);
ArrayList list4 = new ArrayList<>();// 使用指定列表存放的类型是Worker类型
list4.add(work7);
}
}
转载地址:http://wcyzo.baihongyu.com/