CST8102 – CST8132 Object Oriented Programming (Solution)

$ 20.99
Category:

Description

Exercise 7 – Interfaces, ArrayList, Comparators

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<Person> but reference it using List<Person>
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<Person> { 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

Reviews

There are no reviews yet.

Be the first to review “CST8102 – CST8132 Object Oriented Programming (Solution)”

Your email address will not be published. Required fields are marked *