调用compareTo方法java问题

时间:2015-12-03 18:00:39

标签: java sorting oop

我正在尝试构建一个对象属性进行排序的方法,在此示例中为nrPagPublicate,该方法称为compareTo。 我怎么称呼它?我的界面好吗? 这就是我被困的地方:

import java.util.Arrays;
/**
 *
 * @author alex
 */
public class Autor implements Comparable<Autor> {

   /**
    * @param args the command line arguments
    */
    public String nume;
    private int nrPagPublicate;
    private final int masa = 22;
    //contrusctor obiecte
    public Autor(String nume, int nrPagPublicate){
        this.nume = nume;
        this.nrPagPublicate = nrPagPublicate;     
    }
    public void vorb(){
        System.out.println(nume + " asa ma cheama pe mine!");
    }
    //setters and gettters
    public String getNume() {
        return nume;
    }

    public void setNume(String nume) {
        this.nume = nume;
    }

    public int getNrPagPublicate() {
        return nrPagPublicate;
    }
    public int compareTo(Autor CompareAutor) {
        int comparenrPagPublicate = ((Autor)    CompareAutor).getNrPagPublicate(); 
    //ascending order
    return this.nrPagPublicate - comparenrPagPublicate;
    //descending order
    //return compareQuantity - this.quantity;        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    public void setNrPagPublicate(int nrPagPublicate) {
        this.nrPagPublicate = nrPagPublicate;
    }
    //constructor de copiere
    public Autor(Autor c){
        nume = c.nume;
        nrPagPublicate = c.nrPagPublicate;
    }


    public static void main(String[] args) {
        // TODO code application logic here
        Autor ion = new Autor("ion",23);
        Autor ion2 = new Autor("ion2",2);
        compareTo();
    } 
}

amd在我的界面中

public interface Comparable<Autor> {
    public int compareTo(Autor CompareAutor);
}

1 个答案:

答案 0 :(得分:1)

您有两种选择 - 实现Comparable intergace或write standalone Comparator接口。

这两个选项在http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/都有详细描述。

然后,您可以使用Arrays类将项目放入数组并进行排序:

Author[] authors = new Author[]{ ion, ion2, ion3, ... };
Arrays.sort(authors);
// now you would see the ion2 as first element in the array, ion as second element etc.