I have a question about constructing an ArrayList, I have had a Car Class, now I need to make an ArrayList to put content in, I named it as Race, please see code below:
import java.util.ArrayList;
public class Race {
private ArrayList<Car>cars;
public Race(){
cars=new ArrayList<Car>();
}
Now I need to have a method for add content to the ArrayList, there are two ways to write that I am confused with:
First one
public void addCars(){
Car Toyota=new Car("Toyota",1.0,1.0,2.0,2.0);
Car Honda=new Car("Honda",1.0,2.0,1.0,2.0);
Car Mazda=new Car("Mazda",1.0,3.0,2.0,3.0);
Car Suzuki=new Car("Suzuki",1.0,4.0,4.0,2.0);
cars.add(Toyota);
cars.add(Honda);
cars.add(Mazda);
cars.add(Suzuki);
}
Second one
public void addCars(Object nm,String n, double s, double p, double a, double b){
Car name=new Car(n,s,p,a,b);
cars.add(name);
}
Both ways have no mistake reported when I coding, but I am not sure which one is correct, or maybe neither is correct, please help, cheers!
UPDATE:
public void addCars(Car car){
cars.add(car);
}
This is what I used finally, then I created a new class called Test that using main method to add cars individually, but there is mistake in the last line:
public class Test {
public static void main(String[] args) {
Car Toyota=new Car("Toyota",1.0,1.0,2.0,2.0);
**cars.addCars(Toyota);**
I have no idea how to fix it, please help!
Car's constructor arguments inaddCars()is usually not a correct approach. Instead defineaddCars(List<Car> cars)oraddCar(Car car)and construct the car to be added outside of the function.