2

I have a task to change a type of a variable into ArrayList and I need to initialize it as an ArrayList. I don't know how to do it :(

I tried this in a such way:

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;
}

But I think it isn't correct. The source code which I need to change is below:

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;
}

Could someone give me any tips or explain me what I need to use here a generic type ArrayList?

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
Anna K
  • 1,388
  • 3
  • 18
  • 34

1 Answers1

3

Start by declaring the warehouseContent type as a list of WarehouseItem:

private List<WarehouseItem> warehouseContent = new ArrayList<>();

Now you can rely on ArrayList's built-in ability to grow in your registerProducts method:

public void registerProducts(Product... products) {
    for (Product product : products) {
        warehouseContent.add(new WarehouseItem(product));
    }
}

This one loop does what the two loops and an allocation of your original implementation did. Note that copying the content of an old array into the new one is still there, but it is encapsulated in the add method of ArrayList.

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
  • Thank you :) but in the line for (Product : products) I have an error "Syntax error on token "Product", Identifier expected after this token" and warehouseContent.add(new WarehouseItem(product)); error: product cannot be resolved to a variable – Anna K Jan 10 '16 at 12:37