Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 715
so.very.tired Avatar asked Dec 03 '13 12:12

so.very.tired


People also ask

Why HashSet has no get method?

HashSet can not guarantee insertion order so no point in get method. What are you missing is implementing equals and use contains() which will iterate and find the object.

How does TreeSet contain work?

TreeSet is an ordered set, so any element you insert must implement Comparable (unless you specify a custom Comparator ). Class does not. If you don't need the ordering, you can always use an unordered set such as HashSet. Otherwise, you'll need to come up with an ordering of your own.

Does TreeSet allow duplicates?

TreeSet implements the SortedSet interface. So, duplicate values are not allowed and will be leftovers. Objects in a TreeSet are stored in a sorted and ascending order. TreeSet does not preserve the insertion order of elements but elements are sorted by keys.


1 Answers

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.
like image 147
Jesper Avatar answered Oct 05 '22 14:10

Jesper