settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: How to print an ArrayList without the square brackets [ and ] in Java?

+10 votes

I need to print in Java an ArrayList - but without the square brackets [ ] - how can I do it? The output MUST be without the square brackets [ ];

For example I have this code:

        ArrayList<Integer> n = new ArrayList<>();
        n.add(4);
        n.add(5);
        n.add(434);
        n.add((int) 9.5);

        System.out.println(n);

The output in this case is: [4, 5, 434, 9]

But I want to print it without the brackets - only the numbers: 4, 5, 434, 9

asked in Java category by user john7
edited by user golearnweb

1 Answer

+3 votes
 
Best answer

When printing the result - you can make it String and then use it's .replace function - and replace the brackets with nothing "";

In your case the code will look like this:

        ArrayList<Integer> n = new ArrayList<>();
        n.add(4);
        n.add(5);
        n.add(434);
        n.add((int) 9.5);

        System.out.println(n.toString().replace("[","").replace("]",""));

Or also, you can read this thread here: https://stackoverflow.com/questions/5349185/removing-and-from-arraylist

answered by user hues
edited by user golearnweb
...