简体   繁体   中英

Common equals method for interface implementations

This is possibly a code smell but I was wondering if this might be possible in Java. Given that I have my interface:

public interface State {
    String getStateName();
}

and I have one implementation like this:

public class DefaultState implements State {
    final String stateName;

    public DefaultState(String stateName) {
        this.stateName = stateName;
    }

    @Override
    public String getStateName() {return stateName; }

    @Override
    public boolean equals(Object other) {
        return ((State)other).getStateName().equals(this.stateName);
    }
}

and another like this:

public enum EnumState implements State {
    STATE_1("STATE1"),STATE_2("STATE_2");

    final String stateName;
    
    EnumState (String stateName) {
        this.stateName = stateName;
    }

    @Override
    public String getStateName() {return stateName; }
}

When I do the following it fails because I cant override how equals is implemented in the enumeration:

assertTrue(Arrays.asList(new DefaultState("STATE1")).contains(EnumState.STATE_1)); // fails

Is there a way of making this work or is the ultimate answer you shouldn't be mixing implementations like that?

The line Arrays.asList(new DefaultState("STATE1")).contains(EnumState.STATE_1) use contains method, the implementation of this method use the equals method of the parameter (Enum here) for the comparaison, so it will return false because it will compare if this is the same Enum instance or not.

You cannot override equals on Enums, so a possible solution is to stream and find any element that match your condition using the equals overriden in the DefaultState class:

assertTrue(Arrays.asList(new DefaultState("STATE1"))
                              .stream()
                                    .anyMatch(state -> state.equals(EnumState.STATE_1)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM