I have recently been trying to implement a simple genetic algorithm. I need to use an inversible map which stores pairs of (Character,4 bits)
. I chose Guava's BiMap
for this task. However tests will not pass because of an int
array which I chose for the bits storage.
Is int[]
a primitive type? Would the use of a Vector
or List
of integers be a more appropriate tool for this task?
Your problem is not that int[]
is a primitive. An array in Java is an object. The problem is that it is an object which does not override the hashCode()
and equals()
methods.
Since it doesn't override them, they are the same as those of Object, where objects are equal only if they are identical (i.e. references to the same instance).
Basically:
int[] a = new int[] {1,1,1,1};
int[] b = new int[] {1,1,1,1};
System.out.println( a.equals(b) );
You are probably expecting this to print true
, but it will print false
, because you created two distinct arrays, and it checks whether the arrays are the same object, not whether their content is the same!
In all probability, if you also add
System.out.println( a.hashCode() );
System.out.println( b.hashCode() );
You'll also get two different hash codes.
For this reason, arrays are not very suitable to use in collections that check for equality/uniqueness. They are good as the value in a standard Map
, but not as the key. And in a Guava BiMap
they can be used for neither key nor value.
What should you do?
You should use an object which overrides the equals()
and hashCode()
so that if the contents are the same, equals()
returns true
and the same value is returned from hashCode()
on both.
If you want something relatively compact, you can represent the bits with a Byte
object. You can use bit manipulation operators with it.
Or you can use a BitSet
which is a Java standard container for bits.
Be careful, as BitSet
is mutable. Mutable objects might not behave well when used in value-sensitive data structures like hash tables, because most implementations can't tell when you changed the value and so they can't move it around in the hash buckets accordingly. Don't set or clear any bits in the object once it is stored in the BiMap
!