11 - Collections - Exercise
Overview
The aim for this exercise is to replace the Array
in our Employee application with a Collection. We will also implement multiple ways of sorting the collection.
Task 1 - Replace Array with a Collection
Reopen your
EmployeeManagement
project we created (06 - OOP Intro - Exercise 1 ) previously.In the
EmployeeApplication
class, locate the main method and replace theArray
of three employees with a suitableCollection
object. (Hint: maybe one of theList
implementation?)Use the enhanced for loop when iterating through your collection.
In the
Manager
class, amend theaddEmployee
method to NOT allow a manager to manage more than 5 employees.Add the jar dependencies to your project as we did before and unit test your
Employee
andManager
classes. Which methods need special attention?
Task 2 - Sorting a collection of employees
Create a new class called EmployeeNameComparator, which implements java.util.Comparator interface.
Provide the
public int compare(Employee e1, Employee e2)
method. You can useString
'scompareTo
method on the employee's name.Sort the list of employees from the previous task. Use the class method defined on
Collections
class and provide a new instance of your comparator class.Print out the content of the list and check that the employees are indeed sorted.
Create a unit test for this functionality.