Reputation: 9478
What changes to be done in ArrayList to make it behave like a Set (means it should not accept any duplicate values).
Upvotes: 0
Views: 864
Reputation: 74760
Other than already said, you could have a look at java.util.concurrent.CopyOnWriteArraySet
. If you leave the "CopyOnWrite" part away, you have your ArraySet
.
Upvotes: 0
Reputation: 38132
As the others said, it's unclear why you need this. Maybe LinkedHashSet is what you need? http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html
Upvotes: 0
Reputation: 372814
There are many ways to accomplish this. Here are a two:
ArrayList
in random order. When inserting a new value, do a linear scan over the elements and see if the element you're adding already exists. If so, don't add it. Otherwise, append it to the elements.ArrayList
always be stored in sorted order. To insert a new element, do a binary search to find where that element should be placed, and if the element already exists don't insert it. Otherwise, insert it at the given position.However, you shouldn't be doing this. These approaches are very slow compared to HashSet
or TreeSet
, which are specialized data structures optimized to handle this efficiently.
Upvotes: 3
Reputation: 240898
java.util.List
add()
, addAll()
, make use of contains()
Upvotes: 2