java array shift code example

Example 1: shift elements in array java

// Shift right from index of 'a' to 'b'
for(int i = b; i>a; i--) { array[i] = array[i-1]; }
/* Note: element at 'a' index will remain unchanged */

// Shift left from index of 'b' to 'a' 
for(int i = a; i<b; i++) { array[i] = array[i+1]; }
/* Note: element at 'b' index will remain unchanged */

Example 2: es6 remove first element of array

var myarray = ["item 1", "item 2", "item 3", "item 4"];

//removes the first element of the array, and returns that element.
alert(myarray.shift());
//alerts "item 1"

//removes the last element of the array, and returns that element.
alert(myarray.pop());
//alerts "item 4"

Tags:

Java Example