He determinado que Java ArrayList.addes similar a JavaScriptArray.push
Estoy atascado en la búsqueda de ArrayListfunciones similares a las siguientes
Array.popArray.shiftArray.unshiftMe estoy inclinando haciaArrayList.remove[At]
ArrayListes único en sus estándares de nombres. Aquí están las equivalencias:
Array.push -> ArrayList.add(Object o); // Append the list
Array.pop -> ArrayList.remove(int index); // Remove list[index]
Array.shift -> ArrayList.remove(0); // Remove first element
Array.unshift -> ArrayList.add(int index, Object o); // Prepend the list
Tenga en cuenta que unshiftno elimina un elemento, sino que agrega uno a la lista. También tenga en cuenta que es probable que los comportamientos de casos de esquina sean diferentes entre Java y JS, ya que cada uno tiene sus propios estándares.
.push?Array.push -> ArrayList.add, y le preguntó específicamente sobrepop,shiftyunshift. Al leer esto nuevamente, voy a agregar más explicación y agregar.pushal mismo tiempo.Me enfrenté a este problema hace algún tiempo y descubrí que
java.util.LinkedListes lo mejor para mi caso. Tiene varios métodos, con diferentes nombres, pero están haciendo lo que se necesita:push() -> LinkedList.addLast(); // Or just LinkedList.add(); pop() -> LinkedList.pollLast(); shift() -> LinkedList.pollFirst(); unshift() -> LinkedList.addFirst();fuente
LinkeListagrega métodos que serían muy ineficientes enArrayListlaListinterfaz, esto fue lo que me confundió. Estos métodos provienen de las interfacesDequeyQueueque implementa, peroArrayListno lo hace.tal vez quieras echar un vistazo a la
java.util.Stackclase. tiene métodos push, pop. e implementó la interfaz de lista.para shift / unshift, puede hacer referencia a la respuesta de @ Jon.
sin embargo, algo de ArrayList que puede interesarle, arrayList no está sincronizado. pero Stack lo es. (subclase de Vector). Si tiene un requisito de seguridad para subprocesos, Stack puede ser mejor que ArrayList.
fuente
Gran respuesta de Jon .
Sin embargo, soy vago y odio escribir, así que creé un ejemplo simple de cortar y pegar para todas las demás personas que son como yo. ¡Disfrutar!
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<String> animals = new ArrayList<>(); animals.add("Lion"); animals.add("Tiger"); animals.add("Cat"); animals.add("Dog"); System.out.println(animals); // [Lion, Tiger, Cat, Dog] // add() -> push(): Add items to the end of an array animals.add("Elephant"); System.out.println(animals); // [Lion, Tiger, Cat, Dog, Elephant] // remove() -> pop(): Remove an item from the end of an array animals.remove(animals.size() - 1); System.out.println(animals); // [Lion, Tiger, Cat, Dog] // add(0,"xyz") -> unshift(): Add items to the beginning of an array animals.add(0, "Penguin"); System.out.println(animals); // [Penguin, Lion, Tiger, Cat, Dog] // remove(0) -> shift(): Remove an item from the beginning of an array animals.remove(0); System.out.println(animals); // [Lion, Tiger, Cat, Dog] } }fuente
La biblioteca Underscore-java contiene los métodos push (valores), pop (), shift () y unshift (valores).
Ejemplo de código:
import com.github.underscore.U: List<String> strings = Arrays.asList("one", "two", " three"); List<String> newStrings = U.push(strings, "four", "five"); // ["one", " two", "three", " four", "five"] String newPopString = U.pop(strings).fst(); // " three" String newShiftString = U.shift(strings).fst(); // "one" List<String> newUnshiftStrings = U.unshift(strings, "four", "five"); // ["four", " five", "one", " two", "three"]fuente