Skip to content

Instantly share code, notes, and snippets.

@Piasy
Created February 20, 2016 00:25
Show Gist options
  • Save Piasy/0ec6553bb96d8370f176 to your computer and use it in GitHub Desktop.
Save Piasy/0ec6553bb96d8370f176 to your computer and use it in GitHub Desktop.
Java Immutable Blog
List<Integer> list1 = new ArrayList<>();
list1.add(1);
List<Integer> list2 = new ArrayList<>(list1);
list1.add(2);
public class NonStrictlyImmutable {
private final List<Integer> mList = new ArrayList<>();
public List<Integer> getList() {
return mList;
}
}
List<Integer> list1 = new ArrayList<>();
list1.add(1);
List<Integer> list2 = list1;
list1.add(2);
public class StrictlyImmutable {
private final List<Integer> mList = new ArrayList<>();
public List<Integer> getList() {
// 以下两种方式都可以,各有优劣
// return new ArrayList<>(mList);
// return Collections.unmodifiableList(mList);
return Collections.unmodifiableList(mList);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment