I have a question regarding the Comparator interface. Below my class implements the interface to sort strings by length instead of by the default sort which sorts by character value.
After overriding the default compare, I used Arrays.sort() to sort my string array. Even though I have overridden the default method, if I use Arrays.sort, it calls the default compare instead of my overridden method. Is this because I am explicitly calling the super class method?
The other question is initializing the interface itself. I know you cannot initialize an interface and instead initialize a class object (that implements said interface) to reference the methods available to the interface. In this case, when I initialize a comparator, Arrays.sort(strArr, new Ideone()); the sort works correctly. How does the method know that I am passing it a comparator? I only initialized a class object and didn't call the compare(ob1, ob2) method explicitly.
Even if I do Comparator x = new Ideone();, how is the class object reduced to a comparator object? Any explanation on this would be helpful.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone implements Comparator
{
static String ThirdGreatest(String[] strArr)
{
Arrays.sort(strArr);
//Arrays.sort(strArr, new Ideone());
for(String x: strArr)
{
System.out.println(x);
}
return strArr[strArr.length-3];
}
@Override
public int compare(Object s1, Object s2)
{
return (s1.toString().length() - s2.toString().length());
}
public static void main (String[] args) throws java.lang.Exception
{
String[] myarr = {"coder","byte","code", "asfasfasfasf"};
System.out.println(ThirdGreatest(myarr));
}
}
strArrhas at least 3 elements too.