简体   繁体   中英

How to change a array to a arraylist effectively

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM