Question

Hey guys im on my final step of this java proj and i think i know where to begin for this final piece but i am not sure how to.

i am supposed to:

Modify a class such that the toString method sorts the list of cows and the list of horses before iterating through the list. (an example of what i am supposed to do)

how would i be able to begin? the list of cows and horses are part of an arraylist.

would collections be involved? here is the code of my toString method.

  public String toString()
{

    NumberFormat fmt = NumberFormat.getCurrencyInstance();

    String output   =  "**************************************************\n"
                    +  "*                 List of Horses               *\n"
                    +  "**************************************************\n";

    for( Horse horse : listOfHorses )
    {
        output  += horse + "\n"
                +  "--------------------------------------------------\n";
    }


    output  +=  "\n**************************************************\n"
            +  "*                 List of Cows                *\n"
            +  "**************************************************\n";

    for( Cow cow : listOfCows )
    {
        output  += cow + "\nVisit Rate:\t\t\t" 
                + fmt.format( cow.getBillAmount() ) + "\n"
                + "--------------------------------------------------\n";
    }

    return output;
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top