如何将数组更改为ArrayList? (泛型)

时间:2016-01-10 12:21:37

标签: java generics arraylist

我有一个任务要将变量的类型更改为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吗?

1 个答案:

答案 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}}方法中。