Java LinkedHashSet
Syntax:
java.lang.Object
java.util.AbstractCollection
java.util.AbstractSet
java.util.HashSet
java.util.LinkedHashSet
Constructors:
lhset = new LinkedHashSet();
LinkedHashSet hs = new LinkedHashSet();
//Integer type
LinkedHashSet lhset1 = new LinkedHashSet();
//String type
LinkedHashSet lhset2 = new LinkedHashSet();
lhset2.add("PQ");
System.out.println(lhset2);
i=lhset1.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
System.out.println(lhset1.contains(99));
Syntax:
java.lang.Object
java.util.AbstractCollection
java.util.AbstractSet
java.util.HashSet
java.util.LinkedHashSet
- Note: E - the type of elements maintained by this set
- The LinkedHashSet class has no members of its own.
- Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface.
- A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements.
- The hash code is then used as the index at which the data associated with the key is stored.
- The transformation of the key into its hash code is performed automatically.
- The LinkedHashSet does not allow duplicate elements and it does not maintain order.
- The difference between them is...
- HashSet doesn’t maintain any kind of order of its elements.
- TreeSet sorts the elements in ascending order.
- LinkedHashSet maintains the insertion order and Elements gets sorted in the same sequence in which they have been added to the Set.
Constructors:
- HashSet( ): This constructor constructs a default HashSet.
- HashSet(Collection c): This constructor initializes the hash set by using the elements of the collection c.
- LinkedHashSet(int capacity): This constructor initializes the capacity of the linkedhashset to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
- LinkedHashSet(int capacity, float fillRatio): This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments.
- How to declare object of LinkedHashSet?
- Syntax:
- Example:
LinkedHashSet hs = new LinkedHashSet();
//Integer type
LinkedHashSet
//String type
LinkedHashSet
- How to add new elements in LinkedHashSet?
- Syntax:
- Example:
lhset2.add("PQ");
- How to display all elements from LinkedHashSet?
- Example:
System.out.println(lhset2);
- How to display all elements using iterator?
- Example:
while(i.hasNext())
{
System.out.println(i.next());
}
- How to remove an element from LinkedHashSet?
- Example:
- How to check given element is present or not?
- Example:
System.out.println(lhset1.contains(99));
- How to get the size of LinkedHashSet?
- Example:
Tags:
Java