简体   繁体   English

如何有效地将数组更改为arraylist

[英]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 在我的编码示例中,每次用户添加新车(通过字符串输入),都会使numofcars增加1。我试图将数组类型更改为arraylist

ArrayList<ACar> allCars = new ArrayList<ACar>(Arrays.asList());

I changed the allCars = new ACar[maxcars]; 我更改了allCars = new ACar[maxcars]; line into this: allCars = ACar.add(maxcars); 这行: allCars = ACar.add(maxcars);

However now eclipse is giving me errors saying "The method add(int) is undefined for the type ACar". 但是,现在eclipse给了我错误,说“类型ACar的add(int)方法未定义”。

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; ACar是一个数组,因此它没有add()方法,您需要通过执行ACar[x] = value;来插入值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:

ArrayList<ACar> carList = new ArrayList<ACar>(Arrays.asList(allCars));

However you should also think about why you have both an array and an ArrayList. 但是,您还应该考虑为什么同时拥有一个数组和一个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. maxCars变量是可选的,除非您试图优化代码,否则无需设置ArrayList的初始大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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