How should one unit test the hashCode-equals contract?

前端 未结 8 1056
长发绾君心
长发绾君心 2020-12-07 13:18

In a nutshell, the hashCode contract, according to Java\'s object.hashCode():

  1. The hash code shouldn\'t change unless something affecting equals() changes
8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 13:21

    My advice would be to think of why/how this might ever not hold true, and then write some unit tests which target those situations.

    For example, let's say you had a custom Set class. Two sets are equal if they contain the same elements, but it's possible for the underlying data structures of two equal sets to differ if those elements are stored in a different order. For example:

    MySet s1 = new MySet( new String[]{"Hello", "World"} );
    MySet s2 = new MySet( new String[]{"World", "Hello"} );
    assertEquals(s1, s2);
    assertTrue( s1.hashCode()==s2.hashCode() );
    

    In this case, the order of the elements in the sets might affect their hash, depending on the hashing algorithm you've implemented. So this is the kind of test I'd write, since it tests the case where I know it would be possible for some hashing algorithm to produce different results for two objects I've defined to be equal.

    You should use a similar standard with your own custom class, whatever that is.

提交回复
热议问题