Skip to content

Instantly share code, notes, and snippets.

@eliocapelati
Created March 24, 2015 18:13
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 eliocapelati/56efc5cd136636aabf77 to your computer and use it in GitHub Desktop.
Save eliocapelati/56efc5cd136636aabf77 to your computer and use it in GitHub Desktop.
Java way to get a truly immutable copy of a List.
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 );
}
}
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