views:

1809

answers:

7

Say I have a car class with attributes make and registration, and i create an ArrayList to store them. How do I display all the elements in the ArrayList?

I have this code right now:

public Car getAll()
{
    for(int i = 0; i < cars.size(); i++) //cars name of arraylist
    {
        Car car = cars.get(i);  
        {
            return cars.get (i);
        }
    }
    return null;
}

It compiles fine but when I try it out in my tester class using this code:

private static void getAll(Car c1)
{
    ArrayList <Car> cars = c1.getAll(); // error incompatible type
    for(Car item : cars)
    {   
        System.out.println(item.getMake()
                + " "
                + item.getReg()
                );
    }
}

I am getting a error of incompatible type. Is my coding correct? If not can someone please show me how it should be?

Thank You

+1  A: 

You method getAll() does not get all. It returns the first car.

The return statement terminates the loop.

Darron
A: 

You are getting an error because your getAll function in the Car class returns a single Car and you want to assign it into an array.

It's really not clear and you may want to post more code. why are you passing a single Car to the function? What is the meaning of calling getAll on a Car.

Uri
+3  A: 

Are you trying to make something like this?

public List<Car> getAll() {
    return new ArrayList<Car>(cars);
}

And then calling it:

List<Car> cars = c1.getAll();
for (Car item : cars) {   
    System.out.println(item.getMake() + " " + item.getReg());
}
Esko Luontola
I think you're exactly right, except if you have a List<Car> cars, then why return a new list containing its elements instead of simply returning the original list: return cars;
nsayer
Better yet, you could return Collections.unmodifiableList(cars), which would protect the list from being modified by the class's users.
nsayer
You sir are a legend. It works! I spent 2 hours trying to do this and you did it in 2 mins. Thank You very very very much! :)
Yes, Collections.unmodifiableList() would probably be a wise choice. Although then it would be possible for the original class to modify the backing list, which might surprise the user of the returned unmodifiable list.
Esko Luontola
Thank you nsayer for that comment, i'm now using this: return Collections.unmodifiableList(cars);before with the first one when i compiled it game me a warning message, but now its gone.Thank you both for your help.
The original answer was missing the generic argument on the ArrayList construction. I've put it in. Generic types on methods (and constructors) can be inferred, but not yet on constructed types. Collections.unmodifiableList(cars) is the equivalent of Collections.<Car>unmodifiableList(cars). Note well the subtle difference between copying the list (normal practice) and creating a read-only view.
Tom Hawtin - tackline
A: 

It's not at all clear what you're up to. Your function getAll() should return a List<Car>, not a Car. Otherwise, why call it getAll?

If you have

Car[] arrayOfCars

and want a List, you can simply do this:

List<Car> listOfCars = Arrays.asList(arrayOfCars);

Arrays is documented Here.

nsayer
A: 

Hi sorry the code for the second one should be:

private static void getAll(CarList c1) {

ArrayList <Car> cars = c1.getAll(); // error incompatible type
for(Car item : cars)
{   
      System.out.println(item.getMake()
                       + " "
                       + item.getReg()
                       );
}

}

I have a class called CarList which contains the arraylist and its method, so in the tester class, i have basically this code to use that CarList class:

CarList c1; c1 = new CarList();

everything else works, such as adding and removing cars and displaying an inidividual car, i just need a code to display all cars in the arraylist.

getAll() should return a List<Car>, not a Car. And it shouldn't iterate through the list of cars, but rather just return the list as a whole.
nsayer
Thank you very much didnt know that.
Why use CarList instead of List<Car>? Does it do something more than what its name suggests?
Esko Luontola
The CarList is the name of the class where the ArrayList is in and all its methods such as add, remove etc.So basically its like this I have a Car class, that contains attributes of the Car etc, then I have the CarList class which has the arraylist and its functions to hold a car object, and I have a tester class which i basically use to test out the functions. It's abit hard to explain properly here.
A: 

Tangential: String.format() rocks:

public String toString() {
    return String.format("%s %s", getMake(), getReg());
}

private static void printAll() {
    for (Car car: cars)
        System.out.println(car); // invokes Car.toString()
}
Carl Manaster
A: 

Another approach is to add a toString() method to your Car class and just let the toString() method of ArrayList do all the work.

@Override
public String toString() {
    return "Car{" +
            "make=" + make +
            ", registration='" + registration + '\'' +
            '}';
}

You don't get one car per line in the output, but it is quick and easy if you just want to see what is in the array.

List<Car> cars = c1.getAll();
System.out.println(cars);

Output would be something like this:

[Car{make=FORD, registration='ABC 123'},
Car{make=TOYOTA, registration='ZYZ 999'}]
hallidave