This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Date Compare  RSS feed

 
D. Clarke
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to compare two Dates. In the class that hold them I have this inner-class:

==========================================================
public static Comparator DateTimeComparator = new Comparator() {
public int compare(Object firstSolution, Object anotherSolution) {
...
Date firstDate = firstSolution.getDate();
Date nextDate = anotherSolution.getDate();

String firstTime = firstSolution.getTime();
String nextTime = anotherSolution.getTime();

String a = Utils.parseTime(firstDepartTime);
String b = Utils.parseTime(nextDepartTime);

String firstHour = a.substring(0,2);
String firstMin = a.substring(2,4);
String nextHour = b.substring(0,2);
String nextMin = b.substring(2,4);
firstDate.setHours(new Integer(firstHour).intValue());
firstDate.setMinutes(new Integer(firstMin).intValue());
nextDate.setHours(new Integer(nextHour).intValue());
nextDate.setMinutes(new Integer(nextMin).intValue());

return firstDate.compareTo(nextDate);
}


And here is how I call it:
ArrayList tempList = (ArrayList)solutions.getSolutions(); Arrays.sort(tempList.toArray(),Solution.DateTimeComparator );
==========================================================

As far as I can tell, this is not sorting at all. I can step thru and see where firstDate.compareTo(nextDate) returns -1,0,or 1 . I know the Date is ugly, but I dont' know another way to take a Date and a string representation of time (such as 0900 or 2315) and compare them against each other.

I would really appreciate any help anyone can offer.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not sorting because you're creating an array, sorting it, and then discarding it. If you want to sort the ArrayList, use Collections.sort() and pass the ArrayList itself as a parameter.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest is right - tempList.toArray() returns a new array with the contents of the list copied into it. You sort that array, but that ofcourse does not sort the list that you copied it from originally.
 
D. Clarke
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much, I can't believe I didn't see that!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!