So I am to create this program that creates an array of persons which is sorted by a method in the class Algorithms. I am to create the interface Sortable which defines a comparison method called compareTo which should compare 2 objects to see which comes first. The Person Class represents a person and implements Sortable, and the Algorithms class has a method named sort which takes an array consisting of Sortable objects (Persons) and sort these. I am stuck, and my coursebook is not helping me much here.
public interface Sortable <T> {
int compareTo(T ob);
}
.
public class Algorithms implements Sortable <Person>{
public int compare(Person p1, Person p2){
return p1.lastName().compareTo(p2.lastName());
}
}
.
public class Person implements Sortable<Person>
{
String firstName;
String lastName;
String dob;
public Person (String lastName, String firstName, String dob){
this.lastName=lastName;
this.firstName=firstName;
this.dob=dob;
}
public String lastName(){
return lastName;
}
public String firstName(){
return firstName;
}
public String dob(){
return dob;
}
@Override
public int compareTo(Person o){
Person p = (Person)o;
int last = lastName.compareTo(o.lastName);
return last;
}
public String toString(){
return "Namn "+ lastName +" "+ firstName +" Personnummer: "+dob;
}
}
.
public class Personer {
public static void main(String[]args){
Person p1 = new Person ("Ek","Ida","530525-0055") ;
Person p2 = new Person ("Björk","Sten","650203-0250");
Person p3 = new Person ("Al", "Bengt","881212-4455");
List <Person> list = new ArrayList<>();
list.add (p1);
list.add (p2);
list.add (p3);
Arrays.sort(list, new Algorithms());
System.out.println("lista: "+list);
}
}
The question is really what do I need to do to make this code do what I want it to do, which in the end is to print out the names and dob of a number of people in alphabetical order based om last name
Comparable.