I have no idea what immutable class should look like but am pretty sure this one is. Am I right? If I'm not please specify what should be added/removed.
import java.io.Serializable; public class Triangle implements IShape, Serializable { private static final long serialVersionUID = 0x100; private Point[] points; public Triangle(Point a, Point b, Point c) { this.points = new Point[]{a, b, c}; } @Override public Point[] getPoints() { return this.points; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() != obj.getClass()) return false; Point[] trianglePoints = ((Triangle) obj).getPoints(); for (int i = 0; i < points.length; i++){ if (!points[i].equals(trianglePoints[i])) return false; } return true; } } Will this do the trick?
@Override public Point[] getPoints() { Point[] copyPoint = { new Point(points[0]), new Point(points[1]), new Point(points[2]),}; return copyPoint; } Point class:
import java.io.Serializable; public class Point implements Serializable { private static final long serialVersionUID = 0x100; public int x; public int y; public int z; public Point(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public Point(Point that) { this.x = that.x; this.y = that.y; this.z = that.z; } public boolean equals(Object obj) { // assume this is a typical, safe .equals implementation // that compares the coordinates in this instance to the // other instance return true; } }
ImmutableListto begin with.final class Triangleanyway?Pointhas public, non-final fields... aPointis a textbook example of something that should be immutable too. =(