Java arrays printing out weird numbers and text [d

2018-12-31 05:31发布

This question already has an answer here:

I'm new to programming. I'm sure the answer for this question is out there, but I have no idea what to search for.

Ok, I'll go right to it.

Here's my code:

int[] arr;
arr = new int[5];

arr[0] = 20;
arr[1] = 50;
arr[2] = 40;
arr[3] = 60;
arr[4] = 100;

System.out.println(arr);

This compiles and works fine. It's just the output from CMD that I'm dizzy about.

This is the output: [I@3e25a5.

I want the output to represent the exact same numbers from the list (arr) instead. How do I make that happen?

10条回答
与君花间醉酒
2楼-- · 2018-12-31 05:55

Every object has a toString() method, and the default method is to display the object's class name representation, then @ followed by its hashcode. So what you're seeing is the default toString() representation of an int array. To print the data in the array, you can use:

System.out.println(java.util.Arrays.toString(arr));

Or, you can loop through the array with a for loop as others have posted in this thread.

查看更多
栀子花@的思念
3楼-- · 2018-12-31 05:55

It's the default string representation of array (the weird text).

You'll just have to loop through it:

for(int i : arr){
System.out.println(i);
}
查看更多
春风洒进眼中
4楼-- · 2018-12-31 05:57

BTW You can write

int[] arr = { 20, 40, 60, 40, 60, 100 };
System.out.println(Arrays.toString(array));

or even

System.out.println(Arrays.toString(new int[] { 20, 40, 60, 40, 60, 100 }));

or

System.out.println(Arrays.asList(20, 40, 60, 40, 60, 100));
查看更多
查无此人
5楼-- · 2018-12-31 05:59

To print the values use.

for(int i=0; i<arr.length; i++)
   System.out.println(arr[i]);
查看更多
路过你的时光
6楼-- · 2018-12-31 06:00

You printed the reference and not the values at the reference... One day it will all become clear with C.

查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 06:06

Like this:

for (int i = 0; i < arr.length; ++i)
{
    System.out.println(arr[i]);
}

That "weird number" is the reference for the array you printed out. It's the default behavior built into the java.lang.Object toString() method.

You should override it in your own objects if seeing the reference isn't sufficient.

查看更多
登录 后发表回答