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.
You can’t override String’s
compareTomethod because the class is final. But you can provide a custom Comparator toArrays#sort().