Created
March 24, 2015 18:13
-
-
Save eliocapelati/56efc5cd136636aabf77 to your computer and use it in GitHub Desktop.
Java way to get a truly immutable copy of a List.
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
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.List; | |
class App{ | |
public static void main(String[] args) throws Exception { | |
List<String> list = Arrays.asList("a", "b", "c"); | |
List<String> local = new ArrayList<String>(list); | |
List<String> unmodifiableList = Collections.unmodifiableList(local); | |
List<String> trulyUnmodifiableList = Collections.unmodifiableList(new ArrayList<String>(local)); | |
System.out.println("List => "+ list); | |
System.out.println("Local => "+ local); | |
System.out.println("Unmodifiable => "+ unmodifiableList ); | |
System.out.println("TrulyUnmodifiableList => "+ trulyUnmodifiableList ); | |
Collections.reverse(local); | |
System.out.println("List => "+list); | |
System.out.println("Local => "+local); | |
System.out.println("Unmodifiable => "+unmodifiableList ); | |
System.out.println("TrulyUnmodifiableList => "+ trulyUnmodifiableList ); | |
} | |
} |
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
List => [a, b, c] | |
Local => [a, b, c] | |
Unmodifiable => [a, b, c] | |
TrulyUnmodifiableList => [a, b, c] | |
List => [a, b, c] | |
Local => [c, b, a] | |
Unmodifiable => [c, b, a] | |
TrulyUnmodifiableList => [a, b, c] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment