• Post Reply Bookmark Topic Watch Topic
  • New Topic

java collection and priority queue implementation  RSS feed

 
jite eghagha
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could someone please show me how to put all my Golfers in a collection, and use that collection as a parameter of the priority queue.

 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//create a collection

Collection c = new MyChoiceOfCollection();


//put golfers in a Collection

c.add(tiger);
c.add(hal);
c.add(phil);
c.add(jite);


// use collection as parameter here

PriorityQueue pq = new PriorityQueue(c);
 
Niall Loughnane
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi jite,

Here is the testPQ class:
"
import java.util.ArrayList;
import java.util.List;

public class testPQ {

public static void main(String args[]) {

Golfer tiger = new Golfer("Tiger Woods", 61);
Golfer phil = new Golfer("Phil Mickelson", 72);
Golfer hal = new Golfer("Hal Sutton", 920);
Golfer jite = new Golfer("jite eghagha", 123);

// create a collection
List<Golfer> list = new ArrayList<Golfer>();

// put golfers in a Collection
list.add(tiger);
list.add(phil);
list.add(hal);
list.add(jite);

PriorityQueue pq = new PriorityQueue(list); // use collection as
// parameter
Golfer G = (Golfer) pq.remove();
System.out.println(G.getScore()+ " - "+G.getName());
G = (Golfer) pq.remove();
System.out.println(G.getScore()+ " - "+G.getName());

}
}
"

Here is the Golfer class:
"

public class Golfer {

int golferScore = 0;
String golferName = "";

Golfer(String name, int score){
golferScore = score;
golferName = name;
}

int getScore(){
return golferScore;
}

String getName(){
return golferName;
}

}
"

Here is the PriorityQueue class:
"
import java.util.ArrayList;
import java.util.List;

public class PriorityQueue {

List<Golfer> list = new ArrayList<Golfer>();
int listSize = 0;

public PriorityQueue(List l) {
list.addAll(l);
listSize = l.size();
// TODO Auto-generated constructor stub
}

Golfer remove(){
return list.remove(--listSize);
}

}
"

It is better to use instance variables (i.e. non-static) within Golfer class because the Golfer name and score will be created each time you do a "Golfer hal = new Golfer("Hal Sutton", 920);"

Hope this helps,

Niall
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!