Jak przenieść zawartość jednej tablicy ArrayList do innej?

Czy istnieje sposób na przeniesienie całej zawartości ArrayList do innej instancji ArrayList w O (1)?

To znaczy: tylko odniesienie do tablicy bazowej jest przekazywane z jednej instancji do drugiej (elementy nie są kopiowane jeden po drugim).

Na przykład:

<code>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)
</code>

Jeszcze lepiej, czy istniejeArrayList#swapContents(ArrayList) metoda?

Dalsze wyjaśnienia i przypadek użycia:

Dalsze wyjaśnienia 1: odniesienia „a” i „b” nie mogą być wymieniane. Nie szukamtmp = a; a = b; b = tmp; rodzaj rozwiązań.

Dalsze wyjaśnienia 2: Operacja musi być ~ O (1) w czasie.

Obudowa użytkowa: Jest to przydatne, gdy obiekt chce enkapsulować listę zbudowaną na zewnątrz:

<code>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);
    }
}
</code>

Zauważ, że chcemy uniknąć tworzenia kopii (aby zwiększyć prędkość i zmniejszyć zużycie pamięci). Kluczowe jest to, że callee musi utracić możliwość modyfikowania (teraz hermetyzowanego)ArrayList.

questionAnswers(3)

yourAnswerToTheQuestion