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

  

3
Topic starter

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

1 Answer
2

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

Share: