How to override the toString method of ArrayList in Java?
•
Java
I want to use the toString () method for ArrayList in Java However, even if I add such toString () to the class containing ArrayList, I can't get its work
@Override public String toString() { String result = "+"; for (int i = 0; i < list.size(); i++) { result += " " + list.get(i); } return result; }
When I list like this When toString () calls my ArrayList, I still get the default representation Did I miss anything?
Solution
You should do something similar
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 as a parameter of listtostring() You can technically extend ArrayList (using anonymous classes or concrete) and implement toString yourself, but this seems unnecessary
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码