gpt4 book ai didi

Java比较器问题

转载 作者:行者123 更新时间:2023-12-02 07:16:35 25 4
gpt4 key购买 nike

我使用结果集从 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
}

最佳答案

让自己变得简单,使用 Integer 及其 compareTo 方法。

你的比较器方法看起来像这样

    @Override
public int compare(JobRequest object1, JobRequest object2) {
Integer iO1 = Integer.valueOf(object1.getPriority());
Integer iO2 = Integer.valueOf(object2.getPriority());
return -(i01.compareTo(iO2));
}

假设getPriority返回一个intString

关于Java比较器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14875951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com