Java arrays print strange numbers and text

I am new to programming. I am sure that there is an answer to this question, but I have no idea what to look for.

so um. ok, i will go straight to him.

Here is 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); } } 

Compiles and works fine. This is just the result of the CMD that I am talking about.

This is the result: [I@3e25a5

I want them to display the same numbers from a list (arr). How to do it?

+8
java arrays text numbers
source share
10 answers

Each object has a toString () method, and the default method is to display a representation of the class name of the object, then "@" followed by its hash code. So, what you see is the default view for intString () for an int array. To print data in an array, you can use

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

Or you can cycle through an array with a for loop, like the others published in this thread.

+19
source share

This is the standard string representation of an array (weird text).

You just need to go through it:

 for(int i : arr){ System.out.println(i); } 
+5
source share

To print the values, use.

 for(int i=0; i<arr.length; i++) System.out.println(arr[i]); 
+5
source share
 System.out.println(Arrays.toString(arr)); 

Current output classtype@hashcode .

If you need to print arrays using more than one dimension:

 Arrays.deepToString(arr); 

Also remember to override the toString() method for custom classes so that you get the object object representation of your choice, and not the default classtype@hashcode

+4
source share

It prints its .toString () method, which you should print each element

 for(int i=0; i<arr.length; i++) { System.out.println(arr[i]); } or for(Integer i : arr) { System.out.println(i); } 
+4
source share

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)); 
+4
source share

Like this:

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

This "weird number" is a reference to the array you printed. This is the default behavior built into the java.lang.Object toString () method.

You must redefine it in your own objects if viewing the link is insufficient.

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

My version is shorter!

Use Arrays.toString () and PrintStream.printf (String format, Object ... args) .

 System.out.printf("%s%n", Arrays.toString(arr)); 
+2
source share

You printed the link, not the values ​​in the link ... One fine day, all of this will become clear with C.

-3
source share

Source: https://habr.com/ru/post/650274/


All Articles