Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override the toString method of an ArrayList in Java?

I would like to have my own implementation of the toString() method for an ArrayList in Java. However, I can't get it working even though I added my toString() like this to the class that contains the ArrayList.

@Override
public String toString() {
    String result = "+";
    for (int i = 0; i < list.size(); i++) {
        result += " " + list.get(i);
    }
    return result;
}

When I call my ArrayList like this list.toString(), I still get the default representation. Am I missing something?

like image 737
user2426316 Avatar asked Aug 08 '13 15:08

user2426316


4 Answers

You should do something like

public static String listToString(List<?> list) {
    String result = "+";
    for (int i = 0; i < list.size(); i++) {
        result += " " + list.get(i);
    }
    return result;
}

and pass the list in as an argument of listToString(). You can technically extend ArrayList (either with an anonymous class or a concrete one) and implement toString yourself, but that seems unnecessary here.

like image 101
arshajii Avatar answered Oct 16 '22 07:10

arshajii


ArrayList<String> list = new ArrayList<String>()
{
    private static final long serialVersionUID = 1L;

    @Override public String toString()
    {
        return super.toString();
    }
};
like image 36
sashok724 Avatar answered Oct 16 '22 09:10

sashok724


You can't override the toString method of ArrayList1. Instead, you can use a utility class that converts an ArrayList to a String the way you want/need. Another alternative would be using Arrays.deepToString(yourList.toArray()).

Using Java 8, this can be done very easily:

//List<String> list
System.out.println(String.join(",", list));

Or if you have a List<Whatever>:

System.out.println(
    list.stream()
        .map(Whatever::getFieldX())
        .collect(Collectors.joining(", "))
);

I'm still against extending ArrayList or similar, is technically possible but I don't see it as a good option.


1 you could extend ArrayList and override the toString but generally that's not a great idea. Further info:

  • Extending a java ArrayList
  • Can you extend ArrayList in Java?
  • To extend ArrayList, or to not extend ArrayList
like image 10
Luiggi Mendoza Avatar answered Oct 16 '22 08:10

Luiggi Mendoza


You need to write a class extending from ArrayList:

import java.util.ArrayList;

public class MyArrayList extends ArrayList {
    private static final long serialVersionUID = 1L;

    @Override
    public String toString() {
        String result = "+";
        for (int i = 0; i < this.size(); i++) {
            result += " " + this.get(i);
        }
        return result;
    }
}
like image 8
Dennis Kriechel Avatar answered Oct 16 '22 07:10

Dennis Kriechel