07 - 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.
Task 3 - Time different types of collections
Create a large number of
Employee
objects with random details. The methodMath.random()
returns a randomdouble
between 0.0 and 1.0, which you can use to scale up to random ages for example:int age = (int) ((Math.random() * 40) + 18);
In the above expression, do you need all of the brackets?
You must also give the employees random names, which can be done in a similar way:
char c = (int) ((Math.random() * 26) + 65);
This gives you a random character, which you can assemble into Strings, and use the methods
toUpperCase()
andtoLowerCase()
in theString
class to make their names have the appropriate case.If you want to have 'normally' distributed ages, you might try experimenting with the class
java.util.Random
, which has an instance methodnextGaussian()
. But remember the ages are not unlimited!Refactor your code so all this random stuff is encapsulated. Perhaps the
Employee
class could have a methodcreateRandomEmployee()
?Similarly, create random
Manager
s, and devise some way to build a random organisation ofManager
s andEmployee
s.In such a fashion, create a million
Employee
s!The class method
System.currentTimeMillis()
tells you the epoch-based time (i.e. the number of milliseconds since the 1st Jan 1970!). You can use this to measure the time your application runs for. Do this and record your execution time.Experiment with different
Collection
implementation classes to see which one is faster.