I know this has propably been asked 1000 times, and i have seen 1000 answers, but i didn't see any that actually worked for me.
I have to sort a List of objects which implement my own interface. I decided to extend Comparable interface and implement compareTo method for those objects.
my interface:
public interface Field extends Comparable<Field> {
}
my object class
public class ConcreteField implements Field {
public int compareTo(Field other){
return this.getName().compareTo(other.getName());
}
}
This doesn't work as i would expect.
Compiler seems to recognize that the ConcreteField must implement compareTo. Thats fine.
With example above i can compare ConcreteField objects. But not when they are represented by their interface (Field).
I can sort a List of ConcreteField's but i cannot sort a List of Field's. Of course this is naturaly, since the implementation of compareTo is in ConcreteField, but i was expecting that java would call compareTo on each concrete object which implements Field. Seems not to be the case.
But then, how do you actually sort objects which are represented by their comparable interface?
Another strange things that i just dont get.
Using @Override over compareTo method makes the compiler yelling: The method compareTo(Field) of type ConcreteField must override or implement a supertype method. Huh? There is no supertype, its just implementing an interface.
When i remove compareTo from ConcreteField class. Compiler complains that it must be implemented. When i use eclipse quickfix, which says "implement missing methods", it fails to do so and tells me "Cannot implement the missing methods, either due to compiler errors or the project build path does not resolve all dependencies".
There is no dependency at all. Its all in the same project and even same package. So what the hell is wrong with this?
@Masud : Implementation suggested by you (Post deleted)
Create an interface like :
public interface Field<T> extends Comparable<T> {
public String getName();
}
Create a ConcreteField class like :
import java.util.Arrays;
public class ConcreteField implements Field<Field>{
private String name;
@Override
public int compareTo(Field other) {
return this.name.compareTo(other.getName());
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
ConcreteField[] c = new ConcreteField[3];
c[0] = new ConcreteField();
c[1] = new ConcreteField();
c[2] = new ConcreteField();
c[0].setName("c");
c[1].setName("b");
c[2].setName("a");
Arrays.sort(c);
for(int i=0;i<c.length;i++) {
System.out.println(c[i].getName());
}
}
}
The output I am getting is sorted.
a
b
c