B
B
BitNeBolt2020-10-22 14:36:04
Java
BitNeBolt, 2020-10-22 14:36:04

How to correctly implement Comparable in this case?

I have a Vector3 structure that has three coordinates on each of their axes. For the algorithm, I need to check if an element is contained in a set.

How can I make the set check the elements according to my rule, and not according to its own?

I tried to implement Comparable, but did not get the desired result:

Implementation

@Override
    public int compareTo(Object o)
    {
        Vector3 vector3 = (Vector3) o;

        if (x == vector3.getX() && y == vector3.getY() && z == vector3.getZ())
            return 0;
        
        else return -1;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BorLaze, 2020-10-22
@BitNeBolt

In a set - is it in a Set? Then you need to override equals and hashCode.
Comparable is needed for sorting.
ZY: compareTo, by the way, is also incorrectly written. This implementation returns either equal to (0) or less than (-1). A should return -1 / 0 / 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question