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?
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();
}
};
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:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With