0

I have an Arraylist of MyObject which have a date property busDt but it is as a String.

I want to sort my Arraylist on the date.

I wrote the following code:

Collections.sort(myObjectList, new Comparator<MyObject>() {
          public int compare(MyObject o1, MyObject o2) {                  
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
              try {
                return sdf.parse(o1.getBusDt()).compareTo(sdf.parse(o2.getBusDt()));
            } catch (ParseException e) {
                e.printStackTrace();
                return 0;
            }
          }
        }); 

Is my code correct ? Any inputs would be a great help!

Thanks for reading!

Vicky
  • 16,679
  • 54
  • 139
  • 232
  • 1
    If you just want a code review, codereview.stackexchange.com may be more suitable. Otherwise, does your code work for you? Are you sure that you want to consider two elements equal if either of them as an unparsable date? (Hint: that will break the `compareTo` contract.) – Jon Skeet Apr 12 '16 at 16:32
  • @Jon Skeet: The answer you marked is having property as java.util.Date. I want to confirm if my usage of SimpleDateFormat with its try catch on parse is correct or not. – Vicky Apr 12 '16 at 16:33
  • @JonSkeet: Exactly. So if I remove "return 0" from catch block, it will show error that a return statement is mandatory. What should I do for that case ? That is my confusion and the reason for posting this question. – Vicky Apr 12 '16 at 16:35
  • It would make more sense if the field of `MyObject` was a `Date` rather than a `String`. Then you could just compare the `Date` objects. – Paul Boddington Apr 12 '16 at 16:38
  • @PaulBoddington: Sorry. Won't be able to modify that. – Vicky Apr 12 '16 at 16:39
  • Ok, well do you want the dates that can't be parsed to be at the beginning or the end of the list? – Paul Boddington Apr 12 '16 at 16:40
  • @PaulBoddington: At the end – Vicky Apr 12 '16 at 16:51
  • 1
    In that case, there are 4 cases. (1) o1 and o2 both unparsable: return 0. (2) o1 unparseable, o2 parsable: return 1, (3) o1 parsable, o2 unparsable: return -1 (4) both parsable: compare dates. If you don't do it this way `Collections.sort` can throw an exception if it detects an illegal `Comparator`. – Paul Boddington Apr 12 '16 at 16:55

0 Answers0