Friday, January 3, 2020

[Java] A simple way to print array using toString() and deepToString()

By using these method of Arrays, no need use for loop to print array anymore !
===== (1) ======
Arrays.toString(boolean[] a)
Arrays.toString(byte[] a)
Arrays.toString(char[] a)
Arrays.toString(double[] a)
Arrays.toString(float[] a)
Arrays.toString(int[] a)
Arrays.toString[long[] a)
Arrays.toString[Object[] a)
Arrays.toString[short[] a)

This function returns string representation of the contents of the specified array.
The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings. You can use any primitive type array or object array as argument,  Returns "null" if a is null.
Example:
String[] fruits = new String[]{"Apple","Orange","Banana"};
System.out.println(Arrays.toString(fruits));

Result:
[Apple,Orange,Banana]

===== (2) ======
Arrays.deepToString(Object[] a)
This is a status method to returns a string representation of the "deep contents" of the specified array such as 2d array:
int[] cordinates = new int[]{{1,2},{3,4},{3,6}};
System.out.println(Arrays.deepToString(cordinates));

Result:
[[1,2],[1,3],[1,4]]

Reference:
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

No comments :

Post a Comment