0

After adding objects to an ArrayList, is there a way to print the values of the objects from the ArrayList?

I have a class with getMake(), getModel(), and getPrice() but I don't know how to use them after adding the objects to the ArrayList.

    Car car1 = new Car("make1", "model1", 40000);
    Car car2 = new Car("make2", "model2", 200000);
    Car car2 = new Car("make3", "model3", 100000);

    ArrayList<Car> cars = new ArrayList<Car>();

    cars.add(car1);
    cars.add(car2);
    cars.add(car3);

1 Answers1

2

Your Car class must override Object#toString()

public class Car {
    private String make;
    private String model;
    private int price;

    // your code here

    @Override
    public String toString() {     return "Make: " + make +  ", Model:" + model + ", Price: " + price;

    }
}
hfontanez
  • 5,774
  • 2
  • 25
  • 37