I am trying to create a program in which – I am putting this as simply as possible – I find the sides of a triangle.
The problem with doing so is that there might be another triangle that has already been found with the exact same sides. For example:
If the program find a triangle with sides 1, 2, 1 and another with 1, 1, 2, then, because of the rules of what I am doing, I will not need to use this triangle again since it has the same sides, just in a different order.
I would like to create a class that I can enter the triangle values in, like = new triangle(x,y,z) where x, y, and z are all integers of the sides.
This is not the problem, as I already have the class. The question is how I can check to see if the triangle has already been made with the same sides as the one I am entering?
Thanks.
Override
equalsandhashCodeofTriangleto detect “same” triangles, and keep aHashSet<Triangle>with allTrianglecreated so far.For instance, if you want to print the Triangles without duplicates, you could do:
where
Note: This approach requires that you create a new Triangle to check whether it is a duplicate. One could extends the approach to work around object allocation, but this would complicate the code for little performance gain.