0

I used the following code snippet to sort by phone number:

class Item { String addr; /* phone number */ }

private int compareByAddr(Item objA, Item objB) {
    if (objA.addr==null && objB.addr==null) {
        return 0;
    } else if (objA.addr==null && objB.addr!=null) {
        return -1;
    } else if (objA.addr!=null && objB.addr==null) {
        return 1;
    } else {
        if (PhoneNumberUtils.compare(objA.addr, objB.addr)) {
            return 0;
        } // end if
        return objA.addr.compareTo(objB.addr);
    } // end if
} // end compareByAddr()

However I got an Exception:

E/AndroidRuntime(12157): java.lang.IllegalArgumentException: Comparison method violates its general contract!

I've searched about it, and found out that it means my sorting algorithm is not transitive...

Does anyone has a better algorithm for sorting by phone number?

user538565
  • 513
  • 1
  • 6
  • 21

1 Answers1

0

Problem is you have 2 String's which represent phone numbers and you want to compare them and sort them from big to small like there were numbers...

but comparing 2 String to each-other (like in your code snippet):

     objA.addr.compareTo(objB.addr);

wont work :(

you can do this by manipulating the String to a number (and discarding all non digit from it) and then compare the 2 like they were regular numbers ...

 String phone1Str

 String phone2Str

 int phone1

 int phone2

 phone1Str= phone1Str.replaceAll("\\D+",""); //using reg-ex to get only digits

 phone1= Integer.valueOf(phone1Str); //convert to int to compare numbers

 phone2Str= phone2Str.replaceAll("\\D+","");

 phone2= Integer.valueOf(phone2Str);

 if (PhoneNumberUtils.compare(phone1Str,phone2Str)
   //they are equal 
 else if (phone1>phone2)
   //phone1 is the larger number !
 else
   //phone2 is the larger number !

hope this helps

Nimrod007
  • 9,825
  • 8
  • 48
  • 71
  • thanks. but still have a problem. phone number can be displayed in many formats, e.g. +886912345678(with country code +886) or 0912345678(w/o country code). that's why I used PhoneNumberUtils.compare() to do the comparison. your algorithm will assume the above two numbers are different while PhoneNumberUtils.compare() won't, and that's the problem I'm encountering... – user538565 Feb 04 '13 at 14:48
  • i see your point, ive changed it so it should work if the numbers are equal (using PhoneNumberUtils.compare() ) – Nimrod007 Feb 04 '13 at 19:09