Sort vector of custom objects

I am trying to sort a vector in java, but my Vector is not an int vector, it is an object vector

an object:

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

so I have Vectorof MyObject, and I want to order it numObject, how to do it, am I new to java?

Thank you so much for your help.

+3
source share
3 answers

To sort an object's vector, first the MyObject class must implement Comparable and implement the compareTo (Object) method, and then use Collections.sort (Vector)

class MyObject implements Comparable<MyObject> {
    public int compareTo(MyObject a) {
       //return either 1, 0, or -1
       //that you compare between this object and object a
  ``}
}

//and in your logic write this line
Collections.sort(myVector);

check out JavaDoc Vector

+2
source

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

Comparable :

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

, . , Comparator, Collections.sort(..);

+7

Comparable . , . , MyObject SortedSet (, TreeSet), . , , , numObject. , Comparable ( ) .

. http://eyalsch.wordpress.com/2009/11/23/comparators/.

+1

Source: https://habr.com/ru/post/1739622/


All Articles