@@ -66,6 +66,85 @@ Collections are used to perform the following operations:
66
66
---
67
67
68
68
### 8. Explain about Set and their types in a collection?
69
+ ** Set**
70
+ Set cares about uniqueness. It doesn’t allow duplicates. Here the “equals ( )” method is used to determine whether two objects are identical or not.
71
+
72
+ ** Hash Set:**
73
+ * Unordered and unsorted.
74
+ * Uses the hash code of the object to insert the values.
75
+ * Use this when the requirement is “no duplicates and don’t care about the order”.
76
+
77
+ Example:
78
+ ``` java
79
+ public class Fruit {
80
+ public static void main (String [] args ){
81
+ HashSet<String > names = new HashSet <=String >();
82
+ names. add(“banana”);
83
+ names. add(“cherry”);
84
+ names. add(“apple”);
85
+ names. add(“kiwi”);
86
+ names. add(“banana”);
87
+ System . out. println(names);
88
+ }
89
+ }
90
+ ```
91
+ Output:
92
+
93
+ [ banana, cherry, kiwi, apple]
94
+
95
+ Doesn’t follow any insertion order. Duplicates are not allowed.
96
+
97
+ ** Linked Hash set:**
98
+ * An ordered version of the hash set is known as Linked Hash Set.
99
+ * Maintains a doubly-Linked list of all the elements.
100
+ * Use this when the iteration order is required.
101
+
102
+ Example:
103
+ ``` java
104
+ public class Fruit {
105
+ public static void main (String [] args ){
106
+ LinkedHashSet<String > names = new LinkedHashSet <String >();
107
+ names. add(“banana”);
108
+ names. add(“cherry”);
109
+ names. add(“apple”);
110
+ names. add(“kiwi”);
111
+ names. add(“banana”);
112
+ System . out. println(names);
113
+ }
114
+ }
115
+ ```
116
+ Output:
117
+
118
+ [ banana, cherry, apple, kiwi]
119
+
120
+ Maintains the insertion order in which they have been added to the Set. Duplicates are not allowed.
121
+
122
+ ** Tree Set:**
123
+ * It is one of the two sorted collections.
124
+ * Uses “Read-Black” tree structure and guarantees that the elements will be in an ascending order.
125
+ * We can construct a tree set with the constructor by using comparable (or) comparator.
126
+
127
+ Example:
128
+ ``` java
129
+ public class Fruits {
130
+ public static void main (String [] args ) {
131
+ Treeset<String > names= new TreeSet<String > ();
132
+ names. add(“cherry”);
133
+ names. add(“banana”);
134
+ names. add(“apple”);
135
+ names. add(“kiwi”);
136
+ names. add(“cherry”);
137
+ System . out. println(names);
138
+ }
139
+ }
140
+ ```
141
+ Output:
142
+
143
+ [ apple, banana, cherry, kiwi]
144
+
145
+ TreeSet sorts the elements in an ascending order. And duplicates are not allowed.
146
+
147
+
69
148
---
70
149
71
150
### 9. What is the final keyword in Java?
0 commit comments