Yes. You can call Collections.sort(listOfHorses) before the for
loop on listOfHorses
, and do the same with listOfCows
.
Let me point out that -- homework aside -- it's a poor design idea for a toString()
method to do a lot of computation, and an even worse design idea for it to have side effects (in this case, modifying the arraylists).
toString()
ought to be free of side effects. When called by the debugger or a logging statement, those side effects will change what the program does and cause confusion.
Also, a loop that does output += string
will be slower than building up the string in a StringBuffer
. If the number of iterations is large, it will be much slower since the work it does will be O(N^2), that is, proportional to the number of strings squared rather than proportional to the number of strings.