Accessor Methods

AP Computer Science A· difficulty 3/5

public class Group {
    private int[] data;
    public Group(int[] d) {
        data = new int[d.length];
        for (int i = 0; i < d.length; i++) data[i] = d[i];
    }
    public int[] getData() {
        int[] copy = new int[data.length];
        for (int i = 0; i < data.length; i++) copy[i] = data[i];
        return copy;
    }
}
// ...
int[] a = {1, 2, 3};
Group g = new Group(a);
int[] view = g.getData();
view[1] = 100;
System.out.println(a[1] + "," + g.getData()[1]);

What is printed?

  • A

    2,100

  • B

    100,100

  • C

    100,2

  • D

    2,2

    check_circle

Explanation

Both the constructor and accessor make defensive copies, so neither g's data nor a are affected by changes to view.

Want 10 more like this — adaptive to your weak spots?

Related questions