Question

I need to Implement a static method in my class Student

public static Comparator<Student> getCompByName()

that returns a new comparator object for Student that compares 2 Students objects by the attribute 'name'.

Iv created what I think is correct, but I am not sure if it will function like it is supposed to from the requirements given above. I am very new with comparators and having a hard time with them.

public static Comparator<Student> getCompByName()
{

 Comparator comp = new Comparator<Student>(){
     @Override
     public int compare(Student s1, Student s2)
     {
        return Integer.compare(s1.name.length(), s2.name.length());
     }

 };
 return comp;
}  

Just from reading the requirements stated above, I am not sure what I am supposed to be comparing about the 'name', whether it be the length, if they are equal, etc.. So I threw in an Integer compare. Is it clear to anyone from what is required and if I have done this correctly? If not, can anyone let me know what I need to do/change?

Was it helpful?

Solution

Looking at the documentation, the compare() method should be used to determine the order of the two students (here, you would want to do it alphabetically). If you wanted to check for equality, you could override the equals() method of the Comparator. For strings, you can just use existing methods to compare the students' name fields.

public static Comparator<Student> getCompByName()
{

    Comparator comp = new Comparator<Student>(){

        @Override
        public int compare(Student s1, Student s2)
        {
            s1.name.compareTo(s2.name)
        }

    };

    return comp;
}

OTHER TIPS

Assuming your 'name' attribute is a string, you can directly compare the names, using

s1.name.compareTo(s2.name)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top