Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - StringUtils.join() returning pointer

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.

like image 475
Marius Avatar asked Apr 28 '15 11:04

Marius


2 Answers

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.

like image 63
Modus Tollens Avatar answered Oct 31 '22 15:10

Modus Tollens


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 Ints and its "memory location").

like image 4
Kayaman Avatar answered Oct 31 '22 13:10

Kayaman