简体   繁体   中英

How to sort ArrayList of classes

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;
}

The simplest solution if you're using java 8.

public ArrayList<iSomeInterface> sorting(){

    Collections.sort(someInterfaces, (iSomeInterface  i1, iSomeInterface  i2) -> i1.getLevel() - i2.getLevel());

    return someInterfaces;
}

If you're working in something prior to that you can implement your own comparator...with an anonymous inner class to still make a 1-liner...

public ArrayList<iSomeInterface> sorting(){
    Collections.sort(interfaces, new Comparator<iSomeInterface>() {
        @Override
        public int compare(iSomeInterface i1, iSomeInterface i2) {
            return i1.getLevel() - i2.getLevel();
        }
    });
    return interfaces;
}

I assume you want to modify your member variable, but you can always duplicate your list first.

(Note Collections is java.util.Collections)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM