Jan Solo
Jan Solo

Reputation: 13

Sorting objects by a particular property

I am suppose to compare two courses and sort them alphabetically by course name, however I noticed that I cant use either "<" or ">". Is there another way to compare if the course should be greater or less than another.

import java.util.Comparator;

/**
 * A class that overrides the natural order comparison of courses to order
 * them alphabetically by course name.
 *
 */
public class CourseComparator implements Comparator<Course> {
    @Override
    public int compare(Course o1, Course o2) {
        if(o1.getName() == o2.getName()){
            return o1.compareTo(o2);
        if(o1.getName() < o2.getName())
            return 1;
        return -1;
    }
}

Upvotes: 0

Views: 169

Answers (1)

notes-jj
notes-jj

Reputation: 1547

Operators

  • == If both operands are Primitive Data Types it will do a value comparison. String is a Class not a Primitive Data Type.

  • < > Are Operators and are only reasonable with Primitive Data Types like int, double ...

Object Comparison

  • == Will compare to objects if they are the same object.

  • .equals(Object o) Will compare two objects if there Values are the same. Therefore you can overload this method you have to check what the author of the Class means by 'equal'. For the String Class .equals means same String.

  • .compareTo(String s) Is the String comparison in the meaning of before(-), after(+) and equals(0).

Your Example

Just using .compareTo on the both .getName()

public class CourseComparator implements Comparator<Course> {
    @Override
    public int compare(Course o1, Course o2) {
        return o1.getName().compareTo(o2.getName());
    }
}

Interface Comparable

By the Way you could implement the Interface Comparable than the sorting Options of Arrays.sort(Object[] a) or Collections.sort(List<T> list)) don't need a comparator.

public class Course implements Comparable<Course> {
    ...
    @Override
    public int compareTo(Course otherCourse) {
        return getName().compareTo(otherCourse.getName());
    }
}

Upvotes: 1

Related Questions