developer
developer

Reputation: 9478

What changes to be done in ArrayList to make it behave like a Set

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

Answers (4)

Paŭlo Ebermann
Paŭlo Ebermann

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

Puce
Puce

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

templatetypedef
templatetypedef

Reputation: 372814

There are many ways to accomplish this. Here are a two:

  1. Store the elements of the 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.
  2. Enforce that the elements of the 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

Jigar Joshi
Jigar Joshi

Reputation: 240898

  • Create your own implementation , implement java.util.List
  • override add(), addAll() , make use of contains()

Upvotes: 2

Related Questions