Jack E. Moore III
Jack E. Moore III

Reputation: 29

Why does this string comparator not compile?

This is the comparator I'm using:

import java.util.Comparator;

public class StringComparator implements Comparator
{
    public int compare(String obj1, String obj2) 
    {
        String delimeter = " ";
        String nameSplit1[] = obj1.split( delimeter );
        String nameSplit2[] = obj2.split( delimeter );

        return nameSplit1[1].compareTo(nameSplit2[1]);
    }
}

And this is the main file:

import java.util.*;

public class StringCompare
{
    public static void main( String args[] )
    {
        List<String> stringList = new ArrayList<String>();
        String delimeter = " ";

        stringList.add( "Seven Clocks" );
        stringList.add( "Twelve Beds" );
        stringList.add( "Eight Frogs" );


        Collections.sort( stringList, new StringComparator() );

        for ( String a : stringList )
        {
            System.out.println( a );
        }
    }
}

I'm basically trying to make a comparator so the collections.sort sorts according to the second word, not the first. But when I compile it, all I get is the StringComparator doesn't override the abstract method compare(Object, Object) error. Why is it giving me that error?...

Upvotes: 0

Views: 140

Answers (2)

Edwin Buck
Edwin Buck

Reputation: 70939

Because a comparator is a generic interface, and since you didn't define it to be a Comparator<String> it falls back on the most general definition, Comparator<Object> which means the parameters should be Objects and not Strings.

Change it to

public class StringComparator implements Comparator<String> {

and it should compile just fine.

Upvotes: 3

Perception
Perception

Reputation: 80623

You left out the generic parameter from the Comparator declaration.

public class StringComparator implements Comparator<String>
//                                                     ^
//                you need this!                       |
// ----------------------------------------------------

Upvotes: 6

Related Questions