我创建了一个 Java 类,我正在尝试学习如何ArrayList
工作。
假设我有一个名为Complex
. 在那个类中,我们有Houses
等Employees
,所有这些都是单独的类。
如果我想创建一个ArrayList
我会怎么做?
元素的数量是动态的,所以当有人说添加新房子时,我会调用那个询问与房子有关的问题的方法,然后它将所有这些都添加到我假设的列表中?
要创建一个ArrayList
包含类型对象的对象House
,您可以执行以下操作:
ArrayList<House> houseList = new ArrayList<House>();
houseList.add(new House());
遍历列表中的所有项目
for(House house:houseList){
// do something with the house object
}
请参阅文档以了解其他功能。
尝试这个。我会把主要的写作留给你;)
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;
}
}
}