Java: Collections Exercise 1 - Unique Components

Name ____________________________________

For the purposes of this exercise, the only data structures that need to be considered are: array, ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap. For passing over the elements of a data structure, consider only Iterator and for loop.

Situation: A surprisingly common error in layouts is to add the same component twice. This happens when the layout code is edited, and old code is not deleted. Layout managers do not normally check for this, and the resulting layout behavior can be difficult to debug.

Question: What data structure would be appropriate for recording each component as it's added to the layout, and how could this data structure be used? Show the following:

  1. The data structure instance variable, m_componentsSeen, declaration and intialization.
  2. A method, private boolean isNewComponent(Component comp), that returns false if the component has been seen before (ie, is in m_compontsSeen). If it isn't in m_componentsSeen, the method should add it and return true.