我已经确定Java ArrayList.add类似于JavaScriptArray.push
我一直在寻找ArrayList类似于以下的功能
Array.popArray.shiftArray.unshift 我倾向于 ArrayList.remove[At]Jon*_*and 121
ArrayList在命名标准上是独一无二的.这是等价的:
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
Run Code Online (Sandbox Code Playgroud)
请注意,unshift不会删除元素,而是添加一个元素.另请注意,Java和JS之间的角落行为可能不同,因为它们各自都有自己的标准.
Wir*_*one 24
我不久前java.util.LinkedList遇到了这个问题,我发现最适合我的情况.它有几种方法,具有不同的命名,但它们正在做所需的事情:
push() -> LinkedList.addLast(); // Or just LinkedList.add();
pop() -> LinkedList.pollLast();
shift() -> LinkedList.pollFirst();
unshift() -> LinkedList.addFirst();
Run Code Online (Sandbox Code Playgroud)
Ken*_*ent 14
也许你想看看java.util.Stack课.它有push,pop方法.并实现了List接口.
对于班次/不合格,您可以参考@ Jon的答案.
但是,您可能想要关注的ArrayList,arrayList 不同步.但是堆栈是.(Vector的子类).如果您有线程安全的要求,Stack可能比ArrayList更好.
乔恩的回答很好。
我很懒,而且讨厌打字,所以我为所有像我一样的其他人创建了一个简单的剪切和粘贴示例。享受!
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]
}
}
Run Code Online (Sandbox Code Playgroud)