Output an array of elements that we usually do with a for loop, such as:
Package test; Public class Test { publicstaticvoid main (String args[]) { int arr[]={1,2,3}; System.out.print ("["); for (int i=0; i<arr.length-1; i++) System.out.print (Arr[i]+ ","); System.out.println (Arr[arr.length-1]+ "]");} }
The results of the output are: [1, 2, 3].
But Java provides a much simpler approach, which is the ToString method. The following are the specific practices:
Package test; Import java.util.Arrays; Public class Test { publicstaticvoid main (String args[]) { int arr[]={1,2,3}; System.out.println (arrays.tostring (arr));} }
The results of the output are: [1, 2, 3].
But what if the elements in the array are not the same type? Like what:
Package test; Import java.util.Arrays; Public class Test { publicstaticvoid main (String args[]) { int [] arr={1,2,3}; string[] Str={"AAA", "BBB"}; = {arr,str}; System.out.println (arrays.tostring (array));} }
The result of the output is: [[email protected], [Ljava.lang.string;@79a2e7].
You can see that the print is not an array element, but an object's memory code. What if you want to print an array of elements? Here we can use the deeptostring. Like what:
Package test; Import java.util.Arrays; Public class Test { publicstaticvoid main (String args[]) { int [] arr={1,2,3}; string[] Str={"AAA", "BBB"}; = {arr,str}; System.out.println (arrays.deeptostring (array));} }
Results of the output: [[1, 2, 3], [AAA, BBB]].
Java Array output