I currently have a toString method, similar to the one below. Please ignore that the Objects are only temporarily named. I have done this so that there is no confusion between the types of each variable etc.:
@Override
public String toString() {
for(Object object : ArrayList) {
System.out.println("This object is a " + object.getVariableA() + " and a " + object.getVariableB() + ".");
}
return null;
}
However the toString method requires me to return a value. I would obviously just want to return the Strings that I'm printing, although if I place a return statement there, it will only print one Object and not all of the ones I am looping through. What would be the best way to print all these values and not simply return null as I don't want this printing out after all the Objects? I also want to ensure that each of these Objects are printed on separate lines like they currently are so please don't suggest solutions that include one long joined String without line breaks as this is not suitable in this situation.
Thanks in advance!
toString
shouldn't output anything at all. Its job is to return an appropriate string representation of the relevant object, not to output that representation anywhere. That's outside its problem domain.
Instead, build and return a string (probably by using a StringBuilder
).
E.g., something like:
@Override
public String toString() {
StringBuilder sb = new StringBuilder(some_appropriate_size);
for(Object object : ArrayList) {
sb.append("This object is a ")
.append(object.getVariableA())
.append(" and a ")
.append(object.getVariableB())
.append(".\n");
}
return sb.toString();
}
I also want to ensure that each of these Objects are printed on separate lines like they currently are so please don't suggest solutions that include one long joined String as this is not suitable in this situation.
The above puts the items from the array list on separate "lines" (via the \n
). But "one long joined String" is the only appropriate thing for toString
to do. If you want a different result, you must use a different method, rather than breaking the contract of toString
.