Is it possible to override String compareTo method in Java?

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

I would prefer this to override the compareTo method in the String class and use the Arrays.sort() method, but I don't know if this is possible.

I overridden the compareTo method before, but I always just compared instance variables in one 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 it would be more elegant. Please feel free to let me know if you do not agree. I am trying to learn not only code but also code.

+4
source share
5 answers

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

+21
source

I understand that this does not answer your question the way you want, but it seems to me that you need an IP address , not a String class. Otherwise, your decision will be strictly printed.

+8
source

It's impossible. The string is final; there is no redefinition.

This is your class that must implement its own compareTo and execute the logic.

You can either encapsulate it all in a custom class, or implement your own Comparator.

It seems like you are committing a class sin without thinking enough about objects. String primitives are not the best encapsulation for user logic. It’s best to keep everything in one object of your own design.

+4
source

You can try using the method below in the Arrays class:

public static void sort (T [] a, Comparator c);

eg.

 Arrays.sort(arr, new Comparator<String>() { @Override public int compare(String o1, String o2) { // provide your comparison logic here return 0; } }); 
+1
source

you need to implement the Comparable interface and implement the compareTO (Object) method.

 class IP implements Comparable<IP>{ String ip; IP(String ip){ this.ip=ip } String getIP(String ip){ return ip; } public int compareTo(IP){ return ip.compareTo(ip.getIP()); } } 

Now you can call Collection.sort (object_ip) and pass an object of class IP.

0
source

Source: https://habr.com/ru/post/1433418/


All Articles