【发布时间】:2013-09-09 05:27:27
【问题描述】:
当我尝试将作为类成员的 int[] 中的元素连接到 String 时,它可以正常工作。但是,当我使用 temp int[](从 Arrays.copyOf 生成)执行相同的过程时,我会感到很乱。我不明白为什么会这样。我的代码的简化版本如下所示:
import java.util.*;
import java.io.*;
public class Test {
public int[] arr;
public Test(int[] arr) {
this.arr = arr;
}
public void fn() {
// ...
int[] temp = Arrays.copyOf(arr, arr.length);
System.out.println(this);
System.out.println(temp);
}
/*
* Takes an integer array as input and returns a string representation
* of the elements in the array.
*/
public String arrayToString(int[] arr) {
String s = "[";
int i = 0;
while(i < (arr.length - 1)) {
s = s + arr[i++] + ", ";
}
s = s + arr[i] + "]";
return s;
}
public String toString() {
return arrayToString(this.arr);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
Test test = new Test(arr);
test.fn();
/*
* Produces result:
* [1, 2, 3, 4]
* [I@3343c8b3
*/
}
}
为什么会这样?据我所知,arr 和 temp 都应该是 int[] 类型。
【问题讨论】:
-
以后请发你的“胡言乱语”;我怀疑它类似于
[I@502a3135(在@之后插入您自己的十六进制),这是意外打印数组引用而不是格式化它的特征。
标签: java arrays string printing int