説明させてください、私はあなたのコレクションを変更不可能にすることについて(信じられないほど)読んでいました、見てみましょうencapsulate collections、それは興味深いアイデアですが、実際の状況を想像することはできません。
誰かがそれの実用的なアプリケーションを説明できますか?
説明させてください、私はあなたのコレクションを変更不可能にすることについて(信じられないほど)読んでいました、見てみましょうencapsulate collections、それは興味深いアイデアですが、実際の状況を想像することはできません。
誰かがそれの実用的なアプリケーションを説明できますか?
外部からリストを変更するとカプセル化が壊れてしまうため、オブジェクトのプライベート メンバーであるリストを返す場合に非常に便利です。
たとえばobj.getList().clear();
、obj 内のリストをクリアします (getList() がプライベート メンバーを返すと仮定します) が、getList() が Collections.unmodifiableList に渡されたリストを返した場合、例外がスローされます。
これには 2 つの主な利点があります。
後者は、クラスのユーザーが独自の内部コレクションを変更できないようにする場合に役立ちます。
最近では、継承よりも構成を優先することも良い設計と見なされており、このパターンにうまく適合しています。
1の例:
class myComplicatedCollection<T> implements Collection<T> {
// Code goes here
// O no, I still have to deal with the read-only use-case.
// Instead of duplicating almost all of my code or using inheritance I'll use this handy-dandy wrapper
public Collection<T> readonlyVersion() {
return Collections.unmodifiableCollection(this);
}
}
2 の例:
class myClass {
private Collection<T> theData;
// Users need to access the data,
// but we don't want them modifying the private data of this class
public Collection<T> getTheData() {
return Collections.unmodifiableCollection(theData);
}
}
リストを安全に公開したり、不変性を強制したりしたい場合はいつでも使用してください。
例えば:
// neither the reference nor the contents can change
private static final List<String> codes = Collections.unmodifiableList(Arrays.asList("a", "b", "c"));
このリストはクラス内で変更できず、安全に公開できます。
// the caller can't change the list returned
public static List<String> getCodes() {
return codes;
}