Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Is Java HashMap and ArrayList immutable? NOPE. The same is true for other languages.
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);
}
}
@appkr
Copy link
Author

appkr commented Aug 14, 2019

Read the article "Defensive Copying"
http://www.javapractices.com/topic/TopicAction.do?Id=15

Both cases are valid design choices, but you must be aware of which one is appropriate for each case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment