HashSet
import java.util.HashSet;
// HashSet is an interface in java.
// if we want to remove an element which is not exist in set then we do not get any error.
// in set there is no concept of index , so we use for each loop.
// if any element is already present , then we can not add again , no error.
public class Basic{
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
// Insert O(1)
set.add(89);
set.add(10);
set.add(-987);
set.add(100);
// size O(1)
System.out.println(set.size());
//in set elements are stroe randomly
System.out.println(set);
// remove element O(1)
set.remove(10);
System.out.println(set);
// search - true/false O(1)
System.out.println(set.contains(89));
// convert set into array
Object[] arr = set.toArray();
for(Object ele : arr){
System.out.print(ele+" ");
}
// acess elements of set
for(int ele : set){
System.out.print(ele+" ");
}
// for remove all elements from set
set.clear();
System.out.println(set);
}
}
Comments
Post a Comment