Search code examples
javagenericsgeneric-programming

Populating generic array in java


I am trying to populate an array of generic types but its always empty after the Array.fill i am using here. What can I be doing wrong?

  private <T> CartField<T>[] getPopulatedCart(T field) {
    CartField<T> cart = new CartField<>(field);
    CartField<T>[] cartFields = new CartField[0];
    Arrays.fill(cartFields, cart);
    return cartFields;
  }

This always returns an empty array, i can verify when debugging that the cart field makes it, even when inspecting the cart on the same line as Arrays.fill(cartFields, cart) it shows the value but on the return the array is empty.

Any help or guidance would be appreciated.


Solution

  • Arrays.fill will populate every element of an array. Your array is of size zero, and so there are no array elements to populate.

    If you are expecting an array with a single element, you should initialize it to have size one instead.