2 Replies - 595 Views - Last Post: 16 March 2011 - 04:23 PM Rate Topic: -----

#1 isuckatprograming  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-March 07

Dynamic sorting of a queue link list

Posted 15 March 2011 - 09:27 PM

Hey guys,
Im pretty new to java, i have a program i am working on that requires my defined queue be sorted based upon a certian component of the class it represents.


Queue<apples> applesqueue;
applesqueue = new LinkedList<apples>();

public apples{
public int getnumber(){
return number
}


This is just a quick example i made up, now say if i wanted to sort my queue based on the getnumber method, how would i go about doing so?

Thanks in advance

Is This A Good Question/Topic? 0
  • +

Replies To: Dynamic sorting of a queue link list

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Dynamic sorting of a queue link list

Posted 15 March 2011 - 11:31 PM

Your class apples must implement the Comparable interface and have a compareTo() method that return < 0 or == 0 or > 0 depending on getNumber()

class apples implements Comparable<apples> {

   public int compareTo(apples otherApple) {
     return this.getNumber() - otherApple.getNumber();
   }



Now you can invoke the API standard sort methods
Was This Post Helpful? 1
  • +
  • -

#3 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10561
  • View blog
  • Posts: 39,071
  • Joined: 27-December 08

Re: Dynamic sorting of a queue link list

Posted 16 March 2011 - 04:23 PM

@isuckatprograming: You're missing a semi-colon here:
return number  //<--- you need a semi-colon to end the statement



You can also use a Comparator<apple> to compare two apple objects, and pass that to the Collections.sort() method along with your List. Or you could just use a PriorityQueue, which orders elements in FIFO order, but based on priority as defined by the Comparable interface, or a Comparator.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1