Hello Friends,
This is the Example for all the methods used in the java collections SET inteface, each method is implemented in the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
import java.util.HashSet; import java.util.Set; import java.util.Iterator; public class SetExample { public static void main(String args[]) { //initialization Set nameSet1 = new HashSet(); Set nameSet2 = new HashSet(); // add() method nameSet1.add("a"); nameSet1.add("b"); nameSet1.add("c"); nameSet2.add("a"); nameSet2.add("b"); nameSet2.add("c"); nameSet2.add("d"); //equals() method { //Checking Sets whether Identical or not if (nameSet2.equals(nameSet1) || nameSet1.containsAll(nameSet2)) System.out.println("The sets are identical"); else System.out.println("The sets are not identical"); } //addAll() method nameSet1.addAll(nameSet2); System.out.println("The contents of Set2 is added in Set1"); { //After adding, Checking Sets whether Identical or not if (nameSet2.equals(nameSet1) && nameSet1.containsAll(nameSet2)) System.out.println("The sets are identical"); else System.out.println("The sets are not identical"); } //size() method int size = nameSet1.size(); System.out.println("Size of Set1 is =" + size); //iterator() method Iterator it1 = (Iterator) nameSet1.iterator(); System.out.print("The elements in Set 1 are as-"); while (it1.hasNext()) { Object element1 = it1.next(); System.out.print(element1 + ", "); } // contains() method if (nameSet1.contains("a")) System.out.println("n" + "the set1 contains element a"); else System.out.println("the set1 doesnot contains element a"); //clear() method nameSet2.clear(); System.out.println("The Set 2 is cleared"); //hashcode() int hash = nameSet1.hashCode(); System.out.println("the hashCode od set1 is "+hash); //isEmpty() method if (nameSet2.isEmpty()) System.out.println("The Set 2 is empty"); else System.out.println("The Set 2 is not empty"); //toArray() method Object[] array = nameSet1.toArray(); int len = array.length; System.out.println("Length of array is " + len); for (int i = 0; i < len; i++) { System.out.println("value at index " + i + " is " + array[i]); } //remove() method nameSet1.remove("d"); System.out.print("The element d is removed from Set 1 and the remaining elements are as - "); Iterator it2 = (Iterator) nameSet1.iterator(); while (it2.hasNext()) { Object element = it2.next(); System.out.print(element + ", "); } } } |
Hope this will help you.
Thanks,
admin@code2java.com
I thank you hulmby for sharing your wisdom JJWY