Last active
September 14, 2020 06:05
-
-
Save appkr/ad2cd3693d4d6196d30d8a1ed6a76aed to your computer and use it in GitHub Desktop.
Is Java HashMap and ArrayList immutable? NOPE. The same is true for other languages.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package kata; | |
import org.junit.Test; | |
import java.util.*; | |
import static org.junit.Assert.*; | |
public class MutabilityTest { | |
@Test | |
public void isJavaMapImmutable() { | |
// NOPE | |
Map<String, String> source = new HashMap<>(); | |
source.put("foo", "bar"); | |
source.put("baz", "qux"); | |
Set<String> keys1 = source.keySet(); | |
Set<String> keys2 = source.keySet(); | |
source.remove("foo"); | |
assertTrue(1 == keys1.size()); | |
assertTrue(1 == source.size()); | |
} | |
@Test | |
public void isJavaListImmutable() { | |
// NOPE | |
ArrayList<String> source = new ArrayList<>(Arrays.asList("foo", "bar")); | |
String value = source.get(0); | |
System.out.println(value); // foo | |
source.set(0, "baz"); | |
assertEquals("baz", source.get(0)); | |
} | |
@Test | |
public void howToMapToBeImmutable() { | |
Map<String, String> source = new HashMap<>(); | |
source.put("foo", "bar"); | |
source.put("baz", "qux"); | |
// Defensive copy | |
Set<String> keys1 = new HashSet<>(source.keySet()); | |
source.remove("foo"); | |
assertTrue(2 == keys1.size()); | |
assertTrue( 1 == source.size()); | |
} | |
@Test | |
public void howToListToBeImmutable() { | |
ArrayList<String> source = new ArrayList<>(Arrays.asList("foo", "bar")); | |
// Defensive copy | |
String value = new String(source.get(0)); | |
source.set(0, "baz"); | |
assertEquals("baz", source.get(0)); | |
assertEquals("foo", value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read the article "Defensive Copying"
http://www.javapractices.com/topic/TopicAction.do?Id=15