ArrayList sort() compareTo()..

Hi All,
Yep, I've already looked at dozens of "examples" of trying to use:
Collections.sort(ArrayList)
or
Collections.sort(ArrayList, compare)
But I still can't figure-out how to construct a, simple, compareTo() for
my ArrayList. :-\
If someone could point to a relevent example, or just show me
how to do it that would be great! :-)
My ArrayList Object looks like this:
class TypeObject
public int location;
public String name;
public int type;
I want to sort on 'location', and it can be 'int' or 'Integer', whatever is
easier. And I'd like to use the "older" Java, that is no "<>".
Thanks for your help! :-)
Joe S.

     class CustomComparator implements Comparator {
          public int compare(Object o1, Object o2) {
               TypeObject to1 = (TypeObject)o1;
               TypeObject to2 = (TypeObject)o2;
               int thisVal = to1.getLocation();
               int anotherVal = to2.getLocation();
               return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
     }Kaj

Similar Messages

  • 2 dimensional ArrayList sorting.

    Hello,
    let me first tell you a bit about my scenario, I am creating an auction program running over RMI, my server passes my client an arraylist of auctions (ListOfAuctions), and these auctions are represented by an arraylist themselves (description, start time, current price, etc)
    Where I'm struggling, is I have to be able to sort the top level auctions arraylist (ListOfAuctions), based on an integer element within the individual auctions.
    The element I need to sort by is in the same position in the Auction array each time.
    Any ideas would be much appreciated, i'm pretty terrible with sort algorithms!
    Auction is like so:
    element [0] (String)
    element [1] (String)
    element [2] (Integer)
    element [3](Integer)
    time Left [4] (Integer) <-- I need to sort 'ListOfAuctions' by this.
    element [5] (Integer)
    etc.
    ListOfAuction is simply an arraylist of the above. I'm too deep rooted into arraylists to use hashtables now so please, no suggestions for using those.
    Thanks in Advance
    Andy.

    I'm committed to this way though, unfortunately..You should tell the one responsible for your project
    that by not creating an Auction class and
    using java.util.Collection's built-in sort
    algorithms, you are creating something that will end
    up taking more time to maintain (and even to finish!)
    than just doing it the OO-approach and rewriting it
    now!Exactly. The way you're trying to do it, you'll have to not only write the code to compare the auctions, but also implement your own sorting algorithm. If you ever need to add another attribute to your auctions, you'll have to make big changes to your sorting algorithm, as well as all the code that handles those lists. If you had an Auction class, adding another attribute wouldn't affect the sorting at all! (unless they were going to be sorted according to that attribute also). It also wouldn't affect any of the code that handles that list of Auctions, since the data associated with auctions is abstracted away, and you don't have to touch it!

  • ArrayList sort

    Hi everyone,
    I have a problem I need to sort an ArrayList, that contains other
    ArrayList:
    ArrayList row=new Arraylist;
    ArrayList col=new ArrayList;
    col.add(aString);
    col.add(anAge);
    col.add(aDate);
    row.add(col);
    Lets suppose that we have 3 rows:the
    first ["John",23,01/01/1970]
    second["Mary",22,02/02/1980]
    third ["April",34,05/01/1969]
    I want to sort this, I want this order in the row ArrayList:
    ["April"...]
    ["John"...]
    ["Mary"...]
    I will appreciate your help.
    Thanks
    Manuel Rojas

    You probably would want to use the following class
    java.util.Collections and implement the following method.
    Collections.sort(List yourList, Comparator yourComparator);
    You will need to implement yourComparator.
    If you have not done this it is not too hard, and is a good thing to learn, teaches many java fundimetals.

  • Sorting ArrayList multiple times on Multiple Criteria

    I have an arraylist that is sorted with Collection.sort() calling the ComparTo() included below. CompareTo sorts the file on totalLaps, totalSeconds, and etc.. The question is how do I change the sort criteria later in my process so that the arraylist is sorted on sequence number (the first field and a long number)? The only way I can currently think of doing it is to copy the array and create a separate class file like RaceDetail2 that implements a different CompareTo. To me that seems ridiculous!
    I've self tought myself Java using the online tutorials and a few books so sometimes I find I have some basic gaps in knowledge about the language. What am I missing? Seems like it should be simple.
    private ArrayList detailsArrayList = new ArrayList( );
    // Sort arraylist using compareTo method in RaceDetail file
    Collections.sort(detailsArrayList);
    public class RaceDetail implements Comparable, Cloneable {
         public RaceDetail( long seqNum, String boatNumText, int lapNum, String penalty, String question, long seconds, int totalLaps, long totalSecs, long lastSeqNum, long avg, long interval )
    public int compareTo( Object o )
         RaceDetail rd = (RaceDetail) o;
         int lastCmp = (totalLaps < rd.totalLaps ? -1: (totalLaps == rd.totalLaps ? 0: 1));
         int lastCmpA = boatNumText.compareTo(rd.boatNumText);
         int lastCmpB = (lapNum < rd.lapNum ? -1: (lapNum == rd.lapNum ? 0 : 1 ));
         int lastCmpC = (totalSecs < rd.totalSecs ? -1 : (totalSecs == rd.totalSecs ? 0 : 1 ));
         int lastCmpD = (seqNum < rd.seqNum ? -1 : (seqNum == rd.seqNum ? 0 : 1 ));
         int lastCmpE = (seconds < rd.seconds ? -1 : (seconds == rd.seconds ? 0 : 1 ));
         int lastCmpF = (lastSeqNum < rd.lastSeqNum ? -1 : (lastSeqNum == rd.lastSeqNum ? 0 : 1 ));
         // TotalLaps - Descending, TotalSeconds - ascending, lastSeqNum - ascending
         // Boat - Ascending, Second - ascending, seqNum - ascending
         return (lastCmp !=0 ? -lastCmp :
              (lastCmpC !=0 ? lastCmpC :
                   (lastCmpF !=0 ? lastCmpF :
                        (lastCmpA !=0 ? lastCmpA :
                             (lastCmpE !=0 ? lastCmpE :
                                  lastCmpD)))));
    }

    Thanks talden, adding the comparator below in my main program flow worked and now the arraylist sorts correctly. A couple of additional questions. I tried to place this in my RaceDetail class file and received a compile error so placed it in the main program flow and it worked fine. For organization, I would like to place all my sort routines together. Is there some trick to calling this method if I place it in my RaceDetail? Am I even allowed to do that?
    dhall - just to give you a laugh, this arraylist populates a JTable, uses a TableModel, and the TableSorter from the tutorial. Sorting works great in the JTable. Problem is I have to sort the arraylist a couple of times to calculate some of the fields such as lap times and total laps. I went through the TableSorter 5 or 6 times and never could figure out how to adapt it for what I wanted to do. So here I am using an example in my program and can't interpret it.
    Collections.sort( detailsArrayListLeft, SORT_BY_SEQUENCE );
    static final Comparator SORT_BY_SEQUENCE = new Comparator() {
    public int compare ( Object o1, Object o2 )
         RaceDetail rd1 = (RaceDetail) o1;
         RaceDetail rd2 = (RaceDetail) o2;
         return (rd1.seqNum() < rd2.seqNum() ? -1 : (rd1.seqNum() == rd2.seqNum() ? 0 : 1 ));

  • How can I Sort Enumeration

    Hi Guys,
    Please help me solving this problem.
    I have some objects which I am read using Enumeration. But these objects are processed without order by Enumeration.
    How can I sort them without looping so they are read in order. Please bear in mind that I can sort them prior to the use of Enumeration.
    Thanks

    Sorry typing mistake 'I can' = 'I cannot'
    and these are custom ObectsThen you must read the objects one by one using the enumeration and put them into a new data structure. This can either be a tree or a list. If it's a tree, like a TreeSet, then the objects will be kept in sorted order as they're entered. If it's a list, like for example an ArrayList, then you'll have to sort it afterwards. Finally you have to iterate one more time using an Iterator but then they'll come out in sorted order.
    For the above to work the class (of the objects you store ) must either implement an interface called Comparable. Alternatively you can supply a so called Comparator object either to the TreeSet constructor or with the ArrayList sort call.

  • JOptionPane troubles

    Hey, I am trying to make a list using JOptionPane so that the user is able to select a string in this list, press ok, and then have that string returned to me. This works fine, and the line of code I've used is....
    removeItem = (String)JOptionPane.showInputDialog(null, "Choose the word you want to remove", "Remove word",
                      JOptionPane.QUESTION_MESSAGE, null, sortedList, "");...the problem is, I have just changed the sortedList input to increase my code efficiency, and now rather than displaying...about 8 list items on screen at one time, it now only displays one. Has anyone got any suggestions on how to increase this?
    Thanks in advance.

    Tom101 wrote:
    I'm having some real trouble trying to replicate this problem. As the program stands at the moment, it reads in a text file and places words into an array list along with an int. The program then copies the strings from the array list into an array, sorts them (using arrays.sort), and then sends them to the output. Now if I enter strings manually to the array it works perfectly. and if I modify my current code so it doesn't include arrays.sort it works perfectly when reading them from a file. Is arrays.sort doing something to it, that triggers JOptionPane to work incorrectly? If you want I can post the method up, however without the rest of the program it wont work the same.Perhaps you could create a new program that goes through the above steps, all of them, and nothing more, and also post the smallest text file to demonstrate the problem. It really should be compilable though, not just a naked method.
    This program could be quite simple. The pseudocode could look something like this:
    begin
       open text file
       read strings into arraylist
       sort arraylist
       convert arraylist to array
       show input dialog and put result into a string
       show string
    endEdited by: petes1234 on Dec 19, 2007 5:57 AM

  • Help on array

    Hi, I want to sort an array which contains Strings (sort according to alphabetical order...)
    after i sort the array...i want to read it at it's original order too...
    that mean's i want to have 2 set of array.....1 with the original order...1 with the sorted order..
    how do i do that?
    let's say i have a container class Club with an array of Names(type String), and a client class...
    with a Club object memberList.how do i do that?
    thank you.

    that mean's i want to have 2 set of array.....1 with
    the original order...1 with the sorted order..OK, how about
      ArrayList origArray = ... whatever ...;
      ArrayList sorted = new ArrayList(origArray);
      Collections.sort(sorted);Now, origArray still has your data in the original order, sorted has it in the sorted order. Note: both are pointing to the same elements.

  • Need help Sorting an Arraylist of type Object by Name

    Hey guys this is my first time posting on this forum so hopefully i do it the right way. My problem is that i am having difficulties sorting an Array list of my type object that i created. My class has fields for Name, ID, Hrs and Hrs worked. I need to sort this Array list in descending order according to name. Name is the last name only. I have used a bubble sort like this:
    public static void BubbleSort(TStudent[] x){
    TStudent temp = new TStudent();
            boolean doMore = true;
            while (doMore) {
                doMore = false;
                for (int i=0; i < x.length-1; i++) {
                   if (x.stuGetGPA() < x[i+1].stuGetGPA()) {
    // exchange elements
    temp = x[i]; x[i] = x[i+1];
    x[i+1] = temp;
    doMore = true;
    before many time to sort an array of my class TStudent according to GPA.  This time though i tried using an Array list instead of just a simple array and i can't figure out how i would modify that to perform the same task.  Then i googled it and read about the Collections.sort function.  The only problem there is that i know i have to make my own comparator but i can't figure out how to do that either.  All of the examples of writing a comparator i could find were just using either String's or just simple Arrays of strings.  I couldn't find a good example of using an Array list of an Object.
    Anyways sorry for the long explanation and any help anyone could give me would be greatly appreciated.  Thanks guys
    Edited by: Brian13 on Oct 19, 2007 10:38 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    ok still having problems I have this line of code to try and all Arrays.sort
    Arrays.sort(Employee, TEmployee.FirstNameComparator);Then in my class TEmployee i have
    public static Comparator FirstNameComparator = new Comparator() {
        public int compare(Object employee, Object anotherEmployee) {
          String lastName1 = ((TEmployee) employee).getEmpName().toUpperCase();
          String lastName2 = ((TEmployee) anotherEmployee).getEmpName().toUpperCase();     
           return lastName1.compareTo(lastName2);
      };Here is the rundown of what i have for this. I have 2 classes. One is called TEmployee and that class holds fields for Name, ID, Hrs Worked, Hourly Rate. Then i have another class called myCompany that holds an ArrayList of type TEmployee. Then i have my main program in a Jframe.
    So maybe i am putting them in the wrong spots. The code in TEmployee thats make the comparator is fine. However when i try to call Arrays.sort from class myCompany i get this
    cannot find symbol
    symbol: method sort (java.util.Array list<TEmployee>.java.util.Comparator
    location: class java.util.Arrays
    I have to put the comparator in TEmployee right because thats where my fields for Name are? Do i call the arrays.sort from my main program or do i call that from the class myCompany where my ArrayList of TEmployees are stored?
    Again guys thanks for any help you could give me and if you need any code to see what else is going on just let me know.

  • Sort an an arrayList by the first element of an array

    Hi,
    I am really struggling trying to sort an arratList of arrays. I have an arrayList
    ArrayList<String[]> myArrayList = new ArrayList<String []>(100);
    Within this array I have may arrays with 2 elements
    String[] myArray1 = {"Peter", "London"};
    String[] myArray2 = {"John", "London"};
    String[] myArray3 = {"Tony", "Birmingham"};
    I add all these arrays to the arrayList and want to sort by the first element of the array. Basically I expect the final arrayList to be in the order of:
    "John", "London"
    "Peter", "London"
    "Tony", "London"
    Thanks
    Peter

    Hi,
    I am really struggling trying to sort an arratList of
    arrays. I have an arrayList
    ArrayList<String[]> myArrayList = new
    ArrayList<String []>(100);
    Within this array I have may arrays with 2 elements
    String[] myArray1 = {"Peter", "London"};
    String[] myArray2 = {"John", "London"};
    String[] myArray3 = {"Tony", "Birmingham"};
    I add all these arrays to the arrayList and want to
    sort by the first element of the array. Basically I
    expect the final arrayList to be in the order of:
    "John", "London"
    "Peter", "London"
    "Tony", "London"
    Thanks
    PeterThis can be done by using
    Collections.sort(myArrayList, new Comparator<String[]>() {
    public int compare(String[] s1, String[] s2) {
    if (s1.length() <1) {
    return -1;
    if (s2.length() <1) {
    return 1;
    return s1[0].compareTo(s2[0]);
    });

  • Sort ArrayList of objects by  id

    I have ArrayList of containing 'MonthlySale' objects, below is my class.
    import java.io.Serializable;
    import java.util.ArrayList;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import org.hibernate.annotations.GenericGenerator;
    @Entity
    @Table(name="Month")
    public class MonthlySale extends AuraDB implements Serializable, Comparable {
        private String quantity;
        private String value;
        private String avUnit;
        private int saleNumber;
        private int id;
        private String month;
        private String saleYear;
        private String description;
        private int reportNumber;
        public MonthlySale() {
        public MonthlySale(int saleNumber, String saleYear) {
            this.saleNumber = saleNumber;
            this.saleYear = saleYear;
        public MonthlySale(int saleNumber, String saleYear, int reportNumber) {
            this.saleNumber = saleNumber;
            this.saleYear = saleYear;
            this.reportNumber = reportNumber;
        @Column(name="AV_UNIT")
        public String getAvUnit() {
            return avUnit;
        public void setAvUnit(String avUnit) {
            this.avUnit = avUnit;
        @Column(name="MONTH")
        public String getMonth() {
            return month;
        public void setMonth(String month) {
            this.month = month;
        @Column(name="QUANTITY")
        public String getQuantity() {
            return quantity;
        public void setQuantity(String quantity) {
            this.quantity = quantity;
        @Column(name="SALES_NO")
        public int getSaleNumber() {
            return saleNumber;
        public void setSaleNumber(int saleNumber) {
            this.saleNumber = saleNumber;
        @Column(name="SALES_YEAR")
        public String getSaleYear() {
            return saleYear;
        public void setSaleYear(String saleYear) {
            this.saleYear = saleYear;
        @Column(name="VALUE")
        public String getValue() {
            return value;
        public void setValue(String value) {
            this.value = value;
        @Id
        @GenericGenerator(name="generator", strategy="increment")
        @GeneratedValue(generator="generator")
        @Column(name="ID")
        public int getId() {
            return id;
        public void setId(int id) {
            this.id = id;
        @Column(name="DESCRIPTION")
        public String getDescription() {
            return description;
        public void setDescription(String description) {
            this.description = description;
        @Column(name="REPORT_ID")
        public int getReportNumber() {
            return reportNumber;
        public void setReportNumber(int reportNumber) {
            this.reportNumber = reportNumber;
         public void selectMonthList() {
            hibSelectAll(this, "SELECT DISTINCT month FROM MonthlySale WHERE sales_year='" + saleYear + "' AND " +
                    " sales_no = '" + saleNumber + "'");
    }I want my arraylist to be ordered by id. I used collection.sort(), but i cannot sort by id.
    I get objects arrayList like this way
                monthlySale = new MonthlySale(Integer.parseInt(sales_no), sales_year, 0);
                monthlySale.selectMonthList();Any help appreciated.
    regards,
    Dil.

    Of course yes i did, like this.
    public int compareTo(Object o) {
           if(this.id == ((MonthlySale)o).getId()){
                return 0;
           }else if(this.id > ((MonthlySale)o).getId()){
                return 1;
           }else{
                return -1;
        }I implement 'MonthlySale class' form Comparable interface and override above method but it doesn't work.

  • Collecstions.sort(ArrayList) - Please Explain

    Hello,
    This is a rewrite of an earlier question. Hopefully, I better formed the question in this post.
    Can anyone explain why the first code example requires that I write a compareTo() method (called by Collections.sort(bidList)) and a toString() method (called by System.out.println(bidList), while the second code example requires no such additional code in my program?
    Thanks for all responses.
    Karl
    First Code Example (Requires comparTo() and toString() methods in the program.)
         public static void main(String[] args) {
            // fill a list with 5 bids
            ArrayList bidList = new ArrayList();
            for(int i=0; i<5; i++){
                //generate random number 0-100 for a bid amount
                bidList.add(new AuctionBid("Bidder" + i, (int)(Math.random()*100)));
            //sort the bids in natural order and display them
            Collections.sort(bidList); //Why does this call method compareTo()
            System.out.println("Natural order sort by bid amount");
            System.out.println(bidList); //Why does this call method toString()
    }Second Code Example (Does not require compareTo() or toString() methods in the program.)
            public static void main(String[] args) {
            // fill a list with 5 bids
            System.out.println("Printing bidList from Array: ");
            String[] bidList = new String[5]; 
            for(int i=0; i<5; i++){
                if(i==0){bidList[i] = "Zoey";}
                else if (i==1){bidList[i] = "Megan";}
                 else if (i==2){bidList[i] = "Larrry";}
                  else if (i==3){bidList[i] = "Brian";}
                   else if (i==4){bidList[i] = "Abigail";}
       List list2 = Arrays.asList(bidList); // Does NOT requre a toString() method to be coded.
       System.out.println("Printing Unsorted list2: ");
       System.out.println(list2);
       Collections.sort(list2); // Does NOT require a compareTo() method to be coded.
       System.out.println("Printing Sorted list2: ");
       System.out.println(list2);
    }

    To answer your first question, Collections doesn't
    know how to sort any ArrayList unless the objects
    implement the Comparable interface and define the
    compareTo method. The String class already defines
    the compareTo method for you, and that's why your
    second ArrayList doesn't require you to write one.
    In your first list you're loading AuctionBid
    references, and Collections can't sort that list
    unless your AuctionBid class implements Comparable
    and defines the compareTo method.
    To answer your second question, System.out.println
    calls toString on the object reference you pass to
    it, unless the reference actually IS a String
    reference. How else could it get a string
    representation of an object without calling toString
    on it?Thank you!
    That makes sense.
    Karl

  • Sort ArrayList on multiple values

    Hi all!
    i'm trying to sort an ArrayList that contains a list of beans with a bunch of properties.
    i think that the comparator should be written like this:
        protected class CategoryComparator implements Comparator {
            public int compare(Object o1, Object o2) {
                Category cat1 = (Category)o1;
                Category cat2 = (Category)o2;
                return cat1.getCategoryName().compareTo(cat2.getCategoryName()) & cat1.getCategoryId().compareTo(cat2.getCategoryId());
        }where Category is the bean, getCategoryName and getCategoryId return two strings. Is that right to get the list sorted on both the two fields?
    Thanks!

    No, it's not. Assuming categoryName is of higher priority, you want int comp = cat1.getCategoryName().compareTo(cat2.getCategoryName());
    if (comp != 0) return comp;
    return cat1.getCategoryId().compareTo(cat2.getCategoryId());

  • Sort an ArrayList

    On the below code, how would i sort the ArrayList 'inv' by the 3rd element from greatest to smallest number.
    I.E.: 30, 22, 85, 75, 40, 45
    StoreInfo si = new StoreInfo();
            ArrayList sup = new ArrayList();
            ArrayList inv = new ArrayList();
            Supplier s = new Supplier("Hills", "777-123-2222");      
            Supplier s1 = new Supplier("Bantam", "430-126-0978");
            Supplier s2 = new Supplier("Time, Inc.", "967-534-7676");
            Supplier s3 = new Supplier("Starbucks", "897-888-4534");
            Supplier s4 = new Supplier("Prentice Hall", "678-555-9876");
            sup.add(s);
            sup.add(s1);
            sup.add(s2);
            sup.add(s3);
            sup.add(s4);
            inv.add(new Book(s1, "Java for Fun", 30, 45.50, "Wolff"));
            inv.add(new Book(s4,"Databases for Dummies", 22, 65.50, "Riggins"));
            inv.add(new Magazine(s2, "Time", 85, 6.00, new Day(2004,3,5)));
            inv.add(new Magazine(s2,"Sports Illustrated", 75, 5.50, new Day(2004,2,20)));
            inv.add(new Coffee(s,"Breakfast Jolt",40,9.95,"2 pounds"));
            inv.add(new Coffee(s3,"Afternoon Snooze",45,12.95, "1 pound"));

    ok, i read that entire tutorial twice even still a few more questions.
    here is my compareTo method implementing the comparable:
    public int compareTo(Object obj) throws ClassCastException {
              if (!(obj instanceof Inventory))
                throw new ClassCastException("An Inventory object expected.");
              int anotherInv = ((Inventory) obj).getNumInStock();
              return this.numInStock - anotherInv;
         }and this is where i use it
    public void sortPrint(ArrayList inventory)
             Collections.sort(inventory);
             int size= inventory.size();
             for (int i=0; i<size; i++)
                  Inventory inv = (Inventory) inventory.get(i);
                  inv.toString();
        }from what i got from that turorial, you use the Collections call to use the compareTo method?? is this true, if so why?
    here is the error i get:
    java.lang.ClassCastException
         at java.util.Arrays.mergeSort(Arrays.java:1122)
         at java.util.Arrays.sort(Arrays.java:1073)
         at java.util.Collections.sort(Collections.java:109)
         at cornerBookStore.StoreInfo.sortPrint(StoreInfo.java:336)
         at cornerBookStore.CornerBookStore.main(CornerBookStore.java:91)
    Exception in thread "main"
    thanks for your time!

  • Regarding ArrayList objects sorting

    I have number of class instances to be stored in an ArrayList say for example, I have one employee class which has empname,empno,designation as columns.
    I am adding this class instances into the ArrayList. I have an another class which has a method sorting() to sort this ArrayList object with 3 parameter . My ArrayList object is the first parameter passed to this
    sort() method based on anyof the column names specified as second parameter along with ascending or descending as third parameter my object has to be sorted.
    Is there any compatible way to sort the arrayList by the above requirement. Kindly guide us for further proceedings.

    // Sorting ArrayList of Objects(Emp) based on Date of Birth
    import java.util.*;
    import java.text.SimpleDateFormat;
    public class SortObjects
    public void checkData()
    ArrayList ar = new ArrayList();
    ar.add(new Emp(5, "ram", "13-Sep-2005 03:00:39 PM"));          // Date is in String format
    ar.add(new Emp(7, "shiva", "27-Oct-2005 09:08:28 AM"));
    ar.add(new Emp(1, "raj", "29-Aug-2005 11:15:07 AM"));
    ar.add(new Emp(4, "amar", "13-Mar-2005 10:29:18 AM"));
    ar.add(new Emp(6, "bhanu", "08-Oct-2005 03:51:34 PM"));
    ar.add(new Emp(11, "ramesh", ""));
    ar.add(new Emp(2, "gopi", null));
    System.out.println("\nBefore Sorting :");
    for(int i=0; i<ar.size(); i++)
    Emp ob = (Emp) ar.get(i);
    System.out.println(ob.toString());
    Collections.sort(ar);
    System.out.println("\nAfter Sorting :");
    for(int i=0; i<ar.size(); i++)
    Emp ob = (Emp) ar.get(i);
    System.out.println(ob.toString());
    public static void main(String args[])
    SortObjects ob = new SortObjects();
    ob.checkData();
    class Emp implements Comparable
         private int eno;
         private String ename;
         private String dob;
         public Emp(int eno, String ename, String dob)
              this.eno = eno;
              this.ename = ename;
              this.dob = dob;
         public int getEno()
              return eno;
         public String getEname()
              return ename;
         public String getDob()
              return dob;
         public String toString()
              return eno + "\t" + ename + "\t" + dob;
    public int compareTo(Object ob) throws ClassCastException           // Order by Date
              Emp temp = (Emp)ob;           SimpleDateFormat sdf = new
    SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a");
         Date date1 = null, date2 = null;
              try     
              if ((dob!=null)&&(!dob.equalsIgnoreCase("")))
                        date1 = sdf.parse(dob);
         if ((temp.dob!=null)&&(!temp.dob.equalsIgnoreCase("")))
                   date2 = sdf.parse(temp.dob);
              catch(Exception e)     
              {     e.printStackTrace();     }
         if ((date1!=null)&&(date2!=null) )
              return date2.compareTo(date1);
              else
                   return 0;
    /*     public int compareTo(Object ob) throws ClassCastException                // Order by Employee No.
              Emp temp = (Emp)ob;
              int enum = eno - temp.eno;
              return enum;
    }

  • Questions on filtering and sorting an arraylist

    Hello All,
    I'm trying to figure out a better way to do this code, but what I'm doing is taking an arrayList and filtering it using iter.remove(), based on a criteria I have, then take the results and sort them. The code below works, but I was seeing class cast exceptions when I tried to do a ss.addAll(list);
    , but it worked when I just added the set object. Why is this and is there a better way to do all this?
    Set set = new HashSet();
    List retList = new ArrayList();
    SortedSet ss = new TreeSet();
    for(Iterator iter = list.iterator(); iter.hasNext();){
    .//More code...
    iter.remove();
    //Remove duplicates.
    set.addAll(list);
    ss.add(set);
    retList.addAll(set);
    return retList;

    Your current code is adding the set (the hash set) as one element (the only element?) of the sorted set. Is this what you want to do? Would you rather add each element of the set to the sorted set?
    I don't know about the class cast exceptions. If you want somebody's comment on this part, you may consider posting code and stack trace.
    I think I'd rely on Collections.sort() for sorting rather than TreeSet. If you prefer TreeSet, why not skip the hash set in between?
    Hope this helps.
    Please remember the code button/tags.

Maybe you are looking for

  • This computer is no longer authorized

    Every time I sync my new iphone 3G, I get the message "This computer is no longer authorized". When I enter my password, it accepts it and says, the computer is already authorized. It is a bit of a pain and seems a little stupid. What can I do?

  • A specific Requirement in Displaying Report

    Hello All, I have following scenario in one of my reports. I try to explain it with an example. I have a total of 20 rows appearing in a report. (1). I have to hide every 2nd row so that total 10 rows are visible to user in the report. (2). In these

  • Issue with synced videos

    I have a 120 GB Classic, and some of the videos I have synced do not play completely. The iPod lops off the last minute or two of each file. It's not all the files, just certain ones. Rebooting/resetting the iPod didn't work. Deleting and reinstallin

  • Chart Overlap

    Hi, I am facing a strange problem using flexbuilder with LIferay , a portal server. My portlets contains charts made using Flexbuilder and everything work perfectly fine. But since something always has to create a Hicup.. i notice that the drop down

  • Export and Import Computer Groups

    Two Monday mornings in a row the Open Directory on our Intel-based Xserve's Mac OS X 10.5.7 Server had failed. This would mean that users who were supposed to have specific access right to folders and share points on other Xserve file servers couldn'