Search code examples
javaswinglinked-listleaderboard

Simple Java leaderboard from LinkedList


I'm currently working on this application for tracking track (tracking track?) day runs and displaying a leaderboard. This is for a class so I'm not looking for code necessarily, just some thoughts on how to go about it. Anyway, the application currently will take input information (from the bottom textfields), create a LinkedList of RaceEntrant objects (class shown below), and create a queue on the right which is emptied as the participants go through their runs. The problem is, I need the RaceEntrants to be sorted in the (grey) leaderboard area from smallest to largest runTime. I was thinking if there is any way I could do this with the LinkedList listIterator method, but I can't quite figure it out, assuming it would even work. Is that the right idea or is there a better way of going about this, and how would I go about the listIterator idea if it is possible? Sorry for the lengthy question, any help is appreciated.

class RaceEntrant implements Comparable<RaceEntrant>
{
  private String name,
                 car;
  private double runTime;

  public RaceEntrant(String name, String car)
  {
    this.name = name;
    this.car = car;
  }    

  public String getName()
  {
    return name;
  }

  public String getCar()
  {
    return car;
  }   

  public double getTime()
  {
    return runTime;  
  }

  public void setTime(double time)
  {
      this.runTime = time;
  }

  @Override
  public String toString() 
  {
      StringBuilder sb = new StringBuilder("");
      sb.append(getName());
      sb.append("     ");
      sb.append(getCar());
      sb.append("\n" );
      sb.append("Best time: " + getTime() + "\n");
      return sb.toString();
  }

  @Override
  public int compareTo(RaceEntrant entrant) 
  {
      if (this.runTime > entrant.runTime)
          return 0;
      else
          return 1;
  }
}

application example


Solution

  • Have a look at java.util.TreeSet - it is an implementation of SortetSet and should do what you're after.

    Some other things:

    1. If a class implements Comparable it should also override hashCode() and equals() for correctness. (Generally equals() will delegate to compareTo() - this means that in equals() you'll have a line like return compareTo((RaceEntrant) obj) == 0.
    2. Consider creating an implementation of Comparator for use with TreeSet, this way you avoid having to make RaceEntrant implement Comparable.
    3. TreeSet will automatically re-order it's elements as they are added/removed, based on the supplied Comparator or Comparable.