How to use the interface as a card key

I am looking for help on this, how to use the interface as a card key. I tried to implement the solution and did not receive errors in compiletime, but runtime errors while executing my integration tests. Is it not possible to use the interface as a key, or is it my tests, is something wrong with?

My code looks something like this:

private Map<AInterface, Values> myMap = new HashMap<AInterface, Values>();

After returning the keyset from myMap, they contain objects with the expected Id, but are compared with not equal. Therefore, when using myMap.get (Object key), I get null, although there is an object with the same identifier. When using a specific class instead of an interface, all tests pass:

private Map<AClass, Values> myMap = new HashMap<AClass, Values>();

I read Generics , which states that for the Map you need to replace variables of type K and V with specific types, which are subtypes of the object.

Since the compiler does not give me any warnings when using the interface for K, I assumed that the tests have errors.

Does anyone have any experience using interfaces as a key on a card? And could he give me any hints of what I am doing wrong?

+3
source share
6 answers

Your classes should be implemented hashCodeand equals( explanation ; you should also familiarize yourself with the Map interface contract ).

+5

, , hashCode, equals. equals true, hashCode , , JVM "" ( Map) hashCode .

+2

. , HashMap Object.

, , - , - .

:

class MyKey {
    String name;

    public int hashCode() {
        return name.hashCode();
    }

    // assume suitable equals() implementation
}

Map<MyKey,Integer> myMap = new HashMap();

MyKey key1 = new MyKey();
key1.name = "Jimmy";

myMap.put(key1, 10);

key1.name = "Johnny";

myMap.get(key1);  // return null

- , HashMap () - . , - - .

+1

. , "generics". List Maps .

, myMap , ? , AClass - ?

( ).

, Wesho, -, equals ( ) , .

, hashcode equals : - UUID , ( ), ( ).

2

NPE myMap.get(AClass key), myMap null, ( ...)

3

hashcode UUID, . 128- UUID. , UUID UUID , UUID , . . getter UUID AClass, Map HashMap<UUID, Values> myMap , (, ;))

0

[...] , K V .

SO, , .

. " ", . , "K" "S" . "" : , , .

. , , Object. , : , , , . Java, Object, Java , Java. Map<int, String> , Map<String, int[]>.

0
source

If you are using the Apache Commons lang JAR, perhaps add this to your class.

public int hashCode() { 
    return HashCodeBuilder.reflectionHashCode(this);
}
0
source

Source: https://habr.com/ru/post/1723978/


All Articles