Junior — Middle
Can a non-string value be used as a key in an object?
sobes.tech AI
Answer from AI
In Java (and, in particular, in Android), the key in standard objects like HashMap can be an object of any class, not necessarily a string. The main requirement is that this object correctly implements the equals() and hashCode() methods. For example, you can use Integer, Enum, or your own classes as keys.
Example:
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
String value = map.get(1); // "one"
However, if you use a regular object without overriding equals and hashCode, the behavior can be unexpected, as keys are compared using these methods. Unlike JavaScript, where object keys are always converted to strings, in Java, keys in a Map can be any objects.