-1

我创建了一个 Java 类,我正在尝试学习如何ArrayList工作。

假设我有一个名为Complex. 在那个类中,我们有HousesEmployees,所有这些都是单独的类。

如果我想创建一个ArrayList我会怎么做?

元素的数量是动态的,所以当有人说添加新房子时,我会调用那个询问与房子有关的问题的方法,然后它将所有这些都添加到我假设的列表中?

4

2 回答 2

1

要创建一个ArrayList包含类型对象的对象House,您可以执行以下操作:

ArrayList<House> houseList = new ArrayList<House>();

houseList.add(new House());

遍历列表中的所有项目

for(House house:houseList){
   // do something with the house object
}

请参阅文档以了解其他功能。

于 2013-02-15T23:57:52.743 回答
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;
        }


    }
}
于 2013-02-16T00:01:28.703 回答