CST8132 Exercise 7 – Interfaces, ArrayList, Comparators

$30.00

Category: You will Instantly receive a download link for .zip solution file upon Payment

Description

5/5 - (2 votes)

Steps:
• Create a new project in Eclipse
• Add three classes:
1. Person (provided)
2. PersonFirstNameComparator (provided)
3. PersonTester
Tasks:
Using a main method within PersonTester:
1. Instantiate an ArrayList but reference it using List 2. Add three Person objects to the ArrayList you created in task 1
3. Use a loop to print the three person objects on screen, before sorting
4. Use Collections.sort() with the List and the Comparator provided to sort the Person objects by FirstName
5. Use a loop to print the three person objects on screen, after sorting
Bonus: Define 2 Comparators one to sort by Person last name, a second for age. Then demonstrate using them.
Class Person:
public class Person {
private String firstName;
private String lastName;
private int age;
public Person(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName(){ return firstName; }
public void setFirstName(String firstName){this.firstName = firstName;}
public String getLastName(){return lastName;}
public void setLastName(String lastName){this.lastName = lastName;}
public int getAge(){return age;}
public void setAge(int age){this.age = age;}
@Override public String toString(){
return String.format(“%s %s %d”, firstName, lastName, age);
}
}
Class PersonFirstNameComparator:
import java.util.Comparator;
public class PersonFirstNameComparator implements Comparator {
public int compare(Person p1, Person p2){
return p1.getFirstName().compareTo(p2.getFirstName());
}
}
Grading Guide (Total Score 10):
ArrayList instantiated correctly? 2
ArrayList referenced by List? 2
Sample Person objects added to ArrayList? 2
Collections.sort() used to sort by First Name with Comparator? 2
Person objects referenced by List output before and after sorting? 2
Bonus? 4
Expected Total 10
Sample Program Output:
Before sorting:(firstName, lastName, age)
aaa bbb 1
xyz abc 2
kyj lmn 3
After sorting:(firstName, lastName, age)
aaa bbb 1
kyj lmn 3
xyz abc 2