Set:
It's the child interface of collection
If we want to represents a group individual objects where duplicates are not allowed and and insertion order not preserved then best choice is set.
HashSet:
The underling data structure is HashTable insertion order is not preserved and it's based on hashcode of objects.
Duplicate objects are not allowed if trying to insert duplicate objects we wont get any compile time or run time error simple add method of hashtable returns false.
Heterogeneous objects are allowed for insertion null insertion also possible.
Construtors:
1.HashSet<String> elements=new HashSet<String>();
Creates an empty HashSet object with default initial capacity 10 and default fill ratio 0.75(meas after filling 0.75% of elements it again increase the capacity to 10)
2.HashSet<String> elements=new HashSet<String>(20);
Creates an empty HashSet object with initial capacity 20 and default fill ration is 0.75
3. HashSet<String> elements=new HashSet<String>(10,9);
Creates an empty HashSet object with initial capacity 20 and fill ration is 9
4.HashSet<String> elements=new HashSet<String>(Collection c);
Create HashSet object with given collections
Example:
package com.collections;
import java.util.HashSet;
public class HashDemo {
public static void main(String[] args) {
HashSet<String> elements=new HashSet<String>();
elements.add("one");
elements.add("one");
elements.add("one");
elements.add("two");
elements.add("three");
System.out.println(elements);
}
}
output:[two, one, three]
it's not fallow insertion order and it's not allowed
duplicate values.
LinkedHashSet:
It's child class of HashSet it exactly same as HashSet except the fallowing difference
HashSet LinkedHashSet
1.the underlying datastructure Hashtable 1.the underlying datastructure is combination of Hashtable
Hashtable and linkedlsit
2.insertion order is not preserved 2.insertion order is preserved
3.introduced in jdk 1.2 3.introduced in jdk 1.4
Example:
package com.collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
public class HashDemo {
public static void main(String[] args) {
LinkedHashSet<String> elements=new LinkedHashSet<String>();
elements.add("one");
elements.add("one");
elements.add("one");
elements.add("two"); elements.add("three");
System.out.println(elements);
}
}
output:[one, two, three] same like above program but difference in output is
it fallows insertion order.
SortedSet:(Interface)
output:[one, two, three] same like above program but difference in output is
it fallows insertion order.
0 comments: