JagWire
JagWire

Reputation: 269

KeyStroke class as a key in HashMap

Several answers regarding overriding equals() and hashCode() describe the need for both and the application of using them as keys in a HashMap in Java. My question is, is the Java KeyStroke class safe to put as a key in a HashMap? Further, so I'm not annoying and continue to ask these questions, how would one find out if a provided class (I think KeyStroke is provided by Swing) is safe to use in this context...i.e. overrides equals() and hashCode()?

thanks in advance!

Upvotes: 1

Views: 86

Answers (2)

Jeffrey
Jeffrey

Reputation: 44808

The way to see if equals and hashCode are overridden is to take a look at the API. hashCode and equals are not overridden in KeyStroke, but they are in AWTKeyStroke. In fact, AWTKeyStroke#hashCode states:

[this object is] a good choice as the index value in a hash table.

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Best if a HashMap key overrides equals and hashCode and is immutable, and if you check the API, KeyStroke is. So it should be fine.

Upvotes: 2

Related Questions