将表格中的数据存储在List中,将同一种数据包装在一个实体类中,作为一个Object对象存储在List中
ID | 姓名 | 薪水 | 单位 | 入职时间 |
0301 | aaa | 3000 | 项目部 | 2007-09 |
0302 | bbb | 3100 | 教学部 | 2006-11 |
0303 | ccc | 3500 | 教学部 | 2006-10 |
先构建一个Employee的实体类,将数据封装成一个Object对象。
package cn.liu.tree2;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Employee {
private int id;
private String name;
private int salary;
private String department;
private Date hireDate;
public Employee(int id, String name, int salary, String department, String hireDate) {
super();
this.id = id;
this.name = name;
this.salary = salary;
this.department = department;
DateFormat format = new SimpleDateFormat("yyyy-MM");
try {
this.hireDate = format.parse(hireDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Date getHireDate() {
return hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
}
第一种方法:储存在List中。
package cn.liu.tree2;
import java.util.ArrayList;
import java.util.List;
public class test01 {
public static void main(String[] args) {
Employee e1=new Employee(0301,"aaa",3000,"项目部","2007-10");
Employee e2=new Employee(0302,"bbb",3500,"教学部","2007-10");
Employee e3=new Employee(0303,"ccc",3500,"项目部","2006-10");
List<Employee> list=new ArrayList<Employee>();
list.add(e1);
list.add(e2);
list.add(e3);
printEmployeeName(list);
}
public static void printEmployeeName(List<Employee> list) {
for (int i=0;i<list.size();i++) {
System.out.println(list.get(i).getName());
}
}
}
第二种方法:存储在map中:
package cn.liu.tree2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class test02 {
public static void main(String[] args) {
Map map=new HashMap();
map.put("id", 0301);
map.put("name", "aaa");
map.put("salary", 3000);
map.put("department", "项目部");
map.put("hireDate", "2007-10");
Map map2=new HashMap();
map2.put("id", 0301);
map2.put("name", "bbb");
map2.put("salary", 3500);
map2.put("department", "项目部");
map2.put("hireDate", "2007-10");
Map map3=new HashMap();
map3.put("id", 0303);
map3.put("name", "ccc");
map3.put("salary", 3550);
map3.put("department", "教学部");
map3.put("hireDate", "2006-10");
List<Map> list =new ArrayList<Map>();
list.add(map);
list.add(map2);
list.add(map3);
print(list);
}
public static void print(List<Map> list) {
for(int i=0;i<list.size();i++) {
Map tempmap=list.get(i);
System.out.println(tempmap.get("name")+"--"+tempmap.get("salary"));
}
}
}