title: Sorting ArrayList of JSONObjects not working properly
body: <p>I have a JSONArray called events. I need these events to be sorted by a field called <code>"EVENT_TIME"</code> in descending order. I store the events into an ArrayList called <code>all_events</code> and use <code>Collections.sort()</code> on it with my own comparator. Out of 6 events , 5 get sorted and 1 is in the wrong place.</p>
  
  <p>I end up with:</p>
  
  <pre><code>Acceptance 31-May-2014 10:31:00
  Reopened 31-May-2014 10:30:55
  Arrived at Pickup Location 31-May-2014 10:30:45
  Unloaded from Vessel 31-May-2014 10:30:00
  Shipment Create 29-May-2014 00:00:00
  Arrive Load Port 30-May-2014 00:00:00
  </code></pre>
  
  <p>after sorting. Clearly the last one is in the wrong place.</p>
  
  <p>Storing into arraylist and calling the sort:</p>
  
  <pre><code>ArrayList&lt;String&gt;all_events=new ArrayList&lt;String&gt;();
  for(int i=0;i&lt;events.length();i++){
      JSONObject event=events.getJSONObject(i);
      all_events.add(event.toString());
  }
  Collections.sort(all_events, new JSONComparator());;
  </code></pre>
  
  <p>The JSONComparator class:</p>
  
  <pre><code>class JSONComparator implements Comparator&lt;String&gt;{
  
          public int compare(String a, String b){
              String a_time=null;
              String b_time=null;
              try{
                  JSONObject event1=new JSONObject(a);
                  JSONObject event2=new JSONObject(b);
                  a_time=event1.getString("EVENT_TIME");
                  b_time=event2.getString("EVENT_TIME");
              }
              catch(JSONException e){
                  e.printStackTrace();
              }
              SimpleDateFormat sdf=new SimpleDateFormat("ss-MMM-yyyy HH:mm:sss");
              Date date1=null, date2=null;
              try{
                  date1=sdf.parse(a_time);
                  date2=sdf.parse(b_time);
              }
              catch(ParseException pe){
                  pe.printStackTrace();
              }
  
              return date1.compareTo(date2)*-1;
  
          }
  
      };
  </code></pre>
  
  <p>printing the output:</p>
  
  <pre><code>for(int i=0;i&lt;all_events.size();i++){
      JSONObject event=new JSONObject(all_events.get(i));
      String s=event.getString("EVENT_CODE");
      String eventname=codemap.getString(s);
      System.out.println(eventname+" "+event.getString("EVENT_TIME"));
  }
  </code></pre>