è necessario implementare l'interfaccia paragonabile
implements Comparable
il metodo che fa il lavoro è
public int compareTo(Object obj)
{
}
prega di notare che oggetto è spesso sostituito da un pieno sul tipo a causa della sintassi generica che può essere utilizzato nell'istruzione implements (mostrato sotto).
Un esempio completo è here in the tutorial docs speranza che questo aiuta
Un esempio completo (prendere dal link qui sopra è il seguente), ho aggiunto questo solo nel caso in cui il link si esaurisce ad un certo punto
import java.util.*;
public class Name implements Comparable<Name> {
private final String firstName, lastName;
public Name(String firstName, String lastName) {
if (firstName == null || lastName == null)
throw new NullPointerException();
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() { return firstName; }
public String lastName() { return lastName; }
public boolean equals(Object o) {
if (o == null || !(o instanceof Name))
return false;
Name n = (Name) o;
return n.firstName.equals(firstName) && n.lastName.equals(lastName);
}
public int hashCode() {
return 31*firstName.hashCode() + lastName.hashCode();
}
public String toString() {
return firstName + " " + lastName;
}
public int compareTo(Name n) {
int lastCmp = lastName.compareTo(n.lastName);
return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
}
}
il codice client dal l'articolo è:
import java.util.*;
public class NameSort {
public static void main(String[] args) {
Name nameArray[] = {
new Name("John", "Smith"),
new Name("Karl", "Ng"),
new Name("Jeff", "Smith"),
new Name("Tom", "Rich")
};
List<Name> names = Arrays.asList(nameArray);
Collections.sort(names);
System.out.println(names);
}
}
fonte
2012-04-13 17:34:41
Il vostro professore desidera di implementare l'algoritmo di ordinamento te stesso? –
quello che @joncarl dice è un buon punto, se è così è necessario guardare a bubblesort (è abbastanza facile da implementare ma non così veloce) –
Sì, implementerò l'inserimento di tipo alg. – user1253201