¿Cómo mover los contenidos de un ArrayList a otro?
¿Hay alguna forma de mover todo el contenido de un ArrayList a otra instancia de ArrayList en O (1)?
Es decir: solo la referencia a la matriz de respaldo se pasa de una instancia a la otra (los elementos no se copian uno por uno).
Por ejemplo:
<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>
Aún mejor, ¿hay unArrayList#swapContents(ArrayList)
¿método?
Explicación adicional y caso de uso.:
Explicación adicional 1: las referencias de 'a' y 'b' no deben intercambiarse. No estoy buscandotmp = a; a = b; b = tmp;
Tipo de soluciones.
Explicación adicional 2: La operación debe ser ~ O (1) en el tiempo.
El caso de uso: Esto es útil cuando un objeto quiere encapsular una lista construida fuera:
<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>
Tenga en cuenta que queremos evitar hacer una copia (para aumentar la velocidad y disminuir el uso de la memoria). El bit crucial es que la persona que llama debe perder la capacidad de modificar el (ahora encapsulado)ArrayList
.