1

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.

Dan
  • 3,647
  • 5
  • 20
  • 26
lopaxxxkzz
  • 51
  • 4

1 Answers1

2

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;
}
Dan
  • 3,647
  • 5
  • 20
  • 26