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
.