172

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jaanus
  • 16,161
  • 49
  • 147
  • 202

8 Answers8

320

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.

Community
  • 1
  • 1
Sbodd
  • 11,279
  • 6
  • 41
  • 42
  • 1
    What's the easiest way to go from "[x, y, z]" back to an array or List? – clearlight Sep 23 '15 at 21:59
  • @nerdistcolony There's nothing as clean as Arrays.toString to go the other way - but see http://stackoverflow.com/questions/456367/reverse-parse-the-output-of-arrays-tostringint for some suggestions. – Sbodd Sep 23 '15 at 22:29
  • @Sbodd - I came up with an example based on an ArrayList and posted the answer. It was specific to a problem I needed to solve for an app I'm porting, but might save someone some time. – clearlight Sep 24 '15 at 01:48
40
System.out.println(array.toString());

should be:

System.out.println(Arrays.toString(array));
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
38

Very much agreed with @Patrik M, but the thing with Arrays.toString is that it includes "[" and "]" and "," in the output. So I'll simply use a regex to remove them from outout like this

String strOfInts = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", "");

and now you have a String which can be parsed back to java.lang.Number, for example,

long veryLongNumber = Long.parseLong(intStr);

Or you can use the java 8 streams, if you hate regex,

String strOfInts = Arrays
            .stream(intArray)
            .mapToObj(String::valueOf)
            .reduce((a, b) -> a.concat(",").concat(b))
            .get();
Hasasn
  • 810
  • 8
  • 9
24

You can use java.util.Arrays:

String res = Arrays.toString(array);
System.out.println(res);

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
CubeJockey
  • 2,209
  • 8
  • 24
  • 31
Jesfre
  • 702
  • 8
  • 13
17

The toString method on an array only prints out the memory address, which you are getting. You have to loop though the array and print out each item by itself

for(int i : array) {
 System.println(i);
}
cpx
  • 17,009
  • 20
  • 87
  • 142
Frank Sposaro
  • 8,511
  • 4
  • 43
  • 64
3

Using the utility I describe here, you can have a more control over the string representation you get for your array.

String[] s = { "hello", "world" };
RichIterable<String> r = RichIterable.from(s);
r.mkString();                 // gives "hello, world"
r.mkString(" | ");            // gives "hello | world"
r.mkString("< ", ", ", " >"); // gives "< hello, world >"
Community
  • 1
  • 1
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
3

This function returns a array of int in the string form like "6097321041141011026"

private String IntArrayToString(byte[] array) {
        String strRet="";
        for(int i : array) {
            strRet+=Integer.toString(i);
        }
        return strRet;
    }
Roberto Santos
  • 606
  • 1
  • 7
  • 11
0

Here's an example of going from a list of strings, to a single string, back to a list of strings.

Compiling:

$ javac test.java
$ java test

Running:

    Initial list:

        "abc"
        "def"
        "ghi"
        "jkl"
        "mno"

    As single string:

        "[abc, def, ghi, jkl, mno]"

    Reconstituted list:

        "abc"
        "def"
        "ghi"
        "jkl"
        "mno"

Source code:

import java.util.*;
public class test {

    public static void main(String[] args) {
        List<String> listOfStrings= new ArrayList<>();
        listOfStrings.add("abc");
        listOfStrings.add("def");
        listOfStrings.add("ghi");
        listOfStrings.add("jkl");
        listOfStrings.add("mno");

        show("\nInitial list:", listOfStrings);

        String singleString = listOfStrings.toString();

        show("As single string:", singleString);

        List<String> reconstitutedList = Arrays.asList(
             singleString.substring(0, singleString.length() - 1)
                  .substring(1).split("[\\s,]+"));

        show("Reconstituted list:", reconstitutedList);
    }

    public static void show(String title, Object operand) {
        System.out.println(title + "\n");
        if (operand instanceof String) {
            System.out.println("    \"" + operand + "\"");
        } else {
            for (String string : (List<String>)operand)
                System.out.println("    \"" + string + "\"");
        }
        System.out.println("\n");
    }
}
clearlight
  • 12,255
  • 11
  • 57
  • 75
  • Nobody asked for this. – Roberto Feb 19 '18 at 12:40
  • @Roberto It uses related technology (Array methods), and I provided it to supplement the int related answer for people working with array conversions even though it show strings because I knew there were already int related solutions.. No reason to downvote it and being smug about it. Maybe try doing some good around here before trying to trash other people. – clearlight Feb 19 '18 at 23:28
  • No you're wrong. First sentence clarifies the purpose, and it is related enough. Contribute something useful before thinking about crapping on other users. You've done nothing other than make things worse for others. – clearlight Feb 25 '18 at 14:56