I am trying to create a program that creates triangles by storing their sides in the class below:
class Triangle {
private int[] sides;
public Triangle(int x, int y, int z) {
sides = new int[] {x,y,z};
Arrays.sort(sides);
}
@Override public boolean equals(Object o) {
return o instanceof Triangle && Arrays.equals(sides, ((Triangle) o).sides);
}
@Override public int hashCode() {
return Arrays.hashCode(sides);
}
@Override public String toString() {
return Arrays.toString(sides);
}
}
The problem is that I do not know how to create a new instance of these triangles from a for loop. For example, I am comparing the GCD of three numbers via a for loop, and I then want to add a new triangle to a set (discussed here). I believe I know how to everything but create a new instance of the class because, during the loop, there is no way for me to create unique instances of the triangle class.
Is there any way to do this?
Try this:
The Set will automatically avoid duplicates.