File tree 2 files changed +56
-0
lines changed
main/java/com/baeldung/java9/set
test/java/com/baeldung/java9 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .baeldung .java9 .set ;
2
+
3
+ import com .google .common .collect .ImmutableSet ;
4
+
5
+ import java .util .Collections ;
6
+ import java .util .HashSet ;
7
+ import java .util .Set ;
8
+
9
+ public class UnmodifiableSet {
10
+
11
+ public static void main (String [] args ) {
12
+
13
+ Set <String > set = new HashSet <>();
14
+ set .add ("Canada" );
15
+ set .add ("USA" );
16
+
17
+ coreJDK (set );
18
+ guavaOf ();
19
+ copyOf (set );
20
+ java9Of ();
21
+ }
22
+
23
+ private static void java9Of () {
24
+ Set <String > immutable = Set .of ("Canada" , "USA" );
25
+ System .out .println (immutable );
26
+ }
27
+
28
+ private static void guavaOf () {
29
+ Set <String > immutable = ImmutableSet .of ("Canada" , "USA" );
30
+ System .out .println (immutable );
31
+ }
32
+
33
+ private static void copyOf (Set <String > set ) {
34
+ Set <String > immutable = ImmutableSet .copyOf (set );
35
+ set .add ("Costa Rica" );
36
+ System .out .println (immutable );
37
+ }
38
+
39
+ private static void coreJDK (Set <String > set ) {
40
+ Set <String > unmodifiableSet = Collections .unmodifiableSet (set );
41
+ set .add ("Costa Rica" );
42
+ System .out .println (unmodifiableSet );
43
+ }
44
+ }
Original file line number Diff line number Diff line change 1
1
package com .baeldung .java9 ;
2
2
3
+ import java .util .Collections ;
4
+ import java .util .HashSet ;
3
5
import java .util .Set ;
4
6
import org .junit .Test ;
5
7
@@ -23,4 +25,14 @@ public void testArrayToSet() {
23
25
Set <Integer > intSet = Set .of (intArray );
24
26
assertEquals (intSet .size (), intArray .length );
25
27
}
28
+
29
+ @ Test (expected = UnsupportedOperationException .class )
30
+ public void testUnmodifiableSet () {
31
+ Set <String > set = new HashSet <>();
32
+ set .add ("Canada" );
33
+ set .add ("USA" );
34
+
35
+ Set <String > unmodifiableSet = Collections .unmodifiableSet (set );
36
+ unmodifiableSet .add ("Costa Rica" );
37
+ }
26
38
}
You can’t perform that action at this time.
0 commit comments