I would consider using Set
instead of ArrayList. Sets are defined by their requirement that all objects are unique. A HashSet
is a good default choice and may be a more proper data structure for you in this case, but it is ultimately your challenge.
When you add to a set, the add
method returns false
if the object is already contained in the set and a duplicate is not added.
If you need a predictable iteration order, you can use LinkedHashSet.
This implementation differs from HashSet in that it maintains a double-linked list that goes through all its entries. This linked list defines the iteration order, which is the order in which elements were inserted into the set (insert order)
Finally, you might consider using a navigation set in a TreeSet. It doesn't seem that sorting is important based on the information above, so this is probably not the right choice for you, but it is good information for your back pocket.
Just make sure that if you add your own class objects to Set, which you override and override correctly, the equals () method. This will not only match links and will lead to unexpected behavior and a noticeable headache. Use the @Override annotation to make sure you override correctly, but I'm distracted.
Hashset javadocs
TreeSet Javadocs
LinkedHashSet Javadocs
Kon source share