Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get String CompareTo as a comparator object

I would like to sort and binary search a static array of strings via the String.CompareTo comparator.

The problem is that both sorting, and binary searching requires that a Comparator object be passed in -- So how do I pass in the built in string comparator?

like image 664
Georges Oates Larsen Avatar asked Aug 03 '12 23:08

Georges Oates Larsen


People also ask

Can we use compareTo in Comparator?

In Java, we can implement whatever sorting algorithm we want with any type. Using the Comparable interface and compareTo() method, we can sort using alphabetical order, String length, reverse alphabetical order, or numbers. The Comparator interface allows us to do the same but in a more flexible way.

How do you compare strings to objects?

In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .


1 Answers

You may write your own comparator

public class ExampleComparator  implements Comparator<String> {   public int compare(String obj1, String obj2) {     if (obj1 == obj2) {         return 0;     }     if (obj1 == null) {         return -1;     }     if (obj2 == null) {         return 1;     }     return obj1.compareTo(obj2);   } } 
like image 148
kosa Avatar answered Sep 22 '22 17:09

kosa