简体   繁体   English

java - StringUtils.join()返回指针

[英]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. 我试图通过Apache commons库中的StringUtils.join(array, separator)方法加入数组的元素。 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[] ? 任何人都可以解释我为什么我不能得到结果字符串,只有一个指向其位置的指针,如果我使用像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. 仅使用Integer数组。 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? 我理解基元数组的内部处理方式与ArrayList或其他更高阶对象的处理方式不同,但为什么可以实现HashMap<String, int[]>而没有任何警告可能(同一主题或多或少但可能是一个不同的问题) ,例外? 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 : 看一下StringUtils#join int数组的签名:

join(byte[] array, char separator)

You called join using 你打电话给join

StringUtils.join(a, " "),

using a String instead of a char. 使用String而不是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. 所以你的参数被解释为两个对象,一个整数数组和一个带空格字符的String。 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. 一个int(基元)数组是一个对象。

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"). 我怀疑实现不支持原始阵列,并调用toString()它们,从而导致像[I@659e0bfd (这相当于一维(只有一个[的)阵列I NTS和它的“存储器位置”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM