8

Java provides way to define comparison of object outside scope Object using Comparator.

Now my questions is why java does not allow do same for equals() and hashcode().

Now each collection contains() method can easily use this external equality provider to check objects are equal.

4

3 に答える 3

3

Guavaには、Equivalenceあなたが求めていることをほぼ実行するクラスがあります。

オブジェクトをでラップEquivalenceして、より良いhashCode()equals()実装でオブジェクトを装飾することもできます(たとえば、マップキーとして悪いequals()hashCode()を持つオブジェクトを使用したいがアクセスできない場合ソースへ)

次に例を示します。配列にはequals()とhashCode()の適切な実装がありませんが、char配列の同等性は次のとおりです。

private static final Equivalence<char[]> CHAR_ARRAY_EQUIV = new Equivalence<char[]>(){

    @Override
    protected boolean doEquivalent(char[] a, char[] b) {
        return Arrays.equals(a, b);
    }

    @Override
    protected int doHash(char[] chars) {
        return Arrays.hashCode(chars);
    }
};

サンプルコード:

final char[] first ={'a','b'};
final char[] second ={'a','b'};

Assert.assertFalse(first.equals(second));
Assert.assertFalse(first.hashCode() == second.hashCode());

final Wrapper<char[]> firstWrapped = CHAR_ARRAY_EQUIV.wrap(first);
final Wrapper<char[]> secondWrapped = CHAR_ARRAY_EQUIV.wrap(second);

Assert.assertTrue(firstWrapped.equals(secondWrapped));
Assert.assertTrue(firstWrapped.hashCode() == secondWrapped.hashCode());
于 2012-09-12T14:42:05.207 に答える
0

Comparator interface is used to compare objects while sorting collections, and its compare() method returns an "int", means, comparision ends with an int value, which can be used to indicate object's place in a sorted collection.

contains() calls equals() method for each instance in a collection in order to find out whether two instances are equal according to equals- contract.

于 2012-09-12T14:23:45.463 に答える
0

equals and hashCode are concepts that don't change for a given Object. Only the implementor knows what values should be used according to the rules for these methods. Once he decided about those they define the identy of the object and thus should not be changed ever.

Comparasion on the other hand can be highly dependent on the context. You can define a "natural" order by implementing Comparable. But this can't change for different contexts. Say you have a list of Contacts that can be sorted by last name, first name, zip code, city... You can easily do this by providing separate Comparators (or a parametrized Comparator). But it is not inherent to the object itself so it should be a class of its own (it could be implemented as static inner class, depending on your code conventions).

于 2012-09-12T14:36:37.940 に答える