Reputation: 1074
I am trying to build a method to sort an object property, in this example is nrPagPublicate and the method is called compareTo. How do I have to call it? Is my interface ok? This is where I`m stuck:
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 in my interface i have
public interface Comparable<Autor> {
public int compareTo(Autor CompareAutor);
}
Upvotes: 0
Views: 1440
Reputation: 18865
You have two options - either implement Comparable intergace or write standalone Comparator interface.
Both options are well described at http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/ .
You can then put the items into array and sort using Arrays class:
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.
Upvotes: 1