Is this an immutable class? Is this an immutable class? arrays arrays

Is this an immutable class?


No, you can change what's in the Points array. If you want to make it immutable, have the getter hand out a copy of the Points array, not the original.

try this:

Triangle triangle = new Triangle(a, b, c);triangle.getPoints()[1] = null;System.out.println(Arrays.toString(triangle.getPoints()));

Also Point needs to be immutable (as Nikita Rybak points out). For how to copy arrays see how to copy an array in Java.


No, it's not. You expose the Point[] and a caller could modify its contents. Also, your class is not final, so someone could subvert it by subclassing it.


No, it's definitely mutable.

Not only do you expose the actual Point[] array, you don't defensive-copy (Bloch 2nd ed., Item 39) the Point objects themselves when taking them in via the constructor.

  1. The Point[] array could have itemsremoved or added to it, so it'smutable.
  2. You could pass in Points a, b, and c, then call setX() or setY() on them to change their data after construction.