我创建了一个Java类,我正在尝试了解ArrayList
的工作原理。
假设我有一个名为Complex
的顶级课程。在该课程中,我们有Houses
,Employees
等,其中所有这些都是单独的类。
如果我想创建一个ArrayList
我该怎么做呢?
元素的数量是动态的,所以当有人说添加新房子时,我会调用那个询问有关房子的问题的方法,然后将这些全部添加到我假设的列表中?
答案 0 :(得分:1)
要创建一个ArrayList
来保存House
类型的对象,您可以执行以下操作:
ArrayList<House> houseList = new ArrayList<House>();
houseList.add(new House());
循环遍历列表中的所有项目
for(House house:houseList){
// do something with the house object
}
请参阅the documentation了解其他功能。
答案 1 :(得分:0)
试试这个。我将主要写给你;)
import java.util.ArrayList;
public class Complex {
private ArrayList<House> houses;
private ArrayList<Employee> employees;
public void addEmployee(String firstName, String secondName, boolean lazy){
if(employees == null)
employees = new ArrayList<Complex.Employee>();
employees.add(new Employee(firstName, secondName, lazy));
}
public void addHouse(String color, boolean withRoof){
if(houses == null)
houses = new ArrayList<Complex.House>();
houses.add(new House(color, withRoof));
}
class House{
private String color;
private boolean withRoof;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isWithRoof() {
return withRoof;
}
public void setWithRoof(boolean withRoof) {
this.withRoof = withRoof;
}
public House(String color, boolean withRoof) {
super();
this.color = color;
this.withRoof = withRoof;
}
}
class Employee{
private String firstName;
private String secondName;
boolean lazy;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public boolean isLazy() {
return lazy;
}
public void setLazy(boolean lazy) {
this.lazy = lazy;
}
public Employee(String firstName, String secondName, boolean lazy) {
super();
this.firstName = firstName;
this.secondName = secondName;
this.lazy = lazy;
}
}
}