java howto ArrayList push, pop, shift, and unshift

前端 未结 5 484
我在风中等你
我在风中等你 2020-12-12 17:19

I\'ve determined that a Java ArrayList.add is similar to a JavaScript Array.push

I\'m stuck on finding ArrayList functions sim

5条回答
  •  渐次进展
    2020-12-12 17:39

    Great Answer by Jon.

    I'm lazy though and I hate typing, so I created a simple cut and paste example for all the other people who are like me. Enjoy!

    import java.util.ArrayList;
    import java.util.List;
    
    public class Main {
    
        public static void main(String[] args) {
    
            List 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]
    
        }
    
    }
    

提交回复
热议问题