How can I override the toString method of an ArrayList in Java?
You can't override the toString
method of ArrayList
1. 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
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.
ArrayList<String> list = new ArrayList<String>()
{
private static final long serialVersionUID = 1L;
@Override public String toString()
{
return super.toString();
}
};