创建一个将返回ArrayList大小的Java方法

时间:2010-10-25 17:39:51

标签: java

我是Java编程的新手,需要创建一个名为sizeofCarPark的方法,该方法返回存储在停车场中的汽车数量。我非常感谢我需要做的一些事情。

5 个答案:

答案 0 :(得分:3)

什么样的物体是停车场?

ArrayList已经有size()方法。

示例:

public class CarPark {
    private List<Car> cars = new ArrayList<Car>();

    public int sizeOfCarPark() {
        return cars.size();
    }
}

答案 1 :(得分:2)

如果您的“CarPark”只是一个汽车系列:

int totalCars = myCarPark.size();

如果您的“CarPark”仅拥有汽车系列(首选解决方案!):

int totalCars = myCarPark.getCars().size();

如果您的“CarPark”混合收藏品,那么您必须进行迭代并计算:

int count = 0;
for (Object obj:myCarPark)
  if (obj instanceof Car) count++;

希望它有所帮助!

答案 2 :(得分:0)

只做yourList.size()

答案 3 :(得分:0)

ArrayList (Java 2 Platform SE v1.4.2) .. javadoc始终是最佳起点。已经有了一个size()方法,所以你需要做的就是调用它并返回它的值。

答案 4 :(得分:0)

我认为您打算创建一个自定义容器类,而不是为此目的使用其中一个Collection类。

这里有一点提示。假设您有一个NumberBox类,它存储了一个错误的int列表。为了保持元素的数量,除了包含元素的数组之外,还需要某种计数器。我们称之为size。最初,size设置为0。 然后,您有addremove元素的方法,以及返回当前size的方法。 一个实现看起来像这样(不是一个完整的程序,缺少像检查参数这样的东西,例如。)。

public class NumberBox {
    private int[] list;
    private size = 0;

    public class NumberBox(int capacity) {
        list = new int[capacity];
    }

    public void add(int i) {
        // put the int at the first unoccupied position
        // increase the counter
    }

    public int remove() {
        // remove the last int which was inserted
        // decrement the counter
        // return it
    }

    public size() {
        return size; // return the current size
    }
}

现在你需要做的是考虑如何将它应用到你的班级。