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.
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.
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.
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.
What would you expect a get()
method on a Set
to do?
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.contains()
method to check if a Set
contains an object.Set
if you want to do something with all elements in the set.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With