简体   繁体   English

使用另一个类的compareTo方法

[英]Use compareTo method from another class

I have a class called classes who has this compareto method: 我有一个叫做classes ,它具有以下compareto方法:

@Override
public int compareTo(Object other) {
    Cours ot = (Cours)other;
    String heure2 = ot.heure;
    int autre = Integer.parseInt(heure2.substring(0,2));
    int le = Integer.parseInt(this.heure.substring(0,2));

    if (autre > le) {
        return 1;
    }

    if (autre == le) {
        return 0;
    } else {
        return -1;
    }

}

I have another class called day that has a list of classes : 我有另一个名为dayclasses ,它有一个classes列表:

private List<Cours> journee;

And a method to sort the classes: 还有一种对类进行排序的方法:

public void TrieListe() {
    Collections.sort(journee);
}

When I use TrieListe() everything works fine, I can sort the list. 当我使用TrieListe()一切正常,我可以对列表进行排序。

But I've added another class called Weeks which contains a List of Days And now I want to use TrieList() from that class : 但是,我添加了另一个名为Weeks类,其中包含Days List。现在我想使用该类中的TrieList():

private List<Days> leWeek;

public void TrieListe() {
    Collections.sort(leWeek);
}

So how can I use my compareTo method from my classes class using sort() in my Weeks class. 那么如何在我的Weeks类中使用sort()从我的classes类中使用我的compareTo方法。

Create a new abstract class AComparableByHour and make your classes extend it. 创建一个新的abstractAComparableByHour ,并使您的类对其进行扩展。

public abstract class AComparableByHour implements Comparable<AComparableByHour> {

public abstract String getHeure();

// Your comparison method goes here 
@Override
public int compareTo(AComparableByHour ot) {
    String heure2 = ot.getHeure();

    int autre = Integer.parseInt(heure2.substring(0,2));
    int le    = Integer.parseInt(this.getHeure().substring(0,2));

    if( autre > le){
        return 1;
    }

    if( autre == le){
        return 0;
    } else {
        return -1;
    }
}

} }

public class Cours extends AComparableByHour {
    // This method is mandatory now. 
    // You could move it to the new superclass
    public String getHeure() {   
          return heure;
    }
    ...
}

public class Days extends AComparableByHour {
    public String getHeure() {
         return heure;
    }
    ...
}

I have a class called classes who has this compareto method: 我有一个叫做classes ,它具有以下compareto方法:

@Override
public int compareTo(Object other) {

This is already wrong. 这已经是错误的。 Your class should implement Comparable<classes> (noting that classes is a truly terrible name for a class, for at least three separate reasons), which will force the method signature to be: 您的类应实现Comparable<classes> (请注意,由于至少三个单独的原因, classes是一个classes的真正可怕的名称),这将强制方法签名为:

@Override
public int compareTo(classes other) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM