java--用一个对象实现集合
首先先建立一个类:
package collection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Employ {//javabean 实体类 java豆 只包含属性和 private int id; private String name; private int salary; private String department; private Date hiredata; DateFormat format=new SimpleDateFormat("yyyy-yy"); public int getId() { return id; } public void setId(int id) { this.id = id; } public Employ(int id, String name, int salary, String department, String hiredata) { super(); this.id = id; this.name = name; this.salary = salary; this.department = department; //this.hiredata = hiredata; DateFormat format=new SimpleDateFormat("yyyy-yy"); try { this.hiredata=format.parse(hiredata); } catch (Exception e) { // TODO: handle exception } } public Employ() { // TODO Auto-generated constructor stub } 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 getHiredata() { return hiredata; } public void setHiredata(Date hiredata) { this.hiredata = hiredata; } }
测试主函数:
package collection;
import java.util.ArrayList;
public class Datacuncu {
public static void main(String[] args) {
//一行记录一个对象来封装
Employ e=new Employ(0301,"kl",3000,"yc","2007-10");
Employ e1=new Employ(0301,"kla",3200,"ycs","2007-10");
Employ e2=new Employ(0301,"kls",3500,"yca","2007-10");
ArrayList<Employ>list=new ArrayList<Employ>();
list.add(e);
list.add(e1);
list.add(e2);
printEmploy(list);
}
public static void printEmploy(ArrayList<Employ> list) {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getName());
System.out.println(list.get(i).getHiredata());
System.out.println(list.get(i).getDepartment());
}
}
}
运行结果:
幸有我来山未孤