Java日期比较器问题

标签 java priority-queue

我在按日期整理比较器时遇到问题。日期格式应为“dd/MM/yyyy”,因此我从 SQL 数据库调用我的信息,然后通过执行以下操作将字符串转换为日期:

  public void setDeadlineDate(String deadDate) throws ParseException {
        this.d_date = deadDate;
        //convert strings to dates
        formatter = new SimpleDateFormat("dd/MM/yyyy");
        convertedDeadlineDate = (Date)formatter.parse(deadDate);
    }

然后我在下面创建一个 get 方法来调用我的比较器。我必须举例,但总是存在差异,因为奇怪的日期不合适并且比较不正确。

示例1:

  @Override
    public int compare(JobRequest j1, JobRequest j2) {

        if (j1.getConvertedDeadlineDate().before(j2.getConvertedDeadlineDate())) {
            return -1;
        } else if (j1.getConvertedDeadlineDate().after(j2.getConvertedDeadlineDate())) {
            return 1;
        } 
        else {
            return 0;
        }
    } 

示例2:

public int compare(JobRequest j1, JobRequest j2){
return j1.getConvertedDeadlineDate().compareTo(j2.getConvertedDeadlineDate());
}

这两个例子都给我带来了问题,并且我的优先队列截止日期没有按照我想要的正确顺序排列。 在我的数据库中,它们以以下格式保存为 varchar:“01/12/2012”,2012 年 12 月 1 日,因为它不允许我使用它们的日期函数将其设为英文格式。

他们是我转换字符串然后比较的更好方法还是我遗漏了一些东西?

谢谢

编辑: 获取订购日期的输出:

  • 2011年5月4日
  • 2012 年 12 月 16 日
  • 2012年6月18日
  • 2013 年 12 月 17 日
  • 2013 年 12 月 17 日
  • 2013 年 12 月 16 日
  • 2013 年 12 月 17 日
  • 2012年8月14日
  • 2013 年 12 月 19 日

我在哪里声明 PriortyQueue:

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
    }  

scheduledJobs.add(job) 只是从结果集中填充队列,并不断添加到队列,直到读取数据库中的所有字段,见下文

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.setDeadlineDate(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());
        }

    }

}

打印队列:

public void printQueue() {
        for (JobRequest jr : scheduledJobs) {

            System.out.print(jr.getUserID() + "-->");
            System.out.print(jr.getStartDate() + "--START-->");
            System.out.print(jr.getEndDate() + "---END-->");
            System.out.print(jr.getDeadDate() + "--DROP-->");
            System.out.print(jr.getDepartment() + "-->");
            System.out.print(jr.getProjectName() + "-->");
            System.out.print(jr.getProjectApplication() + "-->");
            System.out.print(jr.getPriority() + "--PRIORITY-->");
            System.out.print(jr.getCores() + "-->");
            System.out.print(jr.getDiskSpace() + "-->");
            System.out.println(jr.getAnaylsis());

        }
    }

最佳答案

当您执行以下操作时:for (JobRequest jr : ScheduledJobs) { ... 您实际上使用的是隐式Iterator,这并不能保证这些项目将按优先级顺序返回(由您的比较器定义)。

如上所述,文档指出:

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

这意味着队列中作业的顺序和迭代器的顺序不一定相同。

如果您只需要列出作业,请使用文档中提到的Arrays.sort 方法。

如果您想确保您的 PriorityQueue 正常工作,您必须将其用作一个,执行以下操作:

while(!scheduledJobs.isEmpty()) {
     ... = scheduledJobs.poll();
     //print, do whatever
}

请记住,这将从队列中删除元素,并且只能用于测试目的,或者根据需要实际处理作业。但这应该显示实际优先顺序中的日期。

在我看来,对于如何使用 PriorityQueue 存在一些困惑。我想说,常规用例是这样的:

  • 向队列添加元素
  • 定义一个方法来处理队列中的“作业”(每个元素)
  • 当队列不为空时,使用 poll 获取每个元素(返回最小的元素),并对其执行任何您需要执行的操作。

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

相关文章:

java - 无法使用 JXL API 在 Excel 中查看组合框

Java Processbuilder 返回 255

java - java的makefile,仅在文件更改时重新编译

java - 如何深度复制具有初始容量的 map ?

c - 具有双向链表插入的优先级队列

python - 具有两个优先级值的优先级队列

java - 无重复的 k 排序数组的迭代器实现 - 面试问题

java - PriorityBlockingQueue 按 boolean 比较排序

c++ - priority_queue 常量表达式

Java应用程序更新到jdk 1.7.25,遇到运行时异常,您有何看法?