2

I am not getting a match when using the containsKey method on a Map of this custom object type:

Custom Apex Type

public class StateTransition
{
    final ProcessState CurrentState;
    final Command Command;

    public StateTransition(ProcessState currentState, Command command)
    {
        CurrentState = currentState;
        Command = command;
    }

    public Integer hashCode()
    {
        return 17 + 31 * CurrentState.hashCode() + 31 * Command.hashCode();
    }

    public Boolean equals(Object obj)
    {
        StateTransition other = (StateTransition) obj;
        return other != null && this.CurrentState == other.CurrentState && this.Command == other.Command;
    }
}

Both ProcessState and Command are Enum types.

What is wrong with the implementation of hashCode and equals?

1 Answer 1

2

I believe your problem is the naming conflict in your constructor. When you use the pattern you have, your code simply reassigns the constructor parameter, rather than the object attribute. If they have the same name, you need to use this. to reference the attribute instead of the constructor parameter.

public class MyClass
{
    public Foo param1;
    public Bar param2;
    public MyClass(Foo param1, Bar param2)
    {
        this.param1 = param1;
//      ^^^^^
        this.param2 = param2;
//      ^^^^^
    }
}

It is easy enough to verify your attributes are not being set via an anonymous script:

Enum ProcessState { FOO, BAR }
Enum Command { FOO, BAR }

class StateTransition
{
    final ProcessState CurrentState;
    final Command Command;
    StateTransition(ProcessState currentState, Command command)
    {
        CurrentState = currentState;
        Command = command;
    }
}

StateTransition demo = new StateTransition(ProcessState.FOO, Command.BAR);
system.assertEquals(null, demo.CurrentState);
system.assertEquals(null, demo.Command);
3
  • Do I even need the custom implementations of hashCode and equals?
    – Robs
    Mar 15, 2019 at 22:03
  • 2
    @Robs for using it in containsKey, yes you do.
    – sfdcfox
    Mar 15, 2019 at 22:21
  • 1
    @Robs - If you use ApexMocks for unit testing, you also may need hashCode and equals as ApexMocks matchers need these helpers
    – cropredy
    Mar 16, 2019 at 1:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .