Friday, July 13, 2018

How to convert an int array to String with toString method in Java




I am using trying to use the toString(int[]) method, but I think I am doing it wrong:



http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#toString(int[])




My code:



int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;

System.out.println(array.toString());


The output is:




[I@23fc4bec


Also I tried printing like this, but:



System.out.println(new String().toString(array));  // **error on next line**
The method toString() in the type String is not applicable for the arguments (int[])



I took this code out of bigger and more complex code, but I can add it if needed. But this should give general information.



I am looking for output, like in Oracle's documentation:




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).



Answer



What you want is the Arrays.toString(int[]) method:




import java.util.Arrays;

int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;

..

System.out.println(Arrays.toString(array));



There is a static Arrays.toString helper method for every different primitive java type; the one for int[] says this:




public static String toString(int[] a)


Returns a 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 as by String.valueOf(int). Returns "null" if a is null.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...