Goldengirl
Goldengirl

Reputation: 967

How to remove the brackets [ ] from ArrayList#toString()?

I have created an Array List in Java that looks something like this:

 public static ArrayList<Integer> error = new ArrayList<>();

for (int x= 1; x<10; x++)
 { 
    errors.add(x);
 }

When I print errors I get it errors as

[1,2,3,4,5,6,7,8,9]

Now I want to remove the brackets([ ]) from this array list. I thought I could use the method errors.remove("["), but then I discovered that it is just boolean and displays a true or false. Could somebody suggest how can I achieve this?

Thank you in advance for your help.

Upvotes: 3

Views: 52033

Answers (14)

touqeer
touqeer

Reputation: 407

I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.

Please refer to my Code & Output below:

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        ArrayList mylist = new ArrayList();
        Scanner scan = new Scanner(System.in);

        for(int i = 0; i < 5; i++) {
            System.out.println("Enter Value " + i + " to add: ");
            mylist.add(scan.nextLine());
        }
        System.out.println("=======================");

        for(int j = 0; j < 5; j++) {
            System.out.print(mylist.get(j));
        }
}
}

OUTPUT

Enter Value 0 to add:

1

Enter Value 1 to add:

2

Enter Value 2 to add:

3

Enter Value 3 to add:

4

Enter Value 4 to add:

5

=======================

12345

Upvotes: 0

Muhammad Nauman Tariq
Muhammad Nauman Tariq

Reputation: 13

You can simply remove all the brackets using replaceAll() method like this:- System.out.println(errors.toString().replaceAll("[\\[\\]]", ""));

Upvotes: 0

user17212391
user17212391

Reputation: 11

For that, you can use String.join method like below.

String.join(",",errors);

Upvotes: 1

Adriaan Koster
Adriaan Koster

Reputation: 16209

You are probably calling System.out.println to print the list. The JavaDoc says:

This method calls at first String.valueOf(x) to get the printed object's string value

The brackets are added by the toString implementation of ArrayList. To remove them, you have to first get the String:

String errorDisplay = errors.toString();

and then strip the brackets, something like this:

errorDisplay = errorDisplay.substring(1, errorDisplay.length() - 1);

It is not good practice to depend on a toString() implementation. toString() is intended only to generate a human readable representation for logging or debugging purposes. So it is better to build the String yourself whilst iterating:

List<Integer> errors = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int x = 1; x<10; x++) { 
    errors.add(x);
    sb.append(x).append(",");
}
sb.setLength(sb.length() - 1);
String errorDisplay = sb.toString();

Note that this is not an array, just a String displaying the contents of the list. To create an array from a list you can use list.toArray():

// create a new array with the same size as the list
Integer[] errorsArray = new Integer[errors.size()];
// fill the array
errors.toArray(errorsArray );

EDIT: From an object-oriented perspective one could argue that errors and errorsDisplay conceptually belong together in a class, e.g:

public class Errors {

    private final List<Integer> codes = new ArrayList<>();

    public void add(int error) {
        codes.add(error);
    }

    public Stream<Integer> get() {
        return codes.stream();
    }

    @Override
    public String toString() {
        return codes.stream()
            .map(Object::toString)
            .collect(Collectors.joining(", "));
    }
}

Upvotes: 12

Biswambar
Biswambar

Reputation: 65

You can write like this.

String output = errors.toString().replaceAll("(^\\[|\\]$)", "");

Upvotes: 0

kai
kai

Reputation: 6887

If you print your error list, it will internally call the toString() method of your list and this method add the brackets. There are a few possibilities. You can get the String via toString() method an remove the brackets from the String. Or you write your own method to print the List.

public static <T> void printList(List<T> list)
{
    StringBuilder output = new StringBuilder();
    for(T element : list)
        output.append(element + ", ");
    System.out.println(output);
}

Upvotes: 2

user1740241
user1740241

Reputation: 11

System.out.println(error.toString().substring(1, error.toString().length()-1)); This worked for me

Upvotes: 1

dotvav
dotvav

Reputation: 2848

Short answer: System.out.println(errors.toString().substring(1, errors.toString().length() - 1))

Explanation: when you call System.out.println(obj) with an Object as a parameter, the printed text will be the result of obj.toString(). ArrayList.toString() is implemented in a way that makes it represent its content between brackets [] in a comma separated concatenation of each of the contained items (their .toString() representation as well).

It is not a good practice to rely on another class's toString() implementation. You should use your own way to format your result.

Upvotes: 4

thomas.g
thomas.g

Reputation: 3932

There are not brackets inside your list. This is just the way Java prints a list by default.

If you want to print the content of your list, you can something like this

for (Integer error : errors) {
    System.out.format("%d ", error);
}

Upvotes: 2

faflo10
faflo10

Reputation: 386

The brackets you see are just an automatic way to display a List in JAVA (when using System.out.println(list); for example.

If you do not want them to show when showing it, you can create a custom method :

public void showList(List<Integer> listInt)
{
    for(int el : listInt)
    {
        System.out.print(el + ", ");
    }
}

Then adjust this code to show this according to your liking !

Upvotes: 3

Jan
Jan

Reputation: 1034

The brackets are not actually within the list it's just a representation of the list. If any object goes into a String output the objects toString() method gets called. In case of ArrayList this method delivers the content of the list wrapped by this brackets.

If you want to print your ArrayList without brackets just iterate over it and print it.

Upvotes: 2

Igor Iris
Igor Iris

Reputation: 106

brackets is not a part of your array list, since as you've mentioned it's Integer typed

ArrayList<Integer>

when you print errors using

System.out.println(errors);

it's just formatting your data, just iterate over the array and print each value separately

Upvotes: 1

SatyaTNV
SatyaTNV

Reputation: 4135

String text = errors.toString().replace("[", "").replace("]", "");//remove brackets([) convert it to string

Upvotes: 1

nhb.sajol
nhb.sajol

Reputation: 37

This is an ArrayList of Integer. This ArrayList can not contain a character like '['. But you can remove an Integer from it like this -

error.remove(3);

Upvotes: 0

Related Questions