Back to home

Push, pop, shift, unshift
Java Initialising Arrays main image

Java Initialising Arrays

Basic example on how to declare, declare with allocated size and initialise with default values:

1 2 3 int[] allocArr = new int[2]; // init with memory for 2 spaces int[] declareArr; // declaration int[] withValues = { n.data }; // shorthand init with values

Push, pop, shift, unshift

This requires the use of List and ArrayList

1 2 3 4 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

Example:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 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] } }

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.