How to use the Comparator interface

后端 未结 5 2157
陌清茗
陌清茗 2020-12-29 09:32

I\'m new to java, and I\'m not really getting how to use the comparator interface. I have an ArrayList of Items in an Inventory class

5条回答
  •  抹茶落季
    2020-12-29 09:58

    Use of @Override annotation is a standard practice in editors like eclipse, netbeans to notify developer that he is overriding/implementing parent class/interface method. It is optional.

    Don't implement this interface in your Item class. Create a new class and implement the Comparator interface.

    public class ItemCompare implements Comparator {
    
        @Override
        public int compare(Item a, Item b) {
            if (a.getID().compareToIgnoreCase(b.getID())>0)
                return 1;
            else if (a.getID().compareToIgnoreCase(b.getID())<0)
                return -1;
            return 0;
        }
    } 
    

    And then, in your main class, do this:

    ArrayList al = new ArrayList
    
    Collections.sort(al, new ItemCompare())
    

提交回复
热议问题