I have always wondered how would you implement a Set in Java. Can we implement it just like we implement a HashMap using a LinkedList and an object(Cell) which holds a Key and Value? How would you handle the uniqueness part?
The set interface is present in java. util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set.
The Java platform contains three general-purpose Set implementations: HashSet , TreeSet , and LinkedHashSet . HashSet , which stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration.
Set is a data structure that is used as a collection of objects. Java supports it through its Java Collection library. There are several ways to implement a set and Java supports three different implementations along with useful operations like intersection between sets.
There are three general-purpose Set implementations — HashSet , TreeSet , and LinkedHashSet . Which of these three to use is generally straightforward. HashSet is much faster than TreeSet (constant-time versus log-time for most operations) but offers no ordering guarantees.
Set internally implements a map.So each value in a set is just a key in map.So its uniqueness in maintained.
Here is the link.So that you get clear idea how set works internally. Also few stack Answers. First , Second
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