开发者

Create a Java method that will return the size of an ArrayList [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_StackOverflow Closed 9 years ago.

I'm new to Java programming and need to create a method called sizeofCarPark that returns the amount of cars that are stored in a Car Park. I'd appreciate some pointers in what I need to do.


What kind of an Object is a Car Park?

ArrayList already has a size() method.

Example:

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

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


If your "CarPark" is-a collection of cars only:

int totalCars = myCarPark.size();

If your "CarPark" has-a collection of cars only (preferred solution!):

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

If your "CarPark" is-a mixed collection, then you have to iterate and count:

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

Hope it helps!


Just do yourList.size()?


I suppose you are meant to create a custom container class instead of using one of the Collection classes for that purpose.

Here's a little hint. Suppose you have a NumberBox class which stores a list of, err, ints. In order to maintain the number of elements, besides the array which holds the elements, you need some sort of counter. Let's call it size. Initially, size is set to 0. Then you have a method to add and remove elements, as well as a method which returns the current size. An implementation would look something like this (not a complete program, missing stuff like checking parameters e.g.).

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
    }
}

Now what you need to do is think about how to apply this to your class.


See ArrayList (Java 2 Platform SE v1.4.2).. The javadoc is always the best place to start. There's already a size() method that does it, so all your method needs to do is call on that and return its value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