Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override String's compareTo method in Java?

I have a class that generates random IP addresses. I have to sort this list but I need to use my own logic to compare the two strings.

The way I would prefer to do it is to override the compareTo method in the String class and use Arrays.sort() method but I do not know if this is possible.

I have overridden the compareTo method before but I have always just had it compare instance variables in the same class.

/* Sorts array in ascending order
 *
 * @param    ips     An array of IP Addresses
 * @return           A sorted array of IP Addresses
 */
 public String[] sort(String[] ips)
 {
     String[] arr = ips;

     Arrays.sort(arr);

     return arr;
 }

I know there are other ways to do this but I think that this would be more elegant. Please feel free to let me know if you disagree. I am trying to learn not only how to code, but how to code well.

like image 444
jacky Avatar asked Nov 27 '22 02:11

jacky


1 Answers

You can't override String's compareTo method because the class is final. But you can provide a custom Comparator to Arrays#sort().

like image 124
assylias Avatar answered Dec 11 '22 00:12

assylias