我有一个任务要将变量的类型更改为ArrayList,我需要将其初始化为ArrayList。我不知道该怎么做:(
我试着这样做了:
private ArrayList<T> warehouseContent = new ArrayList<T>();
public void registerProducts(Product... products) {
WarehouseItem[] updatedWarehouseContent = new WarehouseItem[warehouseContent.size()
+ products.length];
int i = 0;
for (; i < warehouseContent.size(); i++) {
updatedWarehouseContent[i] = warehouseContent[i];
}
for (; i < updatedWarehouseContent.length; i++) {
updatedWarehouseContent[i] = new WarehouseItem(products[i - warehouseContent.size()]);
}
warehouseContent=updatedWarehouseContent;
}
但我认为这是不正确的。我需要更改的源代码如下:
private WarehouseItem[] warehouseContent = new WarehouseItem[0];
public void registerProducts(Product... products) {
WarehouseItem[] updatedWarehouseContent = new WarehouseItem[warehouseContent.length
+ products.length];
int i = 0;
for (; i < warehouseContent.length; i++) {
updatedWarehouseContent[i] = warehouseContent[i];
}
for (; i < updatedWarehouseContent.length; i++) {
updatedWarehouseContent[i] = new WarehouseItem(products[i - warehouseContent.length]);
}
warehouseContent=updatedWarehouseContent;
}
有人可以给我任何提示或解释我需要在这里使用通用类型ArrayList
吗?
答案 0 :(得分:3)
首先将warehouseContent
类型声明为WarehouseItem
的列表:
private List<WarehouseItem> warehouseContent = new ArrayList<>();
现在,您可以依靠ArrayList
的内置功能在registerProducts
方法中增长:
public void registerProducts(Product... products) {
for (Product product : products) {
warehouseContent.add(new WarehouseItem(product));
}
}
这一个循环执行两个循环和原始实现的分配。请注意,将旧数组的内容复制到新数组中仍然存在,但它已封装在add
的{{1}}方法中。