I am trying to sort arrayList of classes which have a abstract type.
Here is my interface
public interface iSomeInterface {
public int level();
}
There are couple of implementation of this interface which is different by their level implementations.
public class LevelOne implements iSomeInterface {
@Override
public int level() {return 1;}
}
public class LevelTwo implements iSomeInterface {
@Override
public int level() {return 2;}
}
public class LevelThree implements iSomeInterface {
@Override
public int level() {return 3;}
}
if I have couple of instances of these classes and passing them to the Levels
class
ArrayList<iSomeInterface> someInterfaces = new ArrayList<iSomeInterface>();
someInterfaces.add(new LevelOne());
someInterfaces.add(new LevelTwo());
someInterfaces.add(new LevelOne());
someInterfaces.add(new LevelThree());
someInterfaces.add(new LevelOne());
Levels levels = new Levels(someInterfaces);
How can I sort these classed based on their level value.
public class Levels {
private ArrayList<iSomeInterface> someInterfaces;
public Levels(ArrayList<iSomeInterface> someInterfaces){
this.someInterfaces = someInterfaces;
}
public ArrayList<iSomeInterface> sorting(){
//some code to sorting instances
return someInterfaces;
}
}
Answer : Thanks for your helps, The final answer :
public class someComparator implements Comparator<iSomeInterface> {
@Override
public int compare(iSomeInterface first, iSomeInterface second) {
return first.level()<second.level()?-1:first.level()==second.level()?0:1;
}
}
public ArrayList<iSomeInterface> sorting(){
Collections.sort(someInterfaces,new someComparator());
return someInterfaces;
}