Comparing values in any order

I though this was a common problem, but i can’t find any solution to it.

There’s an enum, something like

public enum MyEnum { C, G, A, T, U }

I need to compare one enum instance with another, like this:

C complements G
G complements C
A complements T
T complements A
U complements T
T complements U

How can i do it without writing code like this:

public boolean complements(MyEnum other) {
    if(this.compareTo(C) == 0) {
        if(other.compareTo(G) {
            return true;
        } else return false;
    }
    ...
}

Thanks in advance.

Answer

Why not have a complements field? You can have it be an EnumSet.

enum MyEnum {
    G, C, A, T, U;

    static {
        C.complements = EnumSet.of(G);
        G.complements = EnumSet.of(C);
        A.complements = EnumSet.of(T);
        T.complements = EnumSet.of(A, U);
        U.complements = EnumSet.of(T);
    }

    private EnumSet<MyEnum> complements;

    public boolean complements(MyEnum other) {
        return complements.contains(other);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *