我正在使用结果集从 MySQL 数据库表中获取所有信息,并将所有值添加到数组中
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());
}
}
从这里我开始调用我的比较器来排序数据,这取决于优先级是 1、2、3,然后对队列进行排序。其他一些代码命名等,但本质上它会将我发送到比较器
public class JobQueueComparator implements Comparator<JobRequest> {
@Override
public int compare(JobRequest object1, JobRequest object2) {
if(object1.getPriority() < object2.getPriority()){
return 1;
} else {
return -1;
}
}
}
但是我从比较器获得的输出是优先级为 3、1 和 2。我已经从在线示例中对此进行了修改,但我不明白我所看到的比较器示例的返回值。
我将如何更改该比较器以对我的优先级进行排序,1 是最重要的,3 是最不重要的。我确保在将所有结果集添加到数组后打印输出,所以我知道它正在工作,因为它改变了我的排序,只是不知道如何按我想要的方式排序。
谢谢
编辑:调度程序优先队列
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
}