Merge pull request #6008 from MherBaghinyan/BAEL-2482

immutable sets
This commit is contained in:
Eric Martin 2019-01-02 21:10:41 -06:00 committed by GitHub
commit 829b11e1f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 56 additions and 0 deletions

View File

@ -0,0 +1,44 @@
package com.baeldung.java9.set;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class UnmodifiableSet {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Canada");
set.add("USA");
coreJDK(set);
guavaOf();
copyOf(set);
java9Of();
}
private static void java9Of() {
Set<String> immutable = Set.of("Canada", "USA");
System.out.println(immutable);
}
private static void guavaOf() {
Set<String> immutable = ImmutableSet.of("Canada", "USA");
System.out.println(immutable);
}
private static void copyOf(Set<String> set) {
Set<String> immutable = ImmutableSet.copyOf(set);
set.add("Costa Rica");
System.out.println(immutable);
}
private static void coreJDK(Set<String> set) {
Set<String> unmodifiableSet = Collections.unmodifiableSet(set);
set.add("Costa Rica");
System.out.println(unmodifiableSet);
}
}

View File

@ -1,5 +1,7 @@
package com.baeldung.java9;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
@ -23,4 +25,14 @@ public class SetExamplesUnitTest {
Set<Integer> intSet = Set.of(intArray);
assertEquals(intSet.size(), intArray.length);
}
@Test(expected = UnsupportedOperationException.class)
public void testUnmodifiableSet() {
Set<String> set = new HashSet<>();
set.add("Canada");
set.add("USA");
Set<String> unmodifiableSet = Collections.unmodifiableSet(set);
unmodifiableSet.add("Costa Rica");
}
}