Java Program using list ,set, database(Cricket Management System) - java

My problem lies with the 5th function. I'm not getting how to solve it. Could someone help me?
populate from the database and store in the list.
List<Player>populate() throws ClassNotFoundException, SQLException;
sort the list according to runs (highest first).
void sortRuns(List<Player> list);
sort the list according to debut date.
void sortByDebut(List<Player> list);
calculate the average of each player and return a list which has field average. The return list should be sorted according to average (highest first).
List<Player>sortByAverage(List<Player>list);
return the set of players who have runs less than 10000. For example if you pass 3 to the function, it should return only 3 players randomly and each time a different set
should be generated.
Set<Player> randomSet(List<Player> list,int n);
Beans Classes are:
public class Player{
int capid;
String playerName;
Country country;
int matches;
int runs;
Date Debut;
int notOut;
float average;
}
Country As enum:
public enum Country {
India,Australia,SouthAfrica,NewZeland,England,SriLanka,WestIndies
}
Above Solved 4 functions are:
public class DataManagerImpl implements DataManager
{
DBConnectionImpl dm=new DBConnectionImpl();
Connection conn;
#Override
public List<Player> populate() throws ClassNotFoundException, SQLException {
List<Player> list=new ArrayList<Player>();
conn=dm.getConnection();
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("Select * from stats");
while(rs.next())
{
Player p=new Player(rs.getInt(1),rs.getString(2),Country.valueOf(rs.getString(3)),rs.getInt(4),rs.getInt (5),rs.getDate(6),rs.getInt(7));
list.add(p);
}
return list;
}
#Override
public void sortRuns(List<Player> list) {
// TODO Auto-generated method stub
Collections.sort(list,new Comparator<Player>(){
#Override
public int compare(Player o1, Player o2) {
// TODO Auto-generated method stub
return Integer.compare(o2.getRuns(),o1.getRuns());
}
});
}
#Override
public void sortByDebut(List<Player> list) {
// TODO Auto-generated method stub
Collections.sort(list,new Comparator<Player>(){
#Override
public int compare(Player o1, Player o2) {
// TODO Auto-generated method stub
return o1.getDebut().compareTo(o2.getDebut());
}
});
}
#Override
public List<Player> sortByAverage(List<Player> list) {
List<Player> plist=new ArrayList<Player>();
float average;
for(Player p:list)
{
int runs=p.getRuns();
int matchs=p.getMatches();
average=(runs/matchs);
p.setAverage(average);
plist.add(p);
}
Collections.sort(plist,new Comparator<Player>(){
#Override
public int compare(Player o1, Player o2) {
// TODO Auto-generated method stub
return Double.compare(o2.getAverage(),o1.getAverage());
}
});
// TODO Auto-generated method stub
return plist;
}

So here is how I understand the problem. This will probably not run, but should give you an idea how to do it.
Set<Player> randomSet(List<Player> list,int n){
ArrayList<Player> possiblePlayers = new ArrayList<>(); // fist we create a list where we can put all players that have 10000 runs
for(Player player: list){ // we loop through the list
if(player.getRuns()> 10000){ // check each player if he had more than 10000 runs
possiblePlayers.add(player); // and if so, we add him to our list of possible results
}
}
// at this point we have a list of players that have more than 10000 runs and we need to randomly select a player and put him into the new Set
// so first we create a Set that we can return
Set<Player> resultSet = new HashSet<>(); // Set is abstract and needs an implemented class like HashSet. This may not be the most appropriate implementation for your case, but it will do for now.
// now we need to pick n random players from our list. So we actually generate n numbers that we use as indexes
Random random = new Random(); // first we instantiate our random generator
ArrayList<Integer> indexes = new ArrayList<>(); // we will use this list to store the generated indexes, so we can check that we don't pick the same index twice
while (n > 0) {
Integer randomIndex = random.nextInt(possiblePlayers.size()); // first we pick a number between 0 and the size of our possiblePlayers list
if (!indexes.contains(randomIndex)) { // then we check if that number is already in the indexes list
indexes.add(randomIndex); // if not, we add it
n--; // and decrement n;
}
// if the random number where already in the indexes list, the loop would simply continue and try again
}
// here we have now a lost of randomly generated (and unique) indexes
// now we get the players at that indexes and put them in the result set
for(Integer index: indexes){
resultSet.add(possiblePlayers.get(index));
}
// and finally return the set
return resultSet;
}
As I said before, I am not sure if this method runs without errors. (I did not test it). It does however give you a solution. No guarantee that it is a good solution, though :) As you can see there are quite a lot of lists and Objects that are created, for such a small task. And I see a lot of potential to make it more efficient.

