-1

How do I sort list1 with MyClass type of objects using list1.sort(); method

If I want the list to be sorted depending on Priority int value? So MyClass object with biggest priority will be at index 0 in LinkedList list1.

LinkedList<MyClass> list1 = new LinkedList<>();

this is what MyClass looks like and it has no Overriden methods.

public class MyClass {    
    int id;
    int LeftTime;
    int Priority;
    int Rasp;

    public Dretva(int[] lista) {
        this.id = lista[1];
        this.LeftTime = lista[2];
        this.Priority = lista[3];
        this.Rasp = lista[4];
    }

    public String toString(){
        return String.format("%d/%d/%d", id, Priority ,LeftTime);
    }
}
Alfred Huang
  • 17,654
  • 32
  • 118
  • 189

1 Answers1

0

You can write a custom comparator like this:

static class MyClassComparator implements Comparator<MyClass>
 {
     public int compare(MyClass c1, MyClass c2)
     {
         return c1.getPriority().compareTo(c2.getPriority());
     }
 }

And then use Collections.sort(list1,new MyClassComparator());

Sandeep Kaul
  • 2,957
  • 2
  • 20
  • 36