Kate Albany
Junior Poster in Training
71 posts since Jun 2005
Reputation Points: 10
Solved Threads: 1
Hashset is an excellent idea, but if you want to just use arraylists then the contain method hook mentioned is the way to go.
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
Using contains would indeed work, but if the List gets large it gets ever more expensive to do the check (it's an O(n) operations, iterating over the entire dataset until either the end is reached or a match is found).
Using a container that prohibits duplicates is indeed a more logical choice.
HashSet checks for duplicates during insert based on hashCode and equals (so make sure to correctly override both for your custom classes when using them in a HashSet) which is a lot faster potentially.
jwenting
duckman
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
hascCode is used in concert with equals to determine whether (and where) in a HashSet (or other hash based collection) an object exists.
You need to have these methods in working order (and thus overridden from the defaults in Object) in order for the algorithms to work correctly.
There's a good explanation in "Effective Java" by Joshua Bloch.
jwenting
duckman
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
don't hijack other peoples' threads.
don't revive long dead threads.
do your own homework.
don't ask for private help by email.
jwenting
duckman
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337