Search code examples
javacomparisoncomparatorcomparable

How to use Comparator class to an object's data tag that is double?


I want to order my vector with full of myClass its like:

class MyClass
{

double distance;
String name;

 public void MyClass()
 {}

}

And then my vector is about:

MyVector<MyClass>myVector = new MyVector<MyClass>();

MyVector.add(myClass1);
MyVector.add(myClass2);
MyVector.add(myClass3);
//Etc....

I want to order my vector's elements by the distance data tag. I tryed to use comparator class but i failed, please someone can implement me a comparator class that is work for this case ?


Solution

  • Is this how you did it? Well, note that there are a few changes.

    List<MyClass> myVector = new Vector<MyClass>();
    
    myVector.add(myClass1);
    myVector.add(myClass2);
    myVector.add(myclass3);
    
    
    Collections.sort(myVector, new Comparator<MyClass>() {
        public int compare(MyClass one, MyClass two) {
            return Double.valueOf(one.getDistance()).compareTo(two.getDistance());
        }
    });
    
    1. Use a List on the left hand side of the assignment as you should always program against interfaces.
    2. I have added getter and setter methods to your MyClass.

    The other option, however, is to make your class Comparable.

    class MyClass implements Comparable<MyClass> {
        private double distance;
        private String name;
    
        @Override
        public int compareTo(MyClass other) {
            return Double.valueOf(this.distance).compareTo(other.distance);
        }
    
        ...
        getters and setters
        ...
    }
    

    Then you could simply write Collections.sort(myVector).