Ziv Sion
Ziv Sion

Reputation: 165

Java add place to array with a limited number of places

I want to add place the "a" array: My code:

Integer[] a = new Integer[3];

I want that: "Integer[] a = new Integer[3]" become to: "Integer[] a = new Integer[4]"

I tried:

a.length += 1;

and:

a[] = a [a.length + 1];

Upvotes: 2

Views: 199

Answers (2)

papaya
papaya

Reputation: 1535

Arrays.copy() is your only solution. As suggested ArrayList<>() is also a possible solution.

But under the hood ArrayList<>() when it reaches its size limit, this is a highly tiresome thing when handling large lists in a small heap, and will run out of memory.

Also in my opinion, if you know about the size of your data. You better go with initialisation of an Array or initialise ArrayList<>(initial_size);

Upvotes: 0

Kevin Anderson
Kevin Anderson

Reputation: 4592

You can't change the size of an array. You can, however, replace the old array with a new one of the required size to which some or all of the contents of the old array have been copied:

    Integer a = new Integer[3];
    a[0] =1; a[1] = 2; a[2] = 3;
    System.out.println(Arrays.toString(a)); // Prints [1,2,3]

    a = Arrays.copyOf(a, 4);
    a[3] = 4;
    System.out.println(Arrays.toString(a)); // prints [1,2,3,4]

Upvotes: 1

Related Questions