BAEL-2682: Move java-immutable-set article to core-java-collections-set module (#9001)
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.set;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SetExamplesUnitTest {
|
||||
|
||||
@Test
|
||||
public void testUnmutableSet() {
|
||||
Set<String> strKeySet = Set.of("key1", "key2", "key3");
|
||||
try {
|
||||
strKeySet.add("newKey");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
}
|
||||
assertEquals(strKeySet.size(), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testArrayToSet() {
|
||||
Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
|
||||
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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user