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
To use the Comparator interface you have to implement it and pass it as an anonymous class to Collections.sort(List list, Comparator c) as the second parameter.
If you want to pass only the list to Collections.sort(List list) then your Item class has to the implement Comparable interface.
So in both cases the Collections.sort methods know how to order the elements in your list
here is some sample code:
Item class implementing Comparable + Inventory holding a list of items
public class Item implements Comparable- {
String id = null;
public Item(String id) {
this.id = id;
}
@Override
public String toString() {
return id;
}
@Override
public int compareTo(Item o) {
return - id.compareToIgnoreCase(o.id);
}
}
public class Inventory {
List
- items = new ArrayList<>();
public void addItem(Item item) {
items.add(item);
}
public static void main(String[] args) {
Inventory inventory = new Inventory();
inventory.addItem(new Item("2"));
inventory.addItem(new Item("4"));
inventory.addItem(new Item("1"));
inventory.addItem(new Item("7"));
Collections.sort(inventory.items, new Comparator
- () {
@Override
public int compare(Item o1, Item o2) {
return o1.id.compareToIgnoreCase(o2.id);
}
});
System.out.println(inventory.items);
Collections.sort(inventory.items);
System.out.println(inventory.items);
}
}
Output
[1, 2, 4, 7] // ascending
[7, 4, 2, 1] // descending since the compareTo method inverts the sign of the comparison result.