Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a Vector of custom objects

Tags:

java

I'm trying to sort a Vector in java but my Vector is not a vector of int, it is a vector of objects

the object is:

public MyObject() {
    numObj = 0;
    price = new Price();
    pax = new Pax();        
}

so I have a Vector of MyObject and I want to order it by numObject, how do i do it, I'm new in java?

Thank you so much for all your help.

like image 390
Eddinho Avatar asked Dec 23 '22 04:12

Eddinho


1 Answers

I assume you are using Collections.sort(..). You have two options:

  • make your class implement Comparable
  • when sorting, create a custom Comparator

An example for implementing Comparable would be:

public class MyObject implements Comparable<MyObject> {
   // ..... other fields and methods
   public int compareTo(MyObject other) {
        return numObj - other.getNumObj();
   } 
}

This will mean the items are sorted in ascending order. If you want other, custom sorting, you can create a Comparator that defines the custom comparison and pass it as an argument to Collections.sort(..);

like image 144
Bozho Avatar answered Jan 07 '23 06:01

Bozho