ArrayListの内容全体をO(1)のArrayListの別のインスタンスに移動する方法はありますか?
つまり、バッキング配列への参照のみが1つのインスタンスから別のインスタンスに渡されます(要素は1つずつコピーされません)。
例えば:
ArrayList<String> a = new ArrayList<>(Arrays.asList("A", "B", "C"));
ArrayList<String> b = new ArrayList<>();
a.moveContentsTo(b);
// 'a' is now empty, while 'b' contains everything that 'a' did before and 'a != b'
// It is desired that the 'moveContentsTo' method is O(1)
さらに良いことに、ArrayList#swapContents(ArrayList)
方法はありますか?
詳細な説明とユースケース:
詳細な説明1:「a」と「b」の参照を交換してはなりません。私はtmp = a; a = b; b = tmp;
解決策の種類を探していません。
詳細な説明2:操作は時間内に〜O(1)でなければなりません。
ユースケース:これは、オブジェクトが外部で作成されたリストをカプセル化する場合に役立ちます。
public class A {
private ArrayList<String> items = new ArrayList<>();
/**
* This method takes the sole ownership of the contents. Whoever
* passed the list from the outside will not be able to modify
* contents of 'this.items' from outside the class.
*/
public AnImmutableObject(ArrayList<String> items) {
if (items != null) {
items.moveContentsTo(this.items);
}
}
/**
* Other collections that do not provide the 'move' functionality
* must be copied. If we just stored the reference to 'items' we
* would break encapsulation as whoever called the constructor
* still have write capabilities to the collection.
*/
public A(Collection<String> items) {
if (items != null) {
this.items.addAll(items);
}
}
public List<String> getItems() {
return Collections.unmodifiableList(items);
}
}
(速度を上げてメモリ使用量を減らすために)コピーを作成しないようにしたいことに注意してください。重要な点は、呼び出し先が(現在カプセル化されている)を変更する機能を失う必要があるということArrayList
です。