JavaArrayList.add
はJavaScriptに似ていると判断しましたArray.push
私はArrayList
次のような関数を見つけることに固執しています
Array.pop
Array.shift
Array.unshift
私はに傾いていますArrayList.remove[At]
回答:
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
要素を削除するのでunshift
はなく、リストに追加することに注意してください。また、JavaとJSにはそれぞれ独自の標準があるため、コーナーケースの動作が異なる可能性があることにも注意してください。
.push
ですか?
Array.push -> ArrayList.add
、具体的には、について尋ねpop
、shift
とunshift
。これをもう一度読ん.push
で、説明を追加すると同時に追加します。
私はしばらく前にこの問題に直面していましたjava.util.LinkedList
が、私の場合に最適であることがわかりました。いくつかのメソッドがあり、名前が異なりますが、必要なことを実行しています。
push() -> LinkedList.addLast(); // Or just LinkedList.add();
pop() -> LinkedList.pollLast();
shift() -> LinkedList.pollFirst();
unshift() -> LinkedList.addFirst();
LinkeList
に非常に非効率的なメソッドを追加ArrayList
しList
ます。これが私を混乱させました。このメソッドは、それが実装するDeque
およびQueue
インターフェースから取得されますが、ArrayList
そうではありません。
多分あなたは見てjava.util.Stack
クラスを取りたいです。プッシュ、ポップメソッドがあります。リストインターフェイスを実装しました。
シフト/シフト解除については、@ 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]
}
}
アンダースコア-Javaライブラリには、メソッドpush(values)、pop()、shift()、およびunshift(values)が含まれています。
コード例:
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"]