D
D
Domus2017-10-12 00:08:20
Java
Domus, 2017-10-12 00:08:20

How to implement a HashMap in which key is an object of the class I created?

Good afternoon!
Can you please tell me how can I use an object of my own class as a key? It only comes to mind to do some unambiguous transformation of the value of the variables of the Location class. For example, define a toString() method and use a String as the HashMap key. But in this case, further use of entry.getKey() is difficult. I specified the toString() method in the code, but did not use it. Are there better ways to get out of this situation?

class Hero{
    // Описание класа
}
class Location{
    private int m;
    private int n;

    int getM() {
        return m;
    }
    int getN(){
        return n;
    }
    String toString(){
        return "" + m + n;
    }
}

public class Main {

    public static void main(String[] args) {

        HashMap<Location, Hero> map = new HashMap<>();
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2017-10-12
@Domus

It is necessary to consistently implement the equals and hashCode methods. Consistently, if equals returned true, then hashCode will return the same number. The converse is not necessarily true.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question