Java programming language

Collections

Collection management - Additional exercises

  

Exercise 1:

Create a project called ListBenchmark. We are going to test in which cases is better to use an ArrayList, or a LinkedList. To measure the time an operation takes, you can use this piece of code:

Instant start = Instant.now();
// Some operation with ArrayList or LinkedList
Instant end = Instant.now();
Duration dur = Duration.between(start, end);
System.out.printf("ArrayList: The operation ... takes: %dms\n", dur.toMillis());

You have to compare these situations (ArrayList<Double> vs LinkedList<Double>). Create one of each empty and reuse the same lists in every comparison:

  1. Add 100.000 (double) random items always at position 0. Compare times.
  2. Delete the first 50.000 items (always delete the first one).
  3. Add 50.000 random items in random positions.
  4. Delete 50.000 items from random positions.

You’ll see that when using a lot of random accesses (index), ArrayList is much faster (LinkedList needs to count from the beginning). When adding or deleting items at the beginning the situation is the opposite (ArrayList has to reorder internal indexes every time, whereas LinkedList doesn’t need to).

Exercise 2:

Create a project named Companies with these classes (including Main):

Exercise 3:

Create a project called AnimalConversation containing the following classes (including a Main class):