1

I cannot figure out why calling getBytes() twice on a String returns two byte arrays that are not equal():

final String aString = "hello world";
System.out.println(aString.getBytes());
System.out.println(aString.getBytes());
System.out.println(aString.getBytes());

Prints:

[B@59887d29
[B@fd13cab
[B@71e606a9

E.g. the following assertion always fails:

Assert.assertEquals(aString.getBytes(), aString.getBytes());

From the doc, I wasn't expecting any nondeterminism! What am I missing?

When converting back to String, the result is the expected one, so my best guess is some uninitialized padding bit?

I.e. the following assertion always passes:

Assert.assertEquals(new String(aString.getBytes()), new String(aString.getBytes()));
Marco
  • 588
  • 1
  • 4
  • 15
  • Combination of http://stackoverflow.com/questions/4479683/java-arrays-printing-out-weird-numbers-and-text and http://stackoverflow.com/questions/8777257/equals-vs-arrays-equals-in-java – Sotirios Delimanolis Dec 19 '14 at 23:53

2 Answers2

6

Assert#assertEquals(Object, Object) uses Object#equals(Object) to compare its arguments, but array types don't override that method. So two array instances will always be different.

Use Assert#assertArrayEquals(byte[], byte[]) to compare arrays of type byte.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
4

The problem is that getBytes() returns a byte[], and arrays are Objects in Java. However, these array objects don't override Object's toString() method, which is responsible for the output you see.

In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

The output includes the hash code, which is different for every object, even if the contents are the same.

Use Arrays.toString to obtain a String with the contents of the array, e.g.

System.out.println(Arrays.toString(aString.getBytes()));

3 times. New output:

[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Thanks, that explains the different output of println, but why is assertEqual returning false? – Marco Dec 20 '14 at 00:00
  • While my answer explains the string output, Sotirios's answer explains why better, with the solution included. – rgettman Dec 20 '14 at 00:03