Related

Java: Unit Test is not returning the correct result

I'm writing a program in which if there aren't any reviews for a game then I need to add it to the map. If there is a review for a game then add the given review to the corresponding GameInfo. My code compiles fine, but my Unit Test aren't returning the points I need for them to return to show that my code is executing correctly. Here is my code:
class GameInfoCollection {
// TODO - you need to use a Map (from a String, the title, to a GameInfo) to keep track of all the GameInfo's
Map<String, Integer> titles = new HashMap<String, Integer>();
// TODO - if there are no reviews for the game, create a new GameInfo (with this review) and add it to the map
// if there's one, add the given review to the corresponding GameInfo
public void addGameReview(String gameTitle, Review r)
{
if (titles.isEmpty()) {
GameInfo g = new GameInfo("Review");
} else titles.put(gameTitle, 1);
}
public int getNumberOfReviewsForGame(String gameTitle)
{
// TODO - implement this
return titles.get(titles);
}
Here is my Unit Test for these methods. It should return 20 points, but it isn't returning any points:
public void testGetNumberOfReviewsForGame()
{
GameInfoCollection gic=new GameInfoCollection();
gic.addGameReview("g1",new Review("cool",5));
gic.addGameReview("g1",new Review("cool",3));
gic.addGameReview("g2",new Review("cool",2));
gic.addGameReview("g3",new Review("cool",2));
Assert.assertEquals(2,gic.getNumberOfReviewsForGame("g1"));
Assert.assertEquals(1,gic.getNumberOfReviewsForGame("g2"));
gic.addGameReview("g1",new Review("cool",3));
Assert.assertEquals(3,gic.getNumberOfReviewsForGame("g1"));
}
#Grade(points=20)
#Test
Here is my code for my entire program.Please note that there are sections at the end which I haven't got to yet.
package assignment;
import java.text.MessageFormat;
import java.util.Scanner;
import java.awt.Point;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.time.LocalDate;
import java.util.*; // List, ArrayList, Map, HashMap
class Review {
public String reviewText;
public int numberOfStars;
public Review(String reviewText, int numberOfStars) {
this.reviewText=reviewText;
this.numberOfStars=numberOfStars;
}
}
class GameInfo {
private String title;
// need an ArrayList to keep the reviews;
private Review[] reviews = new Review[10];
int numReviews=0;
public GameInfo(String title) {
this.title=title;
// you may want to initialize any other variables you create here
}
public String getTitle() {
return title;
}
// TODO - adds the review to the 'array' of reviews. You need to keep all reviews in an array
public void addReview(Review r) {
reviews[numReviews] = r;
++numReviews;
}
// TODO - returns the number of reviews which have been added to this GameInfo
public int getNumberOfReviews() {
return numReviews;
}
// TODO - returns the sum of the number of stars which have been added to this GameInfo
// you have to calculate this from your array
public int getSumOfStars() {
int sum=0;
for (int i=0; i<numReviews;++i)
sum +=reviews[i].numberOfStars;
return sum;
}
// TODO - returns the average number of stars for this GameInfo's reviews
// again, have to calculate this (or at least the sum of stars) from your array
public double getAverageStarRating() {
double firstNumber = getSumOfStars();
double secondNumber = getNumberOfReviews();
double avg = firstNumber/secondNumber;
return avg;
}
}
// TODO - you need to implement all these methods
class GameInfoCollection {
// TODO - you need to use a Map (from a String, the title, to a GameInfo) to keep track of all the GameInfo's
Map<String, Integer> titles = new HashMap<String, Integer>();
// TODO - if there are no reviews for the game, create a new GameInfo (with this review) and add it to the map
// if there's one, add the given review to the corresponding GameInfo
public void addGameReview(String gameTitle, Review r)
{
if (titles.isEmpty()) {
GameInfo g = new GameInfo("Review");
} else titles.put(gameTitle, 1);
}
public int getNumberOfReviewsForGame(String gameTitle)
{
// TODO - implement this
return titles.get(titles);
}
Please note that I'm still new to Java and any help is appreciated. Thanks!
This looks like a homework assignment, and I'm guessing the unit test is part of the code your teacher provided. The fact that the unit test is failing means, not that the unit test is wrong, but that your code is not behaving correctly. In particular, the parts in GameInfoCollection that you haven't finished.
So, let's go over what each of those TODO comments means:
// TODO - you need to use a Map (from a String, the title, to a GameInfo) to keep track of all the GameInfo's
A Map has keys and values, and is said to map from the keys to the values. In the declaration Map<String, Integer>, the first type (String) is the type of the keys, and the second is the type of the values. The TODO here is saying that the type of the values needs to be GameInfo.
// TODO - if there are no reviews for the game, create a new GameInfo (with this review) and add it to the map
Every part of this needs to be done inside the if branch. You need to a) create a new GameInfo, b) put the review in it, and c) add it to the map. You are currently doing only part a), and even for that you aren't passing in the right value to the constructor - take a look at the GameInfo constructor and the name of the argument it takes; does "Review" match that?
// if there's one, add the given review to the corresponding GameInfo
This is about what should go in the else branch.
// TODO - implement this
Technically this method already has an implementation, but you're going to need to change it to correctly match the change from the first TODO about the map value type.

