- A HashSet is an unsorted, unordered Set.
- It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance you'll get.
- Use this class when you want a collection with no duplicates and you don't care about order when you iterate through it.
- This class permits the null element
- If you attempt to add an element to a set that already exists in the set, the duplicate element will not be added, and the add() method will return false
This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets
Output
==============================================================================================
LinkedHashSet
- A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements.
- Use this class instead of HashSet when you care about the iteration order.
- When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.
- permits null elements
It provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets.
As you have already seen in the above program that order is unpredictable, now we'll in the below program LinkedHashSet maintain insertion order.
Output
Note HashSet, LinkedHashSet implementation is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally
Difference between HashSet and LinkedHashSet? *interview question
LinkedHashSet performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list with one exception:
- Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity.
- Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity.
==============================================================================================
TreeSet
The TreeSet is one of two sorted collections (the other being TreeMap). It uses a Red-Black tree structure, and guarantees that the elements will be in ascending order, according to natural order.
- Guarantees log(n) time cost for the basic operations (add, remove and contains).
- Offers a few handy methods to deal with the ordered set like first(), last(), headSet(), and tailSet() etc
- Tress set will not allow null object. if you try to add null value i will be throw null pointer exception
Note that the ordering maintained by a set must be consistent with equals if it is to correctly implement the Set interface.
This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.
The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.
Few functions of TreeSet with the help of example
- ceiling(E e) : Returns the least element in this set greater than or equal to the given element, or null if there is no such element.
- floor(E e) : Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
- higher(E e) : Returns the least element in this set strictly greater than the given element, or null if there is no such element.
- lower(E e) : Returns the greatest element in this set strictly less than the given element, or null if there is no such element.
- SortedSet<E> headSet(E toElement) : Returns a view of the portion of this set whose elements are strictly less than toElement.
- SortedSet<E> tailSet(E fromElement) : Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
Output
Difference between HashSet and TreeSet? *interview question
HashSet
- Hash set allow null object
- class offers constant time performance for the basic operations (add, remove, contains and size).
- Does not guarantee that the order of elements will remain constant over time
- Iteration performance depends on the initial capacity and the load factor of the HashSet.
- It's quite safe to accept default load factor but you may want to specify an initial capacity that's about twice the size to which you expect the set to grow
TreeSet
- Tress set will not allow null object .if you try to add null value i will be throw null pointer exception
- log(n) time cost for the basic operations (add, remove and contains).
- elements of set will be sorted (ascending, natural, or the one specified by you via it's constructor)
- Doesn't offer any tuning parameters for iteration performance
==============================================================================================
Map Interface
- A Map cares about unique identifiers.
- The Map implementations let you do things like search for a value based on the key, ask for a collection of just the values, or ask for a collection of just the keys.
- Like Sets, Maps rely on the equals() method to determine whether two keys are the same or different.
- A map cannot contain duplicate keys; each key can map to at most one value.
- The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings.
- Great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map
HashMap
- The HashMap gives you an unsorted, unordered Map, it does not guarantee that the order will remain constant over time.
- HashMap allows one null key and multiple null values in a collection
- When you need a Map and you don't care about the order (when you iterate through it), then HashMap is the way to go; the other maps add a little more overhead
- The more efficient your hashCode() implementation, the better access performance you'll get.
- The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.
- This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.
As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs.
Output
==============================================================================================
Hashtable
- Just as Vector is a synchronized counterpart to the sleeker, more modern ArrayList, Hashtable is the synchronized counterpart to HashMap.
- Remember that you don't synchronize a class, so when we say that Vector and Hashtable are synchronized, we just mean that the key methods of the class are synchronized
How Hashtable differ from HashMap? *interview question
- Hashtable doesn't let you have anything that's null whereas HashMap allows one null key and multiple null values in a collection
- HashMap is not Synchronized where as HashTable is Synchronized.
- HashMap cannot be shared with multiple thread without proper synchronization where HashTable is thread safe and can be shared between multiple thread
- Iterator in HashMap if fail fast where as Enumerator in HashTable is not fail fast
Output
==============================================================================================
LinkedHashMap
- Like its Set counterpart, LinkedHashSet, the LinkedHash- Map collection maintains insertion order (or, optionally, access order).
- Slower than HashMap for adding and removing elements, you can expect faster iteration with a LinkedHashMap.
Example will be same as above.
TreeMap
And you already know that by default, this means "sorted by the natural order of the elements.
Like TreeSet, TreeMap lets you define a custom sort order (via a Comparable or Comparator) when you construct a TreeMap, that specifies how the elements should be compared to one another when they're being ordered
Output
The iterators returned by this all the above class's iterator methods are fail-fast as you have already seen in the above examples.
Related Post
4 ways to iterate over Map in java
120+ Core java interview Question including Collection related also
7 new feature of Java 7
Garbage Collection from Interview perspective
If you know anyone who has started learning Java, why not help them out! Just share this post with them.
Thanks for studying today!...