Skip to content

Instantly share code, notes, and snippets.

@appkr
Last active September 14, 2020 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save appkr/ad2cd3693d4d6196d30d8a1ed6a76aed to your computer and use it in GitHub Desktop.
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.
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