简体   繁体   中英

Java compareTo method not working as expected

I have an array list that contains the following:

{a2.name, a4.name, tr.prod_date, a3.name, a1.name, a5.name, a6.name, a7.name, a8.name, a9.name, a10.name}

In my method - I am trying to compare the fields and sort them so they will come back in alphabetical order.

        Collections.sort(dataJSON, new Comparator() {
        public int compare(Object obj1, Object obj2) {
            return ((ReportDetail) obj1).getReportColumn().compareTo(((ReportDetail) obj2).getReportColumn());
        }
    });

Unfortunately, the results I'm seeing is that a10.name will come ahead of a2.name - am i missing something or is there another approach i should be taking?

It is doing a String compare since you have not provided your own comparison method. Because of this you are seeing a character by character comparison. That means that 'a' == 'a' , '1' < '2' so it falls out and sorts them in the order your seeing. you'll need to write you own compareTo.

You can make a custom Comparator like ReportComparator implements Comparator<ReportDetail>

Then add

 public int compare(ReportDetail r1, ReportDetail r2) {
            return Long.valueOf(r1.getReportColumn.subString(1,r1.getReport().length() - 1) -Long.valueOf(r2.getReportColumn.subString(1,r2.getReport().length() - 1);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM