Note that there are some explanatory texts on larger screens.

plurals
  1. POSorting of Arraylist by date only sorts day and not month and year?
    text
    copied!<p>I'm attempting to SORT an ArrayList by (Type Date) MyObject.getDate()</p> <p>My format is formatted by SimpleDateFormat by dd-mm-yyyy; I'm using a custom comparator to sort my list. I'm using Collections.sort(produuctList, new CustomComparator())</p> <p>Problem my sorted list is only by dd and not dd-mm-yyyy.</p> <p>Any ideas?</p> <pre><code>public class Product { private String productName; private Date boughtOn; private Date useBy; private double boughtAt; private long quantity; private static DateFormat dateFormat; public Date getUseBy() { return useBy; } public void setUseBy(Date useBy) { this.useBy = useBy; } } public static Date rtnDate(String dateStr, int currentLineCount) { SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy"); try { Date date = df.parse(dateStr); return date; } catch (ParseException e) { productParsingErrorMessages.add("Date parse exception: " + e + "on line " + currentLineCount); return null; } // DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy"); // Date date2 = (Date)formatter.parse(dateStr); } </code></pre> <blockquote> <pre><code>System.out.println("Product list - BEFORE sorting by UseBy"); printInventory(produuctList); Collections.sort(produuctList, new CustomComparator()); System.out.println("Product list - AFTER sorting by UseBy"); printInventory(produuctList); </code></pre> </blockquote> <pre><code>public class CustomComparator implements Comparator&lt;Product&gt; { @Override public int compare(Product o1, Product o2) { return o1.getUseBy().compareTo(o2.getUseBy()); } } </code></pre> <p>Product list - BEFORE sorting by UseBy</p> <p>Product name: sugar UseBy : 12-12-2012<br> Product name: sugar UseBy : 01-10-2012<br> Product name: sugar UseBy : 16-04-2012<br> Product name: sugar UseBy : 30-01-2012<br> Product name: sugar UseBy : 25-04-2012<br> Product name: sugar UseBy : 03-04-2012<br> Product name: sugar UseBy : 08-04-2012 </p> <p>Product list - AFTER sorting by UseBy</p> <p>Product name: sugar UseBy : 01-10-2012<br> Product name: sugar UseBy : 03-04-2012<br> Product name: sugar UseBy : 08-04-2012<br> Product name: sugar UseBy : 12-12-2012<br> Product name: sugar UseBy : 16-04-2012<br> Product name: sugar UseBy : 25-04-2012<br> Product name: sugar UseBy : 30-01-2012</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload