Sorting problem cannot instantiate abstract object overriding compareTo() Method
I'm trying to establish a new sort criteria, in this case by name. I'm facing an error when I call the sort method...
this is a separated class (SortByName) in package "package":
-----------------------CLASS SortByName---------------------------
package package;
import java.util.*;
public abstract class SortByName implements Comparator{
public int compareTo(Object o1, Object o2){
String n1 = ((Ficha)o1).getName();
String n2 = ((Ficha)o2).getName();
return n1.compareTo(n2);
}
and then inside an ActionPerformed event I have this:
----------------IN THE ACTION EVENT BUTTON-----------开发者_运维百科-----------------
Collections.sort( list , new SortByName() );
"package.SortByName is abstract,> cannot be instantiated"
I tried changing the "abstract" type in the class definition (SortByName) , but it complies about not overriding the compareTo() method.
thanks for reading.
The method you have to implement is called compare
, not compareTo
.
Abstract classes cannot be instantiated.
Also, Comparator
is generic, so you'd better do the following:
public class SortByName implements Comparator<Ficha>{
public int compareTo(Ficha f1, Ficha f2){
String n1 = f1.getName();
String n2 = f2.getName();
return n1.compareTo(n2);
}
}
Comparator needs to implement compare(), not compareTo() method.
class SortByName implements Comparator<Ficha>{
@Override
public int compare(Ficha o1, Ficha o2) {
String n1 = o1.getName();
String n2 = o2.getName();
return n1.compareTo(n2);
}
}
You need to remove "abstract" and implement the equals method as well.
Code should look like:
package package;
import java.util.*;
public class SortByName implements Comparator{
public int compare(Object o1, Object o2){
String n1 = ((Ficha)o1).getName();
String n2 = ((Ficha)o2).getName();
return n1.compareTo(n2);
}
public boolean equals(Object o1) {
// code which compares the current comparator (!) with the object given
}
Note that you might need to use specialized comparators if compiling against a version of java which supports generics. Not sure if this is correct but I think you can do something like:
public class SortByName implements Comparator <Ficha> {
public int compare(Ficha o1, Ficha o2){
// comparing code here
}
}
But again, not entirely sure on that part, you need to test it a bit.
If you check out the Comparator API that will explain how you must implement equals.
Also note that the Comparator interface defines compare
, not compareTo
.
Laura you were right I had to add the equals method.( u missed the return value) also remove "abstract" at class definition. and change compareTo() with compare().
thanks a lot Laura, PROBLEM SOLVED !!!!
精彩评论