I have a list of objects where each object has variables previous and next ,they are of type String
List testList=new ArrayList();
CustomObject o1=new CustomObject();
o1.setPrevious(null);
o1.setNext("a");
CustomObject o2=new CustomObject();
o2.setPrevious("a");
o2.setNext("b");
CustomObject o3=new CustomObject ();
o3.setPrevious("b");
o1.setNext("END");
testList.add(o3);
testList.add(o1);
testList.add(o2);
But i need to get it in the order o1,o2,o3.I have written a comparator to do this but i am not getting it right
class OrderComparator implements Comparator{
public int compare(CustomObject obj1, CustomObject obj2) {
if(obj1.getPrevious()==null)
return -1;
else if(obj2.getPrevious()==null)
return 1;
else if(obj1.getNext()!=null&&obj2.getPrevious()!=null&& obj1.getNext().equals(obj2.getPrevious()))
return -1;
else if(obj1.getNext()!=null&&obj2.getPrevious()!=null&&obj2.getNext().equals(obj1.getPrevious()))
return 1;
else if(obj1.getNext().equals("END"))
return -1;
else if(obj2.getNext().equals("END"))
return 1;
else return 0;
}
}
Collections.sort(testList,new OrderComparator());
Your compare method is not complete. Consider the following ordered list of objects:
obj1, obj2, obj3, obj4, obj5, END
If I pass obj1 and obj5 to your compare method, they would not be processed correctly. The reason is that given an object o, you are checking its previous, next, the previous of the previous of the previous object and the next of the next object.
This problem can be solved using the following pseudo code.
Similarly, check if o2 is greater