How can I create simple poker hand algorithms?

So I have been creating this simple poker game in java. I have Created a deck of cards (The cards are objects that consist of a string and integer) and array lists to represent your hand and the dealers hand. Once I have cards in the yourHand array, how can I create a way to check for different suits? I want to keep it simple like having it only check for pairs and 3 of a kind. How can I approach this? The way I think it may be done, is to create a loop that will check each element in the array, and see if any of those elements are equal to another. But that seems easier said then done as I really don't understand how I would do that. And then the idea comes up, would it be an issue to do it that way since the card objects are of type String AND integer? I'm new to programming and will appreciate any help. Thanks! (also, let me know if you guys would like to see my code that sets up the card objects, which I have in a different class)
public class pokerMain implements StackInterFace {
public static void main (String [] args){
ArrayList<String> suits = new ArrayList<String>();//array list for the card suits
ArrayList<Integer> val = new ArrayList<Integer>();//array list for card values
ArrayList<CARDS> newCards = new ArrayList<CARDS>();//array list for cards with assigned val/suits
ArrayList<CARDS> yourHand = new ArrayList<CARDS>();//array list for your hand
ArrayList<CARDS> dealerHand = new ArrayList<CARDS>();//array list for the dealer's hand
Stack<CARDS> deck = new Stack();//Stack to represent deck
suits.add("Clubs");//These are the suits, added to the suits ArrayList
suits.add("Hearts");
suits.add("Diamonds");
suits.add("Spades");
System.out.println("suits contains: " + suits );//Testing for suit
for(int i = 1; i <= 13; i ++){//loop that adds all 13 values to to the val ArrayList
val.add(i);
}
System.out.println("val contains " + val);//Testing for val
for(Integer i : val) {//second attempt of adding objects to newCards
for(String s : suits) {
newCards.add(new CARDS(s, i));
}
}
System.out.println("the full deck contains: ");
System.out.println(newCards.toString());//prints newCards arrayList
Collections.shuffle(newCards);//shuffles array newCards
System.out.println("When shuffled this is what is in the deck");
System.out.println(newCards.toString());//prints shuffled array
deck.addAll(newCards);//adds newCards into the decks stack
System.out.println("Test print stack");
System.out.println(deck.toString());//prints stack as test
System.out.println("You pulled a " + deck.pop());//test pulling card from deck
for(int i = 0; i < 5; i ++){//loop to draw cards and put into hand
yourHand.add(deck.pop());
}
for(int i = 0; i < 5; i ++){//loop to draw cards and put into hand
dealerHand.add(deck.pop());
}
System.out.println("Please draw your cards");
System.out.println("Your hand contains:");
System.out.println(yourHand.toString());
for(int i = 0; i < yourHand.size(); i ++){//loop to check for pairs
}
}
#Override
public Object pop() {
// TODO Auto-generated method stub
return null;
}
#Override
public Object peek() {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void clear() {
// TODO Auto-generated method stub
}
#Override
public void push(ArrayList newCards) {
// TODO Auto-generated method stub
}
#Override
public void addAll(ArrayList newCards) {
// TODO Auto-generated method stub
}
}
One simple way is to sort the cards by face value. That makes it easy to find N of the same values in a row.
I don't write java, so this is probably full of syntax errorrs, but do something like:
class CardFaceComparartor implements Comparator<CARD>
public int compare(CARD a, CARD b) {
return a.getFaceval() - b.getFaceaval;
}
}
...
Collections.sort(yourHand, CardFaceComparator);
int numSame=1;
int sets[4] = {0,0,0,0} //counts singles, pairs, ...
bool maybeFlush=True;
for (i=0; i<yourHand.size()-; i++) {
if (yourHand[i].getFaceval()== yourHand[i-1].getFaceval())
numSame+=1;
else {
sets[numSame]+=1;
numSame = 1;
}
maybeFlush = maybeFlush & (yourHand[i].getSuit() == yourHand[i-1.getSuit());
}
// now you have all the info to find best hand.
Consider this example of using a Comparator and the Collections utils:
public static final Comparator comparator = new Comparator<Card>() {
#Override
public int compare(Card cardOne, Card cardTwo) {
return cardOne.getFaceVal().compareTo(cardTwo.getFaceVal());
}
};
/* Later on we can then use the comparator object to sort! */
Collections.sort(cards, comparator);
Make the fields of your Card object have type String for Suit, and of type Integer for value. Then the above code can be applied to sort a particular ArrayList that contains Card objects such as your hand, or the dealers hand, etc.. What you gain from this is checking for straights, pairs, etc can be optimized and easier since everything is in ascending order.
Here is an example of a hand before sort:
5, 4, Q, 5, 2
Without the sort, you can see checking for a straight is very hard to while then also needing to find pairs... The algorithm would be to see you have a 5, and check for a straight like [5,6,7,8,9] by looking through the rest of the cards, and that is difficult to also keep track of pairs. The logic would get very messy in code, and hard to test or have someone else read. By sorting it we would get
2, 3, 4, 5, 5
We can, in one scan, see there is no straight as well as finding pairs. We know to expect the subsequent card to be just one value greater than the last card, and if it's not no straight can exist. If it's the same value it's a pair! More logic is involved at well for finding a three of a kind, 4 of a kind, etc.. but I'll leave that exercise up to you!
There will be edge cases for an Ace though, as it in some games can be used in sequence with 2, 3, 4, 5 to be a straight.. You didn't say what poke game you were making. Also ensure to consider J-A to be 11-14 respectively.

Can you sort this ArrayList in two different ways writing your own Comparator?

I have an ArrayList of object called Course and I'm trying to sort it in 2 ways, by courseID and courseStartTime.
Edit: to clarify I mean I want to sort it by courseID at some point in time, and at another time later sort it by courseStartTime.
class Course implements Comparable<Course> {
private int courseID;
private String courseBeginTime;
#Override
public int compareTo(Course course) {
//what to return?
}
If I wrote 2 of my own comparators, one to compare courseID and the other for courseStarTime, then the compareTo() method in the class isn't used and I don't know what to return.
If I want to use the compareTo() method, I'm not sure how to write it so I can compare courseID and courseStartTime.
You can implement two different comparators.
public class CourseComparatorById implements Comparator<Course> {
#Override
public int compare(Course o1, Course o2) {
// for example - sort ascending by ID
return o1.getId() - o2.getId();
}
}
public class CourseComparatorByStartTime implements Comparator<Course> {
#Override
public int compare(Course o1, Course o2) {
// for example - sort ascending by start time
return o1.getStartTime() - o2.getStartTime();
}
}
And then use them to sort the array.
List<Course> courses = ...
Collections.sort(courses, new CourseComparatorById());
// now it's sorted by ID
Collections.sort(courses, new CourseComparatorByStartTime());
// now it's sorted by start time
You can also try the Java 8 Lambda way:
// this sorts by courseID
courseList.sort((c1, c2) -> Integer.valueOf(c1.courseID).compareTo(c2.courseID));
// this sorts by String courseBeginTime
courseList.sort((c1, c2) -> c1.courseBeginTime.compareTo(c2.courseBeginTime));
Note that is Java 8 you don't have to use Collections.sort, because the new List interface also provides a sort method
I have a feeling that this is being used for an online registration web app ...
you will probably be fetching the data source from a RDB ... It wouldnt be wise to put ALL courses in one list (one entity) and save that. I would create an object (containing courseID and courseBeginTime) for EVERY course and save them all. Then when querying, add hints to sort your entities based on whatever root parameters you have in them (like courseID or courseBeginTime), ending with a List containing objects sorted the way you want :) :)
May be you should do something like this
public class Course implements Comparator<Course> {
private int compareTime(int lhsTime, int rhsTime) {
if (lhsTime > rhsTime) {
return 1;
} else if (lhsTime == rhsTime) {
return 0;
} else {
return -1;
}
}
#Override
public int compare(Course lhs, Course rhs) {
if (lhs.id > rhs.id) {
return 1;
//Get the time object from course obj and pass to compaerTime
} else if (lhs.courseStarTime == rhs.courseStarTime) {
return compareTime(lhs, rhs);
} else {
return -1;
}
}
}

