0

I couldn't find any information in the official docs. I know that Boolean.hashCode(boolean b) returns the two primes 1231 and 1237 for true and false. I am hoping for a similar implementation in AtomicBoolean. But in the decompiled class file it appears to call public native int hashCode(); of Object - does that mean it will return the memory location?

jcfrei
  • 1,797
  • 4
  • 17
  • 34

4 Answers4

3

The package summary tells why hashCode is not overriden for AtomicBoolean:

Atomic classes are not general purpose replacements for java.lang.Integer and related classes. They do not define methods such as equals, hashCode and compareTo. (Because atomic variables are expected to be mutated, they are poor choices for hash table keys.)

does that mean it will return the memory location?

It depends on what JVM you use, but yes, it's usually derived from the memory address. Other JVMs may just use a random number.

4castle
  • 28,713
  • 8
  • 60
  • 94
2

AtomicBoolean doesn't override hashCode (or equals), so it inherits the default Object behavior.

This actually makes a lot of sense. The main use case of hashCode is to let the object be the key of a hash map, but it's dangerous to mutate keys once they're in a map. Since the main attribute of an AtomicBoolean is its mutability, this makes it a bad candidate for a HashMap key.

In other words: If you need it to be a HashMap key, you shouldn't mutate it, and if you don't intend to mutate it, then you shouldn't use an AtomicBoolean.

Community
  • 1
  • 1
yshavit
  • 39,951
  • 7
  • 75
  • 114
1

AtomicBoolean does not override the hashCode() (or equals(Object), for that matter) method. It uses the default implementation from java.lang.Object. Although it's not specified by the JLS, this implementation usually just returns the internal address of the object represented as an int.

Mureinik
  • 252,575
  • 45
  • 248
  • 283
0

java.util.concurrent.atomic.AtomicBoolean uses hashode of object method , which is not overridden in the class.so it uses defult hascode of object class.