Java Tutorial
HashSet()
This constructor builds an empty HashSet.
HashSet(Collection collection)
This constructor initializes the elements of the collection.
HashSet(int capacity)
Initializes the capacity of the hash set to capacity.
HashSet(int capacity, float loadCapacity)
Initializes the capacity and fill ratio(also called load capacity) of the hash set.
add method is used to add element in the HashSet.
add(object)
contains method is used to check whether element exists in HashSet or not. returns true if object exist in HashSet, otherwise returns false.
contains(object)
remove method is used to remove element in the HashSet.
remove(object)
size method is used to return the number of elements in the HashSet.
size()
// Codingpointer Demonstrates HashSet import java.util.*; class HashSetTest { public static void main(String args[]) { HashSet hs = new HashSet(); //Add elements hs.add("B"); hs.add("E"); hs.add("D"); hs.add("E"); System.out.println(hs); } }Output:
$ java HashSetTest [B, D, E]
import java.util.*; class HashSetTest { public static void main(String args[]) { HashSet hs = new HashSet(); //Add elements hs.add("B"); hs.add("E"); hs.add("D"); hs.add("E"); System.out.println(hs); System.out.println("HashSet contains 'B':" + hs.contains("B")); System.out.println("HashSet contains 'R':" + hs.contains("R")); System.out.println("Size: "+hs.size()); hs.remove("E"); System.out.println("after removed 'E'"); System.out.println(hs); System.out.println("Size: "+hs.size()); } }Output:
java HashSetTest [B, D, E] HashSet contains 'B':true HashSet contains 'R':false Size: 3 after removed 'E' [B, D] Size: 2
import java.util.*; class HashSetTest { public static void main(String args[]) { HashSet hs = new HashSet(); //Add elements hs.add("B"); hs.add("E"); hs.add(2); hs.add("E"); System.out.println(hs); System.out.println("HashSet contains 'B':" + hs.contains("B")); System.out.println("HashSet contains 'R':" + hs.contains("R")); System.out.println("Size: "+hs.size()); hs.remove("E"); System.out.println("after removed 'E'"); System.out.println(hs); System.out.println("Size: "+hs.size()); } }Output:
java HashSetTest [B, 2, E] HashSet contains 'B':true HashSet contains 'R':false Size: 3 after removed 'E' [B, 2] Size: 2
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page