I have array variable declared like this:
public class carshop {
int numofcars = 0;
int maxcars = 10;
ACar[] allCars;
private CarShop;
public CarShop() { //Car Constructor
maxcars = maxE;
allCars = new ACar[maxcars];
}
}
In my coding example, every time a user adds a new car (via string input), it will increase the numofcars by 1. I have tried changing the array type into a arraylist
ArrayList<ACar> allCars = new ArrayList<ACar>(Arrays.asList());
I changed the allCars = new ACar[maxcars]; line into this: allCars = ACar.add(maxcars);
However now eclipse is giving me errors saying "The method add(int) is undefined for the type ACar".
Can you tell me what I have done wrong? Sorry if I have explained this poorly.
1 Answer 1
ACar is an array so it doesn't have the add() method and you need to insert values by doing ACar[x] = value;
If you want to easily convert an array to a List you can just do:
List<ACar> carList = Arrays.asList(allCars);
or for ArrayList specifically:
ArrayList<ACar> carList = new ArrayList<ACar>(Arrays.asList(allCars));
However you should also think about why you have both an array and an ArrayList. You could instead just be doing:
List<ACar> carList = new ArrayList<ACar>(maxCars);
The maxCars variable is optional, you don't need to set the initial size of an ArrayList unless you are trying to optimise the code.
ACar? How is it defined?add?carshopbut your constructor is forCarShop. Now why are you trying to calladdat all in your initialization? And why are you reinitializing the variable when you've already got an initializer? That initializer could be simpler as:List<ACar> allCars = new ArrayList<>();as well...