How come Java's TreeSet has no get() method?

so.very.tired picture so.very.tired · Dec 3, 2013 · Viewed 52k times · Source

What if I want to retrieve and update objects that stored in a TreeSet?

The reason I'm asking, is that I want to be able to maintain some data stracture that will store Students. I want it to be sorted (by grades - which is an instance variable of Student), and - it needs to be kept sorted even after I update one (or more) grade(s) as well.

So, after briefly looking over Java's collections, I decided to go with TreeSet and set a comparator that compares two students by their grades. problem is, I just found out that TreeSet has no get() method!

Any help and suggestions would be greatly appreciated.

Answer

Jesper picture Jesper · Dec 3, 2013

What would you expect a get() method on a Set to do?

  • Sets are not indexed, so a get(int index) makes no sense. (Use a List if you want to get elements by index).
  • get(Object obj) would also not make sense, because you'd have the object that you're trying to get already.
  • There is already a contains() method to check if a Set contains an object.
  • You can iterate over a Set if you want to do something with all elements in the set.