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.
I assume you are using Collections.sort(..)
. You have two options:
Comparable
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(..)
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With