Java Arrays Tutorial

java data structursWhat are Java Arrays?

The Java language has primitive and reference data types. An Array is a reference data type with only one field (length). Java Arrays can not be copied by assigning one to another.

int[] arrayA = {1, 2, 3, 5};
int[] arrayB = a;

arrayB is an alias to the arrayA object above. Both of the references arrayA and arrayB refers to the same object. It will always return true when comparing them with double equal sign ‘==’.

int[] arrayA = {1,2,3};
int[] arrayB = {1,2,3};

arrayA and arrayB refer to different objects,even though the contents are the same. It will return false when we use double equal sign ‘==’ to compare.

Why & How do we use Java Arrays?

Use the Java APIs Arrays class with the equals method to compare arrays.

Java Arrays Class

Use java.util.Arrays convenience class to manipulate arrays (search, sort, print, comparison, …). This class is a set of static methods for working with arrays. It also includes methods for supporting operations over multidimensional arrays.The following code is an example of using this class’s equals method:

int[] arrayA = {3,4,5};
int[] arrayB = {3,4,5};
if( Arrays.equals(arrayA, arrayB) )
   System.out.println("arrayA and arrayB have identical contents");

Use toString() method to print array objects.

int[] arrayA = {1,2,3,4};
//will print out 1 2 3 4

Use sort() to sort contents of array:

int[] arrayA = {4,3,1,2};
//will print out 1 2 3 4

Copy Java Arrays

Examine the code in for more details. We have four ways to copy arrays:

  1. loop structure
  2. Arrays.copyOf()
  3. System.arraycopy()
  4. clone()

Copy Java Array with Loop

int[] arrayA = {1, 2, 3};
int[] arrayB = new int[arrayA.length];
for(int i = 0; i ‹ arrayA.length; i++) 
     arrayB[i] = arrayA[i];

Copy Java Array with copyOf()

int[] arrayA = {1, 2, 3};
int[] arrayB = Arrays.copyOf(arrayA, arrayA.length);

Copy Java Array with arraycopy()

This is the most efficient way to copy data between arrays. It requires five arguments. It copies length elements from a source array starting with the index srcIndex to a new array destination at the index destIndex. The signature is here and the code example follows.

public static void arraycopy(Object source,
                             int srcIndex,
                             Object destination,
                             int destIndex,
                             int length)
int[] arrayA = {1, 2, 3};
int[] arrayB = new int[arrayA.length];
System.arraycopy(arrayA, 0, arrayB, 0, 3)

Copy Java Array with clone()

Cloning creates a new array of the same size and type, then copying all the old elements into a new array. The clone() method is defined in the Object class. Casting (int[]) is required.

int[] arrayA = {1, 2, 3};
int[] arrayB = (int[]) arrayA.clone();

Java Array Insertion & Deletion

Java arrays have no methods and only one immutable field; length. An array’s length is fixed and cannot be changed after it’s created. To resize an array, allocate an array with a different size and copy the contents from the old array into the new array.Here is a code sample for deleting from an array of primitives. The first arraycopy copies elements from index 0 to index pos-1. The second arraycopy copies the elements from index pos+1 to data.length. Review the code from for more details.

public char[] delete(char[] data, int pos)
    if(pos >= 0 && pos < data.length)
        char[] tmp = new char[data.length-1];
        System.arraycopy(data, 0, tmp, 0, pos);
        System.arraycopy(data, pos+1, tmp, pos, data.length-pos-1);
        return tmp;
    } else {
      return data;

Java ArrayList Class

The java.util.ArrayList class supports an array that grows and shrinks on demand (dynamic array) to accomodate the number of elements in the array. Common methods include:

  • add(object)  adds to the end
  • add(index, object)  inserts at the index
  • set(index, object)  replaces at the index
  • get(index)  returns the element at that index
  • remove(index)  deletes the element at that index
  • siz()  returns the number of elements

Code example to show how some the methods are used:

ArrayList<Integer> number = new ArrayList<Integer>();
for(int i = 0; i < 10; i++) number.add(i);

//REMOVE even integers
for(int i = 0; i < number.size(); i++)
if(number.get(i)%2 == 0) number.remove(i);

Copy Java Arrays of Objects

Code example of a loop

Object[] object1 = {new Integer(10),
                new StringBuffer("foobar"),
                new Double(12.95)};
Object[] object2 = new Object[object1.length];
for(int i = 0; i ‹ object1.length; i++)
    object2[i] = object1[i];

The internal data is shared between two arrays (object1 and object2). The assignment (last line of code) creates an alias and not a copy. Review for details.

Multi-Dimensional Java Arrays

Multi-dimensional and two dimensional arrays are used in many applications. A two dimensional array can be viewed as a table of rows and columns. It creates a table of two rows and four columns:int[][] array2 = {{1,2},{3,4},{5,6}};A two dimensional array is not a table exactly, each row in the array has a different length:Object[][] object = {{new Integer(2), new Integer(2)},{new Integer(10), “snoopy”, new Double(1.95)}};

Cloning 2D Java Arrays

Cloning 2D arrays is almost the same as cloning as an array of references. The clone() method does not actually clone each row, it does create references to them. To change the value of obj[1][1] and create a shallow copy:

obj[1][1] = "abc";

To create a deeop copy, provide our own implementation by overriding Object’s clone() method. This makes a distinct copy of each of the object’s fields, recursively. A deep copy is a totally new object created from the original object.We don’t always need to create a deep copy. With immutable objects (can not be modified) we can let clients share the same instance without them interfering each other, so we don’t need to clone them.


Leave a Reply