Does the "no primitives in container" rule apply to arrays?

I recently tried to implement a simple genetic algorithm. I need to use a reverse map that stores pairs (Character,4 bits)

. For this task, I chose Guava BiMap

. However, the tests will fail due to the array int

I chose to store the bits.

Is it a int[]

primitive type? Will the use of integers Vector

or List

a more suitable tool for this task?

+3


source to share


2 answers


Your problem is not what int[]

is primitive. An array in Java is an object. The problem is that this is an object that does not override hashCode()

andequals()

.

Since it doesn't override them, they are the same as Object, where objects are equal only if they are identical (for example, 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 probably expect this to print true

, but it will print false

because you created two different arrays and it checks if the arrays are the same object, not if their contents are the same!

In all likelihood, if you also add

System.out.println( a.hashCode() );
System.out.println( b.hashCode() );

      



You will also get two different hash codes.

For this reason, arrays are not very suitable for use in collections that check for equality / uniqueness. They are good as a value in the standard Map

, but not as a key. And in Guava BiMap

they can be used for neither key nor value.

What should you do?

You must use an object that overrides equals()

and hashCode()

, so that if the content is the same, it equals()

returns true

, and the same values ​​are returned from hashCode()

both.

If you want something relatively compact, you can represent bits with an object Byte

. You can use operators to manipulate it.

Or you can use BitSet

which is a standard Java container for bits.

Be careful as it is BitSet

changed. Editable objects can be misbehaving when used in data-sensitive data structures such as hash tables, as most implementations cannot tell when you changed a value and therefore cannot move it around in hash buckets accordingly. Do not set or clear any bits in the object after saving it to BiMap

!

+5


source


Is it a int[]

primitive type?

Not. Java arrays are not primitive types, even if their individual elements are primitive.

Would using a vector or a list of integers be the right tool for such a task?



Neither Vector<T>

nor List<T>

can they store primitives without "boxing" them in wrappers. However, if you only need four bits, you can use one byte

that has eight bits available for storage.

To extract a bit k

from byte

, use an expression (b & (1 << k)) != 0

. When this expression evaluates to true

, the bit is k

set to 1

; otherwise, it is set to 0

.

To set a bit k

in a byte to 1

, use b |= (1 << k)

. To reset a bit k

- 0

useb &= ~(1 << k)

+2


source







All Articles