text: Ads
  How can we used HashSet and TreeSet in the both Example?
  import java.util.HashSet; import java.util.Set; import java.util.TreeSet; public class SetsExample{ public static void main(String args[]){ Set<String> set1 = new HashSet<String>(); set1.add("B"); set1.add("A"); set1.add("C"); set1.add("A"); //A is a duplicate value System.out.println("Set is " + set1); set1.remove("C"); System.out.println("Set1 after removing c is " + set1); int size=set1.size(); System.out.println("Size of set1 after adding duplicate item is " + size); System.out.println("Is set1 contains a " + set1); System.out.println("Is set1 contains c " + set1.contains("C")); Set<String> set2 = new TreeSet<String>(); set2.add("E"); set2.add("F"); set2.add("G"); System.out.println("Set2 is " + set2); set2.addAll(set1); System.out.println("Set2 is after mergine set1 element " + set2); set2.removeAll(set1); System.out.println("Set is after deleting set1 element " + set2); set2.addAll(set1); set2.retainAll(set1); System.out.println("Set2 is after deleting all element except set1 element " + set2); } }
  Output:-
  Set is [A, B, C] Set1 after removing c is [A, B] Size of set1 after adding duplicate item is 2 Is set1 contains a [A, B] Is set1 contains c false Set2 is [E, F, G] Set2 is after mergine set1 element [A, B, E, F, G] Set is after deleting set1 element [E, F, G] Set2 is after deleting all element except set1 element [A, B]
  Description:- The above example demonstrates you the Set interface. Since Set is an interface, you need to instantiate a concrete implementation of the interface in order to use it. Here Set is implemented by its two subclasses HashSet and TreeSet. Now using the add() method, we have added elements to HashSet. Set does not accept duplicate values. So here we have checked whether the added elements are duplicate or not. Then we have removed one Element from the HashSet by using the method remove(). Now we have created another object by implementing Set-using TreeSet and add elements to the tree set. Using the addAll() method, we have added the elements of set1 to set2 and using the method removeAll(), we have removed all elements from set2.
  Ads
  Ads