'How to increase array size and copy the elements into the new array? [duplicate]

I have the following classes:

Point

public class Point {

    public Integer x;
    public Integer y;

    public Point(Integer x, Integer y) {
        this.x = x;
        this.y = y;
    }

PointSet

public class PointSet {

    private Point[] arr;
    private int index = 0;

    public PointSet(int capacity) {
        arr = new Point[capacity];
    }

    public PointSet() {
        this(10);
    }

In the PointSet class, I need to implement a method which can add a Point to the internal array and if there is no more room the array size should be doubled and still keeping its original elements.

How can I implement a method which returns a new array with double size and the elements of the internal array?

I am stuck because the default constructor takes 10 as a default value and I can't find a way to double it. I also have to use arrays, so using a list or set won't be an option. Thanks.



Solution 1:[1]

As others have already said, once an array has been instantiated its size is fixed, so you will have to instantiate a new array, copy the previous content within the new one and ultimately assign the new array to your class' field.

In order to do so, you should define a method in your PointSet class to perform the previous operations.

private void extendCapacity() {
    Point[] temp = new Point[arr.length * 2];
    for (int i = 0; i < arr.length; i++) {
        temp[i] = arr[i];
    }
    arr = temp;
}

So, if you have an add method to insert a new Point, it should look like something like this:

public void add(Point p) {
    if (index == arr.length) {
        extendCapacity();
    }
    arr[index++] = p;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan