1

Is there a java collection that only allow unique object in and with a get (index i) method ?

i firstly think of a treeSet but there is no get methods in ...
what i want be able to :

// replace object with any class that implement the right things to make it work
Collection<Object> collection = dunno<Object>();
Object o = new Object()
Object o2 = new Object()

collection.add(o)
collection.add(o)

collection.size() // should get 1
collection.get(0) // should return o

// let's suppose that o2 is lower than o (if the collection doesn't sort the way i want i can change it anyway)

collection.add(o2)
collection.get(0) // should return o2

so basicly like a treeSet but with a get methods does anyone know something like that ?

Galyfray
  • 118
  • 1
  • 10
  • 1
    You could always use `contains` before adding to a `List` if you need to – user May 04 '20 at 18:38
  • yes it could be a good idea is using contain and adding to a list as fast as adding to a treeSet especially for some large set ? i could easly manupulate over a thousand of element ... – Galyfray May 04 '20 at 18:42
  • 2
    Does this answer your question? [Any implementation of Ordered Set in Java?](https://stackoverflow.com/questions/8712469/any-implementation-of-ordered-set-in-java) – SomeDude May 04 '20 at 18:42
  • The answers in the question @SomeDude linked to suggests LinkedHashSet – user May 04 '20 at 18:45

4 Answers4

1

There is no such collection in the in the standard library, and I am also not aware of something like that in other widespread libraries like guava or apache commons.

Thus the answer is: you will have to implement your own collection for that. A straight forward solution would use a set and a list to provide the required interface, which will work but obviously increase the memory footprint to a certain degree.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

override equals and hashcode in ur custom class use Arraylist and u can check list.contains before adding to remove duplicate

Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37
0

The LinkedHashSet maintains the order of insertion while maintaining also the uniqueness of the items inserted.

Although it doesn’t have a dedicated get(i) method you can implement one by just iterating through the set.

You will pay for the performance of get() though.

SomeDude
  • 13,876
  • 5
  • 21
  • 44
-1

You should use the LinkedHashSet. This collection does only accept unique objects and keeps track of the order

famabenda
  • 80
  • 1
  • 13