I have some design problems with Java Comparator
Interface.
I have a class which contains a Set
of a simple custom data structure:
I assume that you have a List
stored somewhere.. In Comparator, you need to invoke a getDataById
method from your data class, and sort through Priority..
Check the below code.. I have used a single class for many purpose..
Ideally you would want to break it into more classes.. But this is just a Demo, how to achieve what you want..
class Container {
// List of Data instances created..
// This list has to be static, as it is for a class,
// and not `instance specific`
public static List dataList = new ArrayList();
// List of Ids, that you want to sort.
private List idList = new ArrayList();
// Populate both the list..
// Have a method that will iterate through static list to
// find Data instance for a particular id
public static Data getDataById(long id) {
// Find Data with id from the list
// Return Data
}
public void sortList() {
Collections.sort(idList, new MyComparator());
}
}
public MyComparator implements Comparator {
public int compare(Long int1, Long int2) {
Data data1 = Container.getDataById(int1);
Data data2 = Container.getDataById(int2);
return data1.getPriority() - data2.getPriority();
}
}