I was trying to join the elements of an array via the StringUtils.join(array, separator)
method from the Apache commons library. Can anyone please explain me why I cannot get the resulting string and only a pointer to its location if I use an array of primitive types like int[]
?
Please see example code below:
public static void main(String[] args){
String[] s = new String[]{"Anna","has", "apples"};
System.out.println(StringUtilities.join(s, " "));
int[] a = new int[]{1,2,3};
System.out.println(StringUtilities.join(a, " "));
Integer[] b = new Integer[]{1,2,3};
System.out.println(StringUtilities.join(b, " "));
}
Only using Integer
arrays works. I understood that arrays of primitives are internally treated differently than ArrayList or other higher order objects, but then why is it possible (same topic more or less but a different question maybe) to instantiate a HashMap<String, int[]>
without any warnings, exceptions? Are the arrays internally wrapped in another object? Only for maps? From what I read from the doc you cannot parametrize a map, set, array list etc with primitive types, which I understand, but then... I find it a bit confusing. Any reasonable explanation would be appreciated. Thank you.
Take a look at the signature for int
arrays of StringUtils#join
:
join(byte[] array, char separator)
You called join
using
StringUtils.join(a, " "),
using a String instead of a char. Try using
StringUtils.join(a, ' ')
instead.
What happened is that your call matched another signature:
join(T... elements),
so your arguments get interpreted as two objects, an integer array and a String with a space character. While creating the result string, the method concatenated the string representation of the integer array with the string.
An array of ints (a primitive) is an object.
I suspect the implementation doesn't support primitive arrays, and calls toString()
on them, resulting in something like [I@659e0bfd
(which translates to single dimensional (only one [
) array of I
nts and its "memory location").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With