xxxxxxxxxx
/*
* Template for using hash set to find duplicates.
*/
boolean findDuplicates(List<Type> keys) {
// Replace Type with actual type of your key
Set<Type> hashset = new HashSet<>();
for (Type key : keys) {
if (hashset.contains(key)) {
return true;
}
hashset.add(key);
}
return false;
}
xxxxxxxxxx
// Java program to demonstrate working of HashSet
import java.util.*;
class HashSetDemo {
// Main Method
public static void main(String[] args)
{
HashSet<String> h = new HashSet<String>();
// Adding elements into HashSet usind add()
h.add("India");
h.add("Australia");
h.add("South Africa");
h.add("India"); // adding duplicate elements
// Displaying the HashSet
System.out.println(h);
System.out.println("List contains India or not:"
+ h.contains("India"));
// Removing items from HashSet using remove()
h.remove("Australia");
System.out.println("List after removing Australia:"
+ h);
// Iterating over hash set items
System.out.println("Iterating over list:");
Iterator<String> i = h.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
xxxxxxxxxx
HashSet<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
if(set.contains(1)){
print("hashset contains 1");
}
else{
print("hashset doesn't contain 1");
}
//output
hashset contains 1
xxxxxxxxxx
- HashSet can have null, order is not guaranteed
- HashSet is commonly used if you want to access elements randomly or store a list of items which cannot contain duplicate values
xxxxxxxxxx
class MyHashSet {
private:
vector<bool> table;
public:
MyHashSet() : table(1e6 + 1, false) {}
void add(int key) {
table[key] = true;
}
void remove(int key) {
table[key] = false;
}
bool contains(int key) {
return table[key];
}
};