Bri*_*ian 1 java printing arrays string int
当我尝试将作为类成员的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
*/
}
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?据我所知,arr和temp都应该是int []类型.
您的本地副本正在通过,arrayToString()因为您println(this)调用了它toString().
你的临时副本只是试图转储int[]- 尝试使用arrayToString(temp)而不是println(temp).
| 归档时间: |
|
| 查看次数: |
161 次 |
| 最近记录: |