67,538
社区成员
发帖
与我相关
我的任务
分享
import java.util.ArrayList;
import java.util.List;
public class CompanyList {
private List companys = new ArrayList() ;
public List getCompanys() {
return companys;
}
public void add(Company com){
companys.add(com) ;
}
public Company getCompany(int id){
for (int i = 0; i < companys.size(); i++){
if (((Company)companys.get(i)).getId() == id){
return (Company)companys.get(i) ;
}
}
return null ;
}
/**
* @param args
*/
public static void main(String[] args) {
CompanyList comList = new CompanyList() ;
//自己查数据库得到数据,此处手工创建数据
comList.add(new Company(1, "单位1")) ;
comList.add(new Company(2, "单位2")) ;
comList.add(new Company(3, "单位3")) ;
comList.add(new Company(4, "单位4")) ;
Company com = null ;
Department dept = new Department(1, 1, "部门1") ;
com = comList.getCompany(dept.getCompanyId()) ;
if (com != null ){
com.add(dept) ;
}
dept = new Department(1, 1, "部门2") ;
com = comList.getCompany(dept.getCompanyId()) ;
if (com != null ){
com.add(dept) ;
}
dept = new Department(1, 2, "部门3") ;
com = comList.getCompany(dept.getCompanyId()) ;
if (com != null ){
com.add(dept) ;
}
dept = new Department(1, 3, "部门1") ;
com = comList.getCompany(dept.getCompanyId()) ;
if (com != null ){
com.add(dept) ;
}
List list = comList.getCompanys() ;
for (int i = 0 ;i < list.size(); i++){
com = (Company)list.get(i) ;
System.out.println(com.getName()) ;
com.printDept() ;
}
System.out.println("***打印结束***");
}
}
import java.util.ArrayList;
import java.util.List;
public class Company {
private int id ;
private String name ;
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 List getDepartments() {
return departments;
}
public void setDepartments(List departments) {
this.departments = departments;
}
//getter and setter ;
private List departments = new ArrayList() ;
public void add(Department dept){
departments.add(dept) ;
}
public Company() {
}
public Company(int id, String name) {
this.id = id;
this.name = name;
}
public void printDept() {
List list = this.getDepartments() ;
Department dept = null ;
for (int i = 0; i <list.size(); i++){
dept = (Department ) list.get(i) ;
System.out.println(" --" + dept.getName()) ;
}
}
}public class Department {
private int id;
private int companyId ;
public int getCompanyId() {
return companyId;
}
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
private String name;
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 Department() {
}
public Department(int id, int companyId, String name) {
super();
this.id = id;
this.companyId = companyId ;
this.name = name;
}
}