How can I print out an arraylist and also How can I add errors checks to the arraylist?

I have been trying to solve this problem for ages and with no luck I didn't progress. Could someone please help me out. I have created an arrayList, made an getter class, have made a method. I can add stuff to the array list as well but when I print the arrayList out it prints out some random text.
below is the arrayList I created.
public static ArrayList<getArrayList> arrayList = new ArrayList<getArrayList>();
here is my method;
private static void addToArrayList(String a, double no1, int no2, int no3) {
try {
arrayList.add(new getArrayList(a, no1, no2, no3));
} catch (Exception e) {
e.printStackTrace();
}
}
here is my getter class
public class getArrayList {
private String name;
private double seconds;
private int speed1;
private int speed2;
public String getName() {
return name;
}
public double getSeconds() {
return seconds;
}
public int getSpeed1() {
return speed1;
}
public int getSpeed2() {
return Speed2;
}
public StoreCommands(String storeName, double storeSeconds, int storeSpeed1, int storeSpeed2) throws Exception{
name = storeName;
seconds = storeSeconds;
speed1 = storeSpeed1;
speed2 = storeSpeed2;
}
}
to add stuff on this list I use the method I created
addToArrayList(String a, double no1, int no2, int no3) filled in with my values
and to receive stuff from the arraylist I use this
for(getArrayList s : arrayList) {
System.out.println(arrayList + "\n")
;
and it prints out if i use System.out.println(arrayList), depending on how much I add to the arraylist.
[StoreCommands#49a21b63]
Besides that could someone tell me how I can set a size of the arrayList so if anything more that is being added it won't add and give an error.
Also I need to perform certain error checks once the items are in the arrayList
*1st If the an item is added to the list and the user tries to add the same one again straight after I want to display an error.. (the user can add the same stuff but not directly after the one they just added, they will need to add something else first)
*2nd if say user wants to add apples to the list, I want to limit that to only 2 time in the whole list, more than that will not be added and will display and error.
Could someone help me out please, I will really appreciate it.
Thanks.
Try this -
for(getArrayList s : arrayList)
System.out.println(s + "\n");//This print the tostring of getArrayList class
Again override the toString method of getArrayList class, to print actual field value of the object. Example -
public class getArrayList {
public String toString(){
return name +"||" +seconds+"||"+ speed1+"||"+speed2;
}
}
Note : Follow java nomenclature standard, first later of you class name would be capital And also give a relevent name to the Class.
Overriding toString method will help you to print actual data. Override it in your class getArrayList. One more thing is class name should start with capital letter.
public String toString()
{
return "Name : "+name+" Seconds : "+seconds+" Speed1 : "+speed1+" Speed2 : "+speed2;
}
and use it like
for(getArrayList s : arrayList)
System.out.println(s.toString);
You can limit the size by adding check to
private static void addToArrayList(String a, double no1, int no2, int no3) {
try
{
if(arrayList.size < 10) //any size you want
arrayList.add(new getArrayList(a, no1, no2, no3));
else
System.out.println("ArrayList is full");
} catch (Exception e) {
e.printStackTrace();
}
}
You don't have to loop in order to print an array, just do:
System.out.println(Arrays.toString(arrayList.toArray()));
ArrayList doesn't have a mechanism to limit the size, if you want to do it - you'll have to implement it.
Example:
import java.util.ArrayList;
/**
* User: alfasin
* Date: 2/5/14
*/
public class RestrictedSizeArrayList<E> extends ArrayList<E> {
private static final int limit = 6;//example
#Override
public boolean add(E e){
if(this.size() > 5){
throw new IndexOutOfBoundsException("Can't add more than 5 elements to the ArrayList");
}
boolean result = super.add(e);
return result;
}
}

Java comparator Issue

I'm taking in all the information from an MySQL database table using a resultset and adding all the values into an array
public void populateQueueFromDB() {
// create priority queue
try {
String url = "jdbc:mysql://localhost:3306/project";
Connection conn = DriverManager.getConnection(url, "root", "nbuser");
PreparedStatement stmt = conn.prepareStatement("SELECT user_id,s_date,e_date,d_date,department,projectname,projectapplication,priority,cores,disk_space,analysis FROM booking");
ResultSet rs;
rs = stmt.executeQuery();
//List<JobRequest> jobList = new ArrayList<JobRequest>();
while (rs.next()) {
JobRequest job = new JobRequest();
User user = new User();
user.setUserID(rs.getString("user_id"));
job.setUserID(user.getUserID()); // changes the /user id to the job.setuser id so can call for my queue print.
job.setStartDate(rs.getString("s_date"));
job.setEndDate(rs.getString("e_date"));
job.setDeadDate(rs.getString("d_date"));
job.setDepartment(rs.getString("department"));
job.setProjectName(rs.getString("projectname"));
job.setProjectApplication(rs.getString("projectapplication"));
job.setPriority(rs.getInt("priority"));
job.setCores(rs.getInt("cores"));
job.setDiskSpace(rs.getInt("disk_space"));
job.setAnalysis(rs.getString("analysis"));
schedulerPriorityQueue.addJob( job );
}
schedulerPriorityQueue.printQueue();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
from here I go off and call my comparator to order the data, depending on priority of being either 1,2,3 then sort the queue. some other bits of code naming etc but essentially it sends me to the comparator
public class JobQueueComparator implements Comparator<JobRequest> {
#Override
public int compare(JobRequest object1, JobRequest object2) {
if(object1.getPriority() < object2.getPriority()){
return 1;
} else {
return -1;
}
}
}
But the output I'm getting from the comparator is ordering it in priority 3, 1 then 2. I've adapted this from example online but I don't understand the returns on comparator examples I've seen.
How would I be able to change that comparator to sort my priorities, 1 being the most important, 3 being the least. I made sure I'm printing out the output after adding all the result sets into the array so I know it's working as it's changed my ordering around, just dont know how to order it how I want.
Thanks
EDIT:
schedulerPriorityQueue
public class Queue {
private Comparator<JobRequest> comparator = new JobQueueComparator(); //calls my comparator
private PriorityQueue< JobRequest> scheduledJobs = new PriorityQueue<JobRequest>(100, comparator);
public void addJob(JobRequest job) {
// now add job to priority queue
scheduledJobs.add(job); // add jobs from the resultset into queue
}
Make it easy on yourself and use Integer and its compareTo method.
Your comparator method would look like this
#Override
public int compare(JobRequest object1, JobRequest object2) {
Integer iO1 = Integer.valueOf(object1.getPriority());
Integer iO2 = Integer.valueOf(object2.getPriority());
return -(i01.compareTo(iO2));
}
Assuming getPriorityreturns a int or String.
Simply swap the signs on the compare method. This will reverse the order.
public int compare(JobRequest object1, JobRequest object2) {
if(object1.getPriority() < object2.getPriority()){
return -1;
} else {
return +1;
}
}
You should return 0 from the comparator if the two objects are equal, an integer less than 0 if object 1 < object 2, and an integer greater than 0 if object 1 > object 2. Currently the JobQueueComparator never returns 0. Try the following:
public class JobQueueComparator implements Comparator<JobRequest> {
#Override
public int compare(JobRequest object1, JobRequest object2) {
return object1.getPriority() - object2.getPriority();
}
}
See the Comparator documentation for more details.
You are missing the case where the priorities are equal. I would use something like this:
public class JobQueueComparator implements Comparator<JobRequest> {
#Override
public int compare(JobRequest object1, JobRequest object2) {
return -(object1.getPriority() - object2.getPriority());
}
}
This would work if you take into consideration the priority order like this: 1, 2, 3.

Categories

Resources