Переопределение метода compareTo для сортировки объектов по строковым значениям

У меня есть класс, реализующий интерфейс Comparable. В этом классе мне нужно переопределить метод compareTo, чтобы сортировать объекты по строковым значениям.

Если вы прокрутите вниз, я попытаюсь создать свой метод, и мне нужно в основном методе отсортировать массив курсов (используя метод compareTo, который я делаю) по первому типу отдела, а затем по номеру курса и т. д. но для этого нужно сравнить 2 строки.

   import java.io.Serializable;
   import java.io.*;
   import java.util.*;
public class Course implements Comparable<Course>, Serializable  {
private String prefix;
private int number;
private String Department;
private String grade;
/**
 * Constructs the course with the specified information.
 * 
 * @param prefix the prefix of the course designation
 * @param number the number of the course designation
 * @param Department the Department of the course
 * @param grade the grade received for the course
 */
public Course(String prefix, int number, String Department, String grade)
{
    this.prefix = prefix;
    this.number = number;
    this.Department = Department;
    if (grade == null)
        this.grade = "";
    else
        this.grade = grade;
}

/**
 * Constructs the course with the specified information, with no grade
 * established.
 * 
 * @param prefix the prefix of the course designation
 * @param number the number of the course designation
 * @param Department the Department of the course
 */
public Course(String prefix, int number, String Department)
{
    this(prefix, number, Department, "");
}

public String getPrefix()
{
    return prefix;
}

/**
 * Returns the number of the course designation.
 * 
 * @return the number of the course designation
 */
public int getNumber()
{
    return number;
}

/**
 * Returns the Department of this course.
 * 
 * @return the prefix of the course
 */
public String getDepartment()
{
    return Department;
}
/**
 * Returns the grade for this course.
 * 
 * @return the grade for this course
 */
public String getGrade()
{
    return grade;
}

/**
 * Sets the grade for this course to the one specified.
 * 
 * @param grade the new grade for the course
 */
public void setGrade(String grade)
{
    this.grade = grade;
}

/**
 * Returns true if this course has been taken (if a grade has been received).
 * 
 * @return true if this course has been taken and false otherwise
 */
public boolean taken()
{
    return !grade.equals("");
}

 * Determines if this course is equal to the one specified, based on the
 * course designation (prefix and number).
 * 
 * @return true if this course is equal to the parameter
 */
public boolean equals(Object other)
{
    boolean result = false;
    if (other instanceof Course)
    {
        Course otherCourse = (Course) other;
        if (prefix.equals(otherCourse.getPrefix()) &&
                number == otherCourse.getNumber())
            result = true;
    }
    return result;
}

Функция compareTo:

public int compareTo(Course o)
{
    if(getDepartment().equals(o.getDepartment()))
    {
        return 0;
    }
    else if()
    {
        return -1;
    }
    else
    {
        return 1;
    } 
}   

/**
 * Creates and returns a string representation of this course.
 * 
 * @return a string representation of the course
 */
public String toString()
{
    String result = prefix + " " + number + ": " + Department;
    if (!grade.equals(""))
        result += "  [" + grade + "]";
    return result;
    }
}

Основной класс на данный момент:

import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import java.*;


public class StackCourse 
{

 public static void main(String[] args) 
    {
        Course a = new Course("EEE", 230, "Engineering");
        Course b = new Course("MAT", 150, "Liberal Arts");
        Course c = new Course("PHY", 150, "Liberal Arts");
        Course d = new Course("PHI", 304, "Liberal Arts");
        Course e = new Course("ECN", 214, "W.P. Carey");
        Course f = new Course("EEE", 120, "Engineering");


        Course[] courses = {a,b,c,d,e,f};
        for(int i=0; i<courses.length; i++)
        System.out.println(courses[i].getDepartment());       
    }
}

person Adam Staples    schedule 07.07.2014    source источник
comment
Можете ли вы уточнить свой вопрос?   -  person Jake Chasan    schedule 07.07.2014
comment
В основном методе: Курс a = новый курс (EEE, 230, Engineering); Курс b = новый курс (MAT, 150, гуманитарные науки); Курс c = новый курс (PHY, 150, гуманитарные науки); Курс[] курсы = {а,б,в}; Теперь отсортируйте курсы сначала по типу факультета, а затем...   -  person Adam Staples    schedule 07.07.2014
comment
Можете ли вы добавить свой «основной» метод в тело вопроса?   -  person Jake Chasan    schedule 07.07.2014
comment
Почему вы возвращаете -1, 0 и 1, когда можно было просто вернуть getDepartment().compareTo(o.getDepartment())?   -  person aliteralmind    schedule 07.07.2014
comment
@JakeChasan добавлен «основной» метод. Теперь я хотел бы отсортировать этот массив, используя метод compareTo, который я пытаюсь создать.   -  person Adam Staples    schedule 07.07.2014


Ответы (3)


public int compareTo(Course o)
{
    if(getDepartment().compareTo(o.getDepartment()) ==0){
        if(getNumber() < o.getNumber()) return -1;
        else if(getNumber() > o.getNumber()) return 1;
        else return 0;
    }

    return getDepartment().compareTo(o.getDepartment());

}  

Выход:

EEE 120: Инженерное дело EEE 230: Инженерное дело MAT 150: Гуманитарные науки PHY 150: Гуманитарные науки PHI 304: Гуманитарные науки ECN 214: W.P. Кэри

person Maheedhar Pamuru    schedule 07.07.2014
comment
Хм... какой алгоритм сортировки вы использовали? Я имею в виду без использования Arrays.sort или чего-то подобного. Это в основном методе. - person Adam Staples; 07.07.2014
comment
Я использовал Collections.sort(list); // ArrayList‹Курс› - person Maheedhar Pamuru; 07.07.2014
comment
Единственное, что отличается, это метод compareTo, который я разместил выше... Вот основной метод: List‹Course› list =new ArrayList‹Course›(); список.добавить(а); список.добавить(б); список.добавить(с); список.добавить(д); список.добавить(е); список.добавить(е); Collections.sort(список); for(int i=0;i‹list.size();i++){ System.out.println(list.get(i)); } - person Maheedhar Pamuru; 07.07.2014

Если я последую вашему вопросу, я полагаю, вы хотели что-то вроде этого

public int compareTo(Course o)
{
    int a = getDepartment().compareTo(o.getDepartment());
    if(a != 0)
    {
        return a;
    }
    return Integer.valueOf(getNumber()).compareTo(o.getNumber());
}

Примечание. Вы можете вернуться, если сравниваемые поля не равны 0, потому что эти поля не равны.

person Elliott Frisch    schedule 07.07.2014

Просто используйте встроенный в String compareTo:

@Override
public int compareTo(Course o) {
    return this.Department.compareTo(o.Department);
}
person shmosel    schedule 07.07.2014
comment
Я могу использовать встроенный в Java String метод compareTo, даже если имя метода — compareTo? - person Adam Staples; 07.07.2014
comment
@AdamStaples Конечно... почему бы и нет? Это другой объект другого класса. - person shmosel; 07.07.2014