TreeSet - how does it sort incoming elements?
TreeSet accepts only objects, and sorts with their Comparable implementation
Case 1: Integer, Double, Long, etc
TreeSet uses their already existing Comparable implementation and sorts the numeric values automatically.
Case 2: Custom objects
We must implement our own Comparable for these custom objects.
TreeSet - how does it use hashcode or equals?
No, it only uses compareTo() (or Comparator) to sort or locate an element.
HashSet uses hashcode() and equals()
TreeSet - what is a useful use case?
Hibernate gives us unordered result set.
We can feed it in a TreeSet to obtain an ordered/sorted set according to our business needs
E.g. treeSet.addAll(hibernateUnorderedSet)
TreeSet - how to traverse?
With advanced for loop or with iterator. Best use iterator - also removes items when iterating without ConcurrentModification.
Equals() - what's its purpose?
By default, Object.equals() checks equality by memory references
But in our business domain and collections, we may want to define equality with our own terms (override equals())
When we override equals, we must override hashcode, because of equals-hashcode contract:
Equals() - does HashSet use it?
HashSet and all Set collections (and Map ones) are hash-based.
That means they check for matching using hashcode() first. But in case of hashcode collision, they use equals() secondly.
Hibernate - what data structures to use per case?
Arraylist - For read-only collections, when random access is acceptable
LinkedList - For read-write collections, when modifications are frequent. LinkedList is fast for inserting/removing elements.
For example, use for Students of a Course entity, with @ElementCollection.
HashSet - When we want to filter query results with unique values
TreeSet - When we want to sort query results by our business comparison implementation.
Example for both:
TreeSet - how to have two comparison fields?
- CascadeType.REMOVE
- CascadeType.DETACH
Δεν υπάρχουν σχόλια:
Δημοσίευση σχολίου
What may be missing, or could get better?