Java Language


Arrays Java SE 1.0–Java SE 9 (Early Access)

Java SE 1.0
Java SE 1.1
Java SE 1.2
Java SE 1.3
Java SE 1.4
Java SE 5
Java SE 6
Java SE 7
Java SE 8
Java SE 9 (Early Access)

This draft deletes the entire topic.

inline side-by-side expand all collapse all

Examples

  • Improvements requested by Menasheh:

    • This example does not sufficiently illustrate the point and needs to be edited to provide more details. - 3h ago
      Comments:
      • What does "standard way" mean? Is there a different way to word that? - Menasheh
    379

    Java offers several ways of defining and initializing arrays, including literal and constructor notation. When declaring arrays without explicit values, the contents will be initialized with default values:

    The size of an array is fixed - it cannot be changed after initialization. If you do not know the size at initialization time, you may want to use another Collection class such as ArrayList.

    There are several ways to create and initialize an array of primitive types:

    int[] arr1 = new int[] { 1, 2, 3 }; // create an array with new operator and array initializer
    int[] arr2 = { 1, 2, 3 };           // shortcut syntax with array initializer
    int[] arr3 = new int[0];            // 0-length array
    int[] arr4 = new int[3];            // { 0, 0, 0 }
    int[] arn0 = null;                  // null
    

    When declaring an array, [], may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.

    int arr4[];         /* equivalent to */  int[] arr4;
    int a, b[], c[][];  /* equivalent to */  int a; int[] b; int[][] c;
    int[] a, b[];       /* equivalent to */  int[] a; int[][] b;
    

    Although both are correct, and compile and run without any problems, the Java Coding Convention discourages this form; the brackets identify the array type and should appear with the type designation.1

    The same methods for arrays of reference types are:

    String[] arr5 = new String[] { "Laurel", "Hardy" }; // create an array with new operator and array initializer
    String[] arr6 = { "Laurel", "Hardy" };              // shortcut syntax with array initializer
    String[] arr7 = new String[0];                      // 0-length array
    String[] arr8 = new String[3];                      // { null, null, null }
    String[] arn1 = null;                               // null
    

    In both primitive and reference types, an empty array initialization (for example String[] arr8 = new String[3];) will initialize the array with the default value for each data type.

    Arrays.fill() method can be used to fill an array with the same value after the array is initialized:

    Arrays.fill(arr8, "abc");        // { "abc", "abc", "abc" }
    

    An array can be declared, initialized, and filled with values in separate steps:

    int[] arr9;             // array declaration - uninitialized
    arr9 = new int[3];      // initialize array  - { 0, 0, 0 }
    arr9[0] = 10;           // set index 0 value - { 10, 0, 0 }
    arr9[1] = 20;           // set index 1 value - { 10, 20, 0 }
    arr9[2] = 30;           // set index 2 value - { 10, 20, 30 }
    

    The value of an index for an array element needs to be a non-negative integer (0, 1, 2, 3, 4, ...) and less than the length of the array (indexes are zero-based); otherwise an ArrayIndexOutOfBoundsException will be thrown.

    It's not necessary for all of the array elements to share the same type, so long as they are a subclass of the array's type:

    interface I {}
    
    class A implements I {}
    class B implements I {}
    class C implements I {}
    
    I[] arr10 = new I[] { new A(), new B(), new C() }; // create an array with new operator and array initializer
    I[] arr11 = { new A(), new B(), new C() };         // shortcut syntax with array initializer
    I[] arr12 = new I[3];                              // { null, null, null }
    
    I[] arr13 = new A[] { new A(), new A() }; // works because A implements I
    
    Object[] arr14 = new Object[] { "Hello, World!", 3.14159, 42 }; // create an array with new operator and array initializer
    Object[] arr15 = { new A(), 64, "My String" };                  // shortcut syntax with array initializer
    

    Note that it is not possible to re-initialize an array via a shortcut syntax with array initializer since an array initializer can only be specified in a a field declaration or local variable declaration, or as a part of an array creation expression. To re-initialize an array, a new operator can be used with array initializer:

    int[] arr = new int[] { 1, 2, 3 };
    
    // prints "1 2 3 "
    for (int i : arr)
        System.out.print(i + " ");
    
    // re-initializes arr to a new int[] array
    arr = new int[] { 4, 5, 6 };
    
    // prints "4 5 6 "
    for (int i : arr) 
        System.out.print(i + " ");
    
    arr = { 1, 2, 3, 4 }; // Error! Can't re-initialize an array via shortcut syntax with array initializer
    

    When arr is assigned to a new int[] array, the memory allocated for the previous int[] array may be reclaimed by the Garbage Collector.

  • 106

    java.util.Arrays provides Arrays.sort() to sort arrays. Here are a few examples:

    Sort an array

    Java SE 1.2
    int[] array = {4, 1, 3, 2};
    Arrays.sort(array);
    System.out.print(Arrays.toString(array));
    

    Output:

    [1, 2, 3, 4]

    Partially sort

    You can partially sort an array by passing two additional parameters to the sort() method:

    1. The index to begin sorting from (inclusive).
    2. The index to end sorting at (exclusive).

    For example, to sort only the first three numbers of an array, pass start index as 0 and end index as 3. Remember that the end index is exclusive, and will not be included:

    Java SE 1.2
    int[] array = {4, 1, 3, 2};
    Arrays.sort(array, 0, 3); // 0 is inclusive, 3 is exclusive
    System.out.println(Arrays.toString(array));
    
    //> [1, 3, 4, 2]
    

    Custom sort

    The Arrays.sort() method can also take a Comparator as a parameter, which allows you to define a custom sorting method, or use a different, predefined one:

    Predefined Comparator

    It is possible to use a predefined static method Collections.reverseOrder():

    Java SE 1.2
    String[] array = { "aaaa", "bbbb", "cccc", "dddd" };
    Arrays.sort(array, Collections.reverseOrder());
    System.out.println(Arrays.toString(array));
    
    //> dddd cccc bbbb aaaa
    

    Custom Comparator

    It is also possible to define a custom Comparator inline, via anonymous classes. For this case the compare() method should be overridden with arguments of the correct type (here we use String):

    Java SE 1.2
    String[] array = { "bbbb", "dddd", "aaaa", "cccc" };
    
    Arrays.sort(array, new Comparator<String>() {
         @Override
         public int compare(String string1, String string2) {
              return string1.compareTo(string2);
         }
    });
    
    System.out.println(Arrays.toString(array));
    
    //> aaaa bbbb cccc dddd
    

    The anonymous class above can be also shortened from Java SE 8:

    Java SE 8
    Arrays.sort(array, (string1, string2) -> string1.compareTo(string2));
    

    You can use the Comparator.comparing() which was introduced by Java SE 8 to create a comparator:

    Java SE 8
    String[] array = { "bb", "dddd", "a", "ccc" };
    
    Arrays.sort(array, Comparator.comparing(String::length)); 
    //> [a, bb, ccc, dddd]
    

    Any object can be sorted with this API as long as it implements Comparable, or a custom Comparator is provided.


    An alternative to the Arrays.sort() method is to implement your own sorting algorithm. One of the most popular algorithms is bubble sort:

    public static void bubbleSort(int[] numArray) {
        int n = numArray.length;
        int temp = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 1; j < (n - i); j++) {
                if (numArray[j - 1] > numArray[j]) {
                    temp = numArray[j - 1];
                    numArray[j - 1] = numArray[j];
                    numArray[j] = temp;
                }
            }
        }
    }
    

    An element can be searched using Collections.binarySearch() if the array is sorted. If an element is present, its index should be provided; otherwise the returned result will be a negative value.

    int[] array = {1,2,3};
    int key = 2;
    int index = Arrays.binarySearch(array, key); // returns index of the search key
    System.out.println(index);
    //> 1
    

    Notes:

    Java SE 7

    The algorithm used by sort() for sorting primitive types is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm executes in O(n log(n)) time even on most of the datasets that cause the classical One-Pivot Quicksort to degrade to quadratic time. The implementation of sort(Object[] a) was adapted from Tim Peters's list sort for Python (TimSort).

    Java SE 6

    For sorting primitive types Java SE 6 uses a tuned quicksort, adapted from Jon Bentley and M. Douglas McIlroy's "Engineering a Sort Function". For sorting objects, a modified mergesort is used.

  • 66

    The Arrays.asList method can create a List from an Array. The resulting list will be of the same type as the array.

    String[] stringArray = new String[]{"foo", "bar", "baz"};
    List<String> stringList = Arrays.asList(stringArray);

    Note that Java also provides java.util.Collections to create a List from an Array:

    Java SE 5
    String[] stringArray = new String[]{"foo", "bar", "baz"};
    List<String> stringList = new ArrayList<String>(stringArray.length);
    Collections.addAll(stringList, stringArray);
    
    Java SE 7

    In Java SE 7 and later, pair of angle brackets, <> can be used, which is called the diamond. The compiler can determine, or infer, the type arguments from the context.

    String[] stringArray = new String[]{"foo", "bar", "baz"};
    List<String> stringList = new ArrayList<>(stringArray.length);
    Collections.addAll(stringList, stringArray);
    

    Important Notes related to using of Arrays.asList method

    • Changes to the List affect the array, and vice-versa:

      String[] stringArray = new String{"very", "related", "strings"};
      List<String> stringList = Arrays.asList(stringArray);
      
      System.out.println(stringArray[0]); // "very"
      stringList.set(0, "boo");
      System.out.println(stringArray[0]); // "boo"
      
      System.out.println(stringArray[2]); // "strings"
      stringArray[2] = "faz";
      System.out.println(stringList.get(2)); // "faz"
      
    • The resulting List will be fixed-size, i.e., adding or removing elements is not supported and will result in an exception:

      stringList.add("something"); // throws java.lang.UnsupportedOperationException
      
    • Modifiable List can be created by passing the unmodifiable List to the constructor of a new one. This creates a new copy of the data, which will then be modifiable:

      List<String> modifiableList = new ArrayList<>(Arrays.asList("foo", "bar"));
      
    • Calling <T> List<T> asList(T... a) on a primitive array, such as an int[], will produce a List whose only element is the source primitive array instead of the actual elements of the source array.

      The reason for that behavior is that primitive types can't be used in place of generic type parameters, so the entire primitive array replaces the generic type parameter in this case. In order to convert a primitive array to a List, first convert the primitive array to an array of the corresponding wrapper type (i.e. call Arrays.asList on an Integer[] instead of an int[]). Therefore:

      int[] arr = {1, 2, 3};
      System.out.println(Arrays.asList(arr).contains(1));
      

      will print false, while on the other hand:

      Integer[] arr = {1, 2, 3};
      System.out.println(Arrays.asList(arr).contains(1));
      

      will print true.


    Using java 8:

    Java SE 8
    int[] ints = {1, 2, 3};
    List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
    

I am downvoting this example because it is...

Syntax

  • ArrayType[] variableName; // Declaring arrays
  • ArrayType variableName[]; // Another valid syntax (less commonly used)
  • ArrayType[][][] variableName; // Declaring multi-dimensional ragged arrays (repeat []'s)
  • array[index] = value; // Assignment to index of arrays; elements are similarly accessed
  • ArrayType[] myArray = new ArrayType[arrayLength]; // Array initialization syntax
  • int[] ints = {1, 2, 3}; // Array initialization syntax with values provided, length is inferred from the number of provided values: {[value1[, value2]*]}
  • int[] ints = int[3]; // same as {0, 0, 0}
  • int[][] ints = {{1, 2}, {3}, null}; // Multi-dimensional array initialization. int[] is Object (and so is anyType[]) so null is a valid value.

Parameters

Parameters

Remarks

Remarks

Still have a Arrays question? Ask Question

Creating and Initializing Arrays

379

Java offers several ways of defining and initializing arrays, including literal and constructor notation. When declaring arrays without explicit values, the contents will be initialized with default values:

The size of an array is fixed - it cannot be changed after initialization. If you do not know the size at initialization time, you may want to use another Collection class such as ArrayList.

There are several ways to create and initialize an array of primitive types:

int[] arr1 = new int[] { 1, 2, 3 }; // create an array with new operator and array initializer
int[] arr2 = { 1, 2, 3 };           // shortcut syntax with array initializer
int[] arr3 = new int[0];            // 0-length array
int[] arr4 = new int[3];            // { 0, 0, 0 }
int[] arn0 = null;                  // null

When declaring an array, [], may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.

int arr4[];         /* equivalent to */  int[] arr4;
int a, b[], c[][];  /* equivalent to */  int a; int[] b; int[][] c;
int[] a, b[];       /* equivalent to */  int[] a; int[][] b;

Although both are correct, and compile and run without any problems, the Java Coding Convention discourages this form; the brackets identify the array type and should appear with the type designation.1

The same methods for arrays of reference types are:

String[] arr5 = new String[] { "Laurel", "Hardy" }; // create an array with new operator and array initializer
String[] arr6 = { "Laurel", "Hardy" };              // shortcut syntax with array initializer
String[] arr7 = new String[0];                      // 0-length array
String[] arr8 = new String[3];                      // { null, null, null }
String[] arn1 = null;                               // null

In both primitive and reference types, an empty array initialization (for example String[] arr8 = new String[3];) will initialize the array with the default value for each data type.

Arrays.fill() method can be used to fill an array with the same value after the array is initialized:

Arrays.fill(arr8, "abc");        // { "abc", "abc", "abc" }

An array can be declared, initialized, and filled with values in separate steps:

int[] arr9;             // array declaration - uninitialized
arr9 = new int[3];      // initialize array  - { 0, 0, 0 }
arr9[0] = 10;           // set index 0 value - { 10, 0, 0 }
arr9[1] = 20;           // set index 1 value - { 10, 20, 0 }
arr9[2] = 30;           // set index 2 value - { 10, 20, 30 }

The value of an index for an array element needs to be a non-negative integer (0, 1, 2, 3, 4, ...) and less than the length of the array (indexes are zero-based); otherwise an ArrayIndexOutOfBoundsException will be thrown.

It's not necessary for all of the array elements to share the same type, so long as they are a subclass of the array's type:

interface I {}

class A implements I {}
class B implements I {}
class C implements I {}

I[] arr10 = new I[] { new A(), new B(), new C() }; // create an array with new operator and array initializer
I[] arr11 = { new A(), new B(), new C() };         // shortcut syntax with array initializer
I[] arr12 = new I[3];                              // { null, null, null }

I[] arr13 = new A[] { new A(), new A() }; // works because A implements I

Object[] arr14 = new Object[] { "Hello, World!", 3.14159, 42 }; // create an array with new operator and array initializer
Object[] arr15 = { new A(), 64, "My String" };                  // shortcut syntax with array initializer

Note that it is not possible to re-initialize an array via a shortcut syntax with array initializer since an array initializer can only be specified in a a field declaration or local variable declaration, or as a part of an array creation expression. To re-initialize an array, a new operator can be used with array initializer:

int[] arr = new int[] { 1, 2, 3 };

// prints "1 2 3 "
for (int i : arr)
    System.out.print(i + " ");

// re-initializes arr to a new int[] array
arr = new int[] { 4, 5, 6 };

// prints "4 5 6 "
for (int i : arr) 
    System.out.print(i + " ");

arr = { 1, 2, 3, 4 }; // Error! Can't re-initialize an array via shortcut syntax with array initializer

When arr is assigned to a new int[] array, the memory allocated for the previous int[] array may be reclaimed by the Garbage Collector.

Sorting Arrays

106

java.util.Arrays provides Arrays.sort() to sort arrays. Here are a few examples:

Sort an array

Java SE 1.2
int[] array = {4, 1, 3, 2};
Arrays.sort(array);
System.out.print(Arrays.toString(array));

Output:

[1, 2, 3, 4]

Partially sort

You can partially sort an array by passing two additional parameters to the sort() method:

  1. The index to begin sorting from (inclusive).
  2. The index to end sorting at (exclusive).

For example, to sort only the first three numbers of an array, pass start index as 0 and end index as 3. Remember that the end index is exclusive, and will not be included:

Java SE 1.2
int[] array = {4, 1, 3, 2};
Arrays.sort(array, 0, 3); // 0 is inclusive, 3 is exclusive
System.out.println(Arrays.toString(array));

//> [1, 3, 4, 2]

Custom sort

The Arrays.sort() method can also take a Comparator as a parameter, which allows you to define a custom sorting method, or use a different, predefined one:

Predefined Comparator

It is possible to use a predefined static method Collections.reverseOrder():

Java SE 1.2
String[] array = { "aaaa", "bbbb", "cccc", "dddd" };
Arrays.sort(array, Collections.reverseOrder());
System.out.println(Arrays.toString(array));

//> dddd cccc bbbb aaaa

Custom Comparator

It is also possible to define a custom Comparator inline, via anonymous classes. For this case the compare() method should be overridden with arguments of the correct type (here we use String):

Java SE 1.2
String[] array = { "bbbb", "dddd", "aaaa", "cccc" };

Arrays.sort(array, new Comparator<String>() {
     @Override
     public int compare(String string1, String string2) {
          return string1.compareTo(string2);
     }
});

System.out.println(Arrays.toString(array));

//> aaaa bbbb cccc dddd

The anonymous class above can be also shortened from Java SE 8:

Java SE 8
Arrays.sort(array, (string1, string2) -> string1.compareTo(string2));

You can use the Comparator.comparing() which was introduced by Java SE 8 to create a comparator:

Java SE 8
String[] array = { "bb", "dddd", "a", "ccc" };

Arrays.sort(array, Comparator.comparing(String::length)); 
//> [a, bb, ccc, dddd]

Any object can be sorted with this API as long as it implements Comparable, or a custom Comparator is provided.


An alternative to the Arrays.sort() method is to implement your own sorting algorithm. One of the most popular algorithms is bubble sort:

public static void bubbleSort(int[] numArray) {
    int n = numArray.length;
    int temp = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {
            if (numArray[j - 1] > numArray[j]) {
                temp = numArray[j - 1];
                numArray[j - 1] = numArray[j];
                numArray[j] = temp;
            }
        }
    }
}

An element can be searched using Collections.binarySearch() if the array is sorted. If an element is present, its index should be provided; otherwise the returned result will be a negative value.

int[] array = {1,2,3};
int key = 2;
int index = Arrays.binarySearch(array, key); // returns index of the search key
System.out.println(index);
//> 1

Notes:

Java SE 7

The algorithm used by sort() for sorting primitive types is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm executes in O(n log(n)) time even on most of the datasets that cause the classical One-Pivot Quicksort to degrade to quadratic time. The implementation of sort(Object[] a) was adapted from Tim Peters's list sort for Python (TimSort).

Java SE 6

For sorting primitive types Java SE 6 uses a tuned quicksort, adapted from Jon Bentley and M. Douglas McIlroy's "Engineering a Sort Function". For sorting objects, a modified mergesort is used.

Creating a List from an Array

66

The Arrays.asList method can create a List from an Array. The resulting list will be of the same type as the array.

String[] stringArray = new String[]{"foo", "bar", "baz"};
List<String> stringList = Arrays.asList(stringArray);

Note that Java also provides java.util.Collections to create a List from an Array:

Java SE 5
String[] stringArray = new String[]{"foo", "bar", "baz"};
List<String> stringList = new ArrayList<String>(stringArray.length);
Collections.addAll(stringList, stringArray);
Java SE 7

In Java SE 7 and later, pair of angle brackets, <> can be used, which is called the diamond. The compiler can determine, or infer, the type arguments from the context.

String[] stringArray = new String[]{"foo", "bar", "baz"};
List<String> stringList = new ArrayList<>(stringArray.length);
Collections.addAll(stringList, stringArray);

Important Notes related to using of Arrays.asList method

  • Changes to the List affect the array, and vice-versa:

    String[] stringArray = new String{"very", "related", "strings"};
    List<String> stringList = Arrays.asList(stringArray);
    
    System.out.println(stringArray[0]); // "very"
    stringList.set(0, "boo");
    System.out.println(stringArray[0]); // "boo"
    
    System.out.println(stringArray[2]); // "strings"
    stringArray[2] = "faz";
    System.out.println(stringList.get(2)); // "faz"
    
  • The resulting List will be fixed-size, i.e., adding or removing elements is not supported and will result in an exception:

    stringList.add("something"); // throws java.lang.UnsupportedOperationException
    
  • Modifiable List can be created by passing the unmodifiable List to the constructor of a new one. This creates a new copy of the data, which will then be modifiable:

    List<String> modifiableList = new ArrayList<>(Arrays.asList("foo", "bar"));
    
  • Calling <T> List<T> asList(T... a) on a primitive array, such as an int[], will produce a List whose only element is the source primitive array instead of the actual elements of the source array.

    The reason for that behavior is that primitive types can't be used in place of generic type parameters, so the entire primitive array replaces the generic type parameter in this case. In order to convert a primitive array to a List, first convert the primitive array to an array of the corresponding wrapper type (i.e. call Arrays.asList on an Integer[] instead of an int[]). Therefore:

    int[] arr = {1, 2, 3};
    System.out.println(Arrays.asList(arr).contains(1));
    

    will print false, while on the other hand:

    Integer[] arr = {1, 2, 3};
    System.out.println(Arrays.asList(arr).contains(1));
    

    will print true.


Using java 8:

Java SE 8
int[] ints = {1, 2, 3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());

Creating an Array from a Collection

20

There are two methods of creating an array from a collection, namely:

public interface Collection<E> extends Iterable<E> {
   /**
     * Returns an array containing all of the elements in this collection.
     * ...
     * @return an array containing all of the elements in this collection
     */
    Object[] toArray();

   ....

   /**
     * Returns an array containing all of the elements in this collection;
     * the runtime type of the returned array is that of the specified array.
     * If the collection fits in the specified array, it is returned therein.
     * Otherwise, a new array is allocated with the runtime type of the
     * specified array and the size of this collection.
     * If this collection fits in the specified array with room to spare
     * (i.e., the array has more elements than this collection), the element
     * in the array immediately following the end of the collection is set to
     * null.  (This is useful in determining the length of this
     * collection only if the caller knows that this collection does
     * not contain any null elements.)
     * ...
     * @param <T> the runtime type of the array to contain the collection
     * @param a the array into which the elements of this collection are to be
     *        stored, if it is big enough; otherwise, a new array of the same
     *        runtime type is allocated for this purpose.
     * @return an array containing all of the elements in this collection
     * @throws ArrayStoreException if the runtime type of the specified array
     *         is not a supertype of the runtime type of every element in
     *         this collection
     * @throws NullPointerException if the specified array is null
     */
    <T> T[] toArray(T[] a);
}

They can be used as follows:

Set<Integer> set = new HashSet<>();
set.add(0);
set.add(1);

/**
 * Note that the array does not need to be created up front with the correct size.
 */
Integer[] integerArray = set.toArray(new Integer[0]);  

List<String> list = new ArrayList<String>();
list.add("android");
list.add("apple");

String[] stringArray = list.toArray(new String[list.size()]);

The difference between them is more than just having untyped vs typed results. Their performance odds too:

  • Object[] toArray() uses vectorized arraycopy which is much faster than the type-checked arraycopy in T[] toArray(T[] a)
  • T[] toArray(new T[non-zero-size]) needs to zero the array, while T[] toArray(new T[0]) does not. Such avoidance makes the latter call faster than the former.

An alternative of converting ArrayList to Array is to use Arrays.copyOf method:

ArrayList<String> arrayList = new ArrayList<String>();
Object[] objectList = arrayList.toArray();
String[] stringArray =  Arrays.copyOf(objectList,objectList.length,String[].class);

From Java 8 on you can also use

Java SE 8
String[] strings = list.stream().toArray(String[]::new);

Examples taken from this and this answers to a question "Converting 'ArrayList to 'String[]'" on Stack Overflow.

Multidimensional and Jagged Arrays

13

It is possible to define an array with more than one dimension; instead of accessing them linearly, one can access them as a set of row and column pairs.

To do this, we repeat the declaration of an array; if we wanted to make a 2-dimensional int array, we would add another set of brackets to our declaration (such as int[][]). This continues for 3-dimensional arrays (int[][][]) and so forth.

Below, we define a 2-dimensional array with three rows and three columns.

int rows = 3;
int columns = 3;
int[][] table = new int[rows][columns];

With this construct, we can index into the array and assign values.

table[0][0] = 0;
table[0][1] = 1;
table[0][2] = 2;

Less commonly, you can also instantiate one dimension at a time, and even make non-rectangular arrays. These are more commonly referred to as jagged arrays.

int[][] nonRect = new int[4][];

It is important to note that you can define any dimension of jagged array; however, its preceding level must be defined.

// valid
String[][] employeeGraph = new String[30][];

// invalid
int[][] unshapenMatrix = new int[][10];

// also invalid
int[][][] misshapenGrid = new int[100][][10];

Multidimensional arrays can also be initialized with a literal expression. The following declares and populates a 2x3 int array:

int[][] table = {
    {1, 2, 3},
    {4, 5, 6}
};

ArrayIndexOutOfBoundsException

7

The ArrayIndexOutOfBoundsException is thrown when attempting to access an index of the array that doesn't exist.

Remember that the smallest array index is 0 and the largest is 1 less than the number of elements in the array. Thus, any request to an array, like array[i], where i < 0 || i > array.length - 1 will throw an ArrayIndexOutOfBoundsException.

The following code is a simple example where an ArrayIndexOutOfBoundsException is thrown.

String[] people = new String[] { "Carol", "Andy" };
System.out.println(people[2]);  //throws an ArrayIndexOutOfBoundsException.

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at your.package.path.method(YourClass.java:15)

To avoid this, simply check that the index is within the limits of the array:

int index = 2;
if (index >= 0 && index < people.length) {
    System.out.println(people[index]);
} 

Arrays to a String

6

Arrays and multi-dimensional arrays:

int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));          // [1, 2, 3, 4, 5]

int[][] arr = { {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9} };
System.out.println(Arrays.deepToString(arr));      // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Since Arrays.toString() method uses Object.toString() method to produce String values of every item in the array, beside primitive type array, it can be used for all type of arrays. For instance:

public class Cat { /* implicitly extends Object */
    @Override
    public String toString() {
      return "CAT!";
    }
}

Cat[] arr = { new Cat(), new Cat() };
System.out.println(Arrays.toString(arr));            // [CAT!, CAT!]

If no overridden toString() exists for the class, then the inherited toString() from Object will be used. Usually the output is then not very useful, for example:

public class Dog { /* implicitly extends Object */
}

Dog[] arr = { new Dog() };
System.out.println(Arrays.toString(arr));            // [Dog@17ed40e0]

Arrays to Stream

6

Convert array of objects to Stream

String[] arr = new String[]{"str1", "str2", "str3"};
Stream<String> stream = Arrays.stream(arr);

Convert array of primitives to Stream using Arrays.stream will transform array to primitive specialization of Stream.

int[] intArr = new int[]{1, 2, 3};
IntStream intStream = Arrays.stream(intArr);

You can also limit the Stream to a range of elements in the array, the start index is inclusive and the end index is exclusive:

int[] values = { 1, 2, 3, 4 };
IntStream intStream = Arrays.stream(values, 2, 4);

A similar method to Arrays.stream() appears in the Stream class, Stream.of(). The difference is that Stream.of() uses a varargs parameter, so you can write something like:

Stream<Integer> intStream = Stream.of(1, 2, 3);
Stream<String> stringStream = Stream.of("1", "2", "3");
Stream<Double> doubleStream = Stream.of(new Double[]{1.0, 2.0});

Accessing Contents of an Array

5

The content in an array is referenced by its index, starting from 0.

int[] primes = { 2, 3, 5, 7 };
int firstPrime  = primes[0]; //retrieves the first item from the array. now firstPrime contains int value 2
int secondPrime = primes[1]; //retrieves the second item from the array. now secondPrime contains int value 3

You can access the content iterating it in a C-Style for-loop :

for (int i = 0; i < primes.length; i++) {
    int currenVal = primes[i];
}

Or for-each loop using auto-created iterator:

for (int prime : primes) {
    int currentVal = prime;
}

Iterating over arrays

5

You can iterate over arrays either by using extended for (aka foreach) or by using array indices:

int[] array = new int[10];

//using indices: read and write
for( int i = 0; i < array.length; i++ ) {
  array[i] = i;
}

//extended for: read only
for( int e : array ) {
  System.out.println( e );
}

It is worth noting here that there is no direct way to use an Iterator on an Array, but through the Arrays library it can be easily converted to a list with Arrays.asList to obtain an Iterable object.

In two-dimensional arrays or more, both techniques can be used in a slightly more complex fashion.

Example:

int[][] array = new int[10][10];

for( int indexOuter = 0; indexA < array.length; indexA++; ){
    for( int indexInner = 0; indexInner < array[0].length; indexInner++ ){
        array[indexOuter][indexInner] = indexOuter + indexInner;
    }
}

for(int[] numbers : array){
    for(int value : numbers){
        System.out.println(value);
    }
}

It is impossible to set an Array to any non-uniform value without using an index based loop.

Of course you can also use while or do-while loops when iterating using indices.

One note of caution: when using array indices, make sure the index is between 0 and array.length - 1 (both inclusive). Don't make hard coded assumptions on the array length otherwise you might break your code if the array length changes but your hard coded values don't.

Example:

int[] numbers = {1,2,3,4};

public void incrementNumbers() {
  //DO 
  for( int i = 0; i < numbers.length; i++ ) {
    numbers[i] += 1; //or this: numbers[i] = numbers[i] + 1; or numbers[i]++;      
  }
 
  //DON'T
  for( int i = 0; i < 4; i++ ) {
    numbers[i] += 1;
  }
}

It's also best if you don't use fancy calculations to get the index but use the index to iterate and if you need different values calculate those.

Example:

public void fillArrayWithDoubleIndex( int[] array ) {
  //DO 
  for( int i = 0; i < array.length; i++ ) {
    array[i] = i * 2;
  }
 
  //DON'T
  int doubleLength = array.length * 2;
  for( int i = 0; i < doubleLength; i += 2 ) {
    array[i/2] = i;
  }
}

How to access array elements backwards?

int[] array = {0, 1, 1, 2, 3, 5, 8, 13};
for( int i = array.length-1; i >= 0; i--) {
   System.out.println(array[i]);
}

Remove an element from an array

5

Java doesn't provide a direct method in java.util.Arrays to remove an element from an array. To perform it, you can either copy the original array to a new one without the element to remove or convert your array to another structure allowing the removal.

Using ArrayList

You can convert the array to a java.util.List, remove the element and convert the list back to an array as follows:

String[] array = new String[]{"foo", "bar", "baz"};

List<String> list = new ArrayList<>(Arrays.asList(array));
list.remove("foo");

// Creates a new array with the same size as the list and copies the list
// elements to it.
array = list.toArray(new String[list.size()]);

System.out.println(Arrays.toString(array)); //[bar, baz]

Using System.arraycopy

System.arraycopy() can be used to make a copy of the original array and remove the element you want. Below an example:

int[] array = new int[] { 1, 2, 3, 4 }; // Original array.
int[] result = new int[array.length - 1]; // Array which will contain the result.
int index = 1; // Remove the value "2".

// Copy the elements at the left of the index.
System.arraycopy(array, 0, result, 0, index);
// Copy the elements at the right of the index.
System.arraycopy(array, index + 1, result, index, array.length - index - 1);

System.out.println(Arrays.toString(result)); //[1, 3, 4]

Using Apache Commons Lang

To easily remove an element, you can use the Apache Commons Lang library and especially the static method removeElement() of the class ArrayUtils. Below an example:

int[] array = new int[]{1,2,3,4};
array = ArrayUtils.removeElement(array, 2); //remove first occurrence of 2
System.out.println(Arrays.toString(array)); //[1, 3, 4]

Test if an array contains an element

5

Non-primitive array

If your array doesn't contain primitive elements, then you can use

String[] array = new String[]{"foo", "bar", "baz"};
Arrays.asList(array).contains("foo"); // true

Primitive array

Since primitives are not generic, you cannot use Arrays.asList(array).contains(). Instead, you can perform the check as below:

Java SE 8
int[] array = {4, 1, 3, 2};
boolean anyMatch = IntStream.of(array).anyMatch(x -> x == 4); // true
Java SE 8

There is no native Java utility to do this, so you have to manually loop over the array to check if it contains the element.

int[] array = {4, 1, 3, 2};
boolean contains = false;

for(int arrayValue : array) {
    if(arrayValue == 4) {
        contains = true;
        break;
    }
}

You can also use org.apache.commons library to easily perform the check:

int[] array = {4, 1, 3, 2};
org.apache.commons.lang3.ArrayUtils.ArrayUtils.contains(array, 4); // true

Array Covariance

4

Object arrays are covariant, which means that just as Integer is a subclass of Number, Integer[] is a subclass of Number[]. This may seem intuitive, but can result in surprising behavior:

Integer[] integerArray = {1, 2, 3};
Number[] numberArray = integerArray;  // valid
Number firstElement = numberArray[0]; // valid
numberArray[0] = 4L;                  // throws ArrayStoreException at runtime

Although Integer[] is a subclass of Number[], it can only hold Integers, and trying to assign a Long element throws a runtime exception.

Note that this behavior is unique to arrays, and can be avoided by using a generic List instead:

List<Integer> integerList = Arrays.asList(1, 2, 3);
//List<Number> numberList = integerList;  // compile error
List<? extends Number> numberList = integerList;
Number firstElement = numberList.get(0);
//numberList.set(0, 4L);                  // compile error

Copying arrays

4

Java provides several ways to copy an array.

for loop

 int[] a = { 4, 1, 3, 2 };
 int[] b = new int[a.length]; 
 for (int i = 0; i < a.length; i++)
 {
    b[i] = a[i];
 }

Note that using this option with an Object array instead of primitive array will fill the copy with reference to the original content instead of copy of it.

Object.clone()

Since Array is considered as an Object in Java, you can use Object.clone().

int[] a = { 4, 1, 3, 2 };
int[] b = a.clone(); // [4, 1, 3, 2]

Note that the clone method returns a reference to a new array which references the same elements as the source array.


Arrays.copyOf()

java.util.Arrays provides a easy way to perform the copy of an array to another. Here is the basic usage:

int[] a = {4, 1, 3, 2};
int[] b = Arrays.copyOf(a, a.length); // [4, 1, 3, 2]

System.arraycopy()

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

Below an example of use

int[] a = { 4, 1, 3, 2 };
int[] b = new int[a.length];
System.arraycopy(a, 0, b, 0, a.length); // [4, 1, 3, 2]

Arrays.copyOfRange()

Mainly used to copy a part of an Array, you can also use it to copy whole array to another as below:

int[] a = { 4, 1, 3, 2 };
int[] b = Arrays.copyOfRange(a, 0, a.length); // [4, 1, 3, 2]

Getting the Length of an Array

4

Arrays are objects which provide space to store up to its size of elements of specified type. An array's size can not be modified after the array is created.

int[] arr1 = new int[0];
int[] arr2 = new int[]{1, 2, 3, 4};
int[] arr3 = {1, 2, 3, 4, 5, 6, 7};

int len1 = arr1.length; // 0
int len2 = arr2.length; // 4
int len3 = arr3.length; // 7

The length field in an array stores the size of an array. It is a final field and cannot be modified.

This code shows the difference between the length of an array and amount of objects an array stores.

public static void main(String[] args) {
    Integer arr[] = new Integer[] {1,2,3,null,5,null,7,null,null,null,11,null,13};

    int arrayLength = arr.length;
    int nonEmptyElementsCount = 0;

    for (int i=0; i<arrayLength; i++) {
        Integer arrElt = arr[i];
        if (arrElt != null) {
            nonEmptyElementsCount++;
        }
    }

    System.out.println("Array 'arr' has a length of "+arrayLength+"\n"
                            + "and it contains "+nonEmptyElementsCount+" non-empty values");
}

Result:

Array 'arr' has a length of 13
and it contains 7 non-empty values

Seaching an Array

4

Java offers several ways for searching a value in arrays.

Here I am describing searching method in array.

  • Using a List

    String[] arr1 = new String[] {"A", "B", "C"};
    boolean found1 = Arrays.asList(arr1).contains("A");
    System.out.println(found1);
    
  • Using a Set

    String[] arr1 = new String[] {"A", "B", "C"};
    HashSet<String> set =  new HashSet<>(Arrays.asList(arr1));
    boolean found2 = set.contains("A");
    System.out.println(found2);
    
  • Using a stream

Java SE 8
  String[] arr1 = new String[] {"A", "B", "C"};
  boolean found3 = Arrays.stream(arr1).anyMatch("A"::equals);
  System.out.println(found3);
  • Direct search on array using linear search

    String[] arr1 = new String[] {"A", "B", "C"};
    boolean found = false;
    for(int i=0; i<arr1.length; i++){
        if(arr1[i].equals("A")){
            found = true;
            break;
        }            
    }
    if(found){
        System.out.println("Found");
    } else {
        System.out.println("Not Found");
    }
    
  • Direct search on array using binary search

    String[] array = new String[] { "A", "B", "C", "E", "F", "G", "H", "I"};
    String toSearch = "H";
    boolean found = false;
    int min = 0, max = array.length - 1, mid, comp;
    while (min < max) {
        mid = (min + max) / 2;
        comp = toSearch.compareTo(array[mid]);
        if (comp == 0) {
            found = true;
            break;
        } else if (comp < 0) {
            max = mid - 1;
        } else {
            min = mid + 1;
        }
    }
    if(found){
        System.out.println("found");
    } else {
        System.out.println("not found");
    }
    
  • Using method binarySearch(Object[] a, Object key) from java.util.Arrays library

Note: Array being searched using the binarySearch(Object[] a, Object key) method must be already sorted into ascending order according to the natural ordering of its elements prior to making this call.

Note: Using a simple loop method is more efficient than using any collection.

Arrays as method parameter

3

You can use the varargs syntax sugar to make passing an array to a method easier for the caller.

void varargs(String... arguments) {
    if (arguments == null) {                      // guard for null arrays
        return;
    }
    if (arguments.length >= 1) {                  // guard for empty arrays
        String first = arguments[0]; // Access like a normal array
    }
}

void main() {
    varargs("First", "Second"); // call without explicitly creating the array
    varargs(); // or even without any parameters at all (creates empty, non-null array)

    // or directly with given array
    String[] givenArray = {"Third", "Forth"};
    varargs(givenArray)

    // null arrays are also supported
    String[] nullArray = null;
    varargs(nullArray);
    varargs((String[]) null);
}

Comparing arrays for equality

3

Array types inherit their equals() (and hashCode()) implementations from java.lang.Object, so equals() will only return true when comparing against the exact same array object. To compare arrays for equality based on their values, use java.util.Arrays.equals, which is overloaded for all array types.

int[] a = new int[]{1, 2, 3};
int[] b = new int[]{1, 2, 3};
System.out.println(a.equals(b)); //prints "false" because a and b refer to different objects
System.out.println(Arrays.equals(a, b)); //prints "true" because the elements of a and b have the same values

When the element type is a reference type, Arrays.equals() calls equals() on the array elements to determine equality. In particular, if the element type is itself an array type, identity comparison will be used. To compare multidimensional arrays for equality, use Arrays.deepEquals() instead as below:

int a[] = { 1, 2, 3 };
int b[] = { 1, 2, 3 };

Object[] aObject = { a }; // aObject contains one element
Object[] bObject = { b }; // bObject contains one element

System.out.println(Arrays.equals(aObject, bObject)); // false
System.out.println(Arrays.deepEquals(aObject, bObject));// true

Because sets and maps use equals() and hashCode(), arrays are generally not useful as set elements or map keys. Either wrap them in a helper class that implements equals() and hashCode() in terms of the array elements, or convert them to List instances and store the lists.

Casting Arrays

2

Arrays are objects, but their type is defined by the type of the contained objects. Therefore, one cannot just cast A[] to T[], but each A member of the specific A[] must be cast to a T object. Generic example:

public static <T, A> T[] castArray(T[] target, A[] array) {
    for (int i = 0; i < array.length; i++) {
        target[i] = (T) array[i];
    }
    return target;
}

Thus, given an A[] array:

T[] target = new T[array.Length];
target = castArray(target, array);

You can just use Arrays.copyOf(original, newLength, newType)) as well.

Converting an Array of Objects to an Array of primitives

2
Integer[] integerArray = new Integer[]{1, 2, 3, 4, 5}; // The array of Integer objects
int[] intArray = Arrays.stream(integerArray)
                       .mapToInt(Integer::intValue)
                       .toArray(); // The resulting array of ints

Resizing an array to add more elements

2

Once an array is initialized, you cannot resize the array if you want to add more elements to it.

String[] listOfCities = new String[3];
listOfCities[0] = "New York";
listOfCities[1] = "London";
listOfCities[2] = "Berlin";

If a new element needs to be added to above listOfCities, you have a create a new array with size 4 and copy above 3 elements to it (may be using an iterator) and then add the new element at the end (or whatever position you may need).

String[] newArray = new String[4];
System.arraycopy( listOfCities, 0, newArray, 0, listOfCities.length );

In such scenario, it is best to use a List implementation like an ArrayList.

See this example on creating ArrayList and add elements to it.

Declaring an ArrayList and adding objects

Use Objects with ArrayList

2

In this exemple we use ArrayList of an Object, we named it User like that:

package stack;

import java.util.Date;

public class User {
    
    private String username;
    private String password;
    private Date submit;

    public User() {
    }

    public User(String username, String password, Date submit) {
        this.username = username;
        this.password = password;
        this.submit = submit;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getSubmit() {
        return submit;
    }

    public void setSubmit(Date submit) {
        this.submit = submit;
    }
}

Now we will create a new ArrayList and add some Users:

package stack;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ArrayObject {

    public static void main(String args[]) {
        List<User> listeUser = new ArrayList<>();

        listeUser.add(new User("JSE", "JSE123", new Date(2010, 7, 22)));
        listeUser.add(new User("JEE", "JEE123", new Date(2012, 10, 15)));
        listeUser.add(new User("JME", "JME123", new Date(2014, 8, 7)));

        for (User user : listeUser) {
            System.out.println(user.getUsername() + ", " + user.getPassword() 
                    + ", " + new SimpleDateFormat("yyyy-MM-dd").format(user.getSubmit()));
        }

    }
}

Result:

JSE, JSE123, 3910-08-22

JEE, JEE123, 3912-11-15

JME, JME123, 3914-09-07

Reversing an array

0

It happens quite often, that the necessity of reversing an array in a program arises.This example illustrates how to do so, by reversing a String array.(You can change the data type from Object to primitive like int, float etc. to reverse arrays of primitive types as well.)

public class ReversingAnArrayExample
{
    public static void main(String[] args)
    {
        String[] names={"1-Apricot","2-Banana","3-Coconut","4-Date","5-Elderberry","6-Fig"};
        System.out.println("Original array is:");
        for(String s:names)
        {
            System.out.println(s);
        }
        reverseArray(names);
        
        System.out.println("\nReversed array is:");
        for(String s:names)
        {
            System.out.println(s);
        }
    }

    static void reverseArray(Object[] array)
    {
        for(int i=0;i<array.length/2;i++)
        {
            Object temp=array[i];
            array[i]=array[array.length-i-1];
            array[array.length-i-1]=temp;
        }
    }
}

It is to be noted that this function is not creating any extra copy of array, thus it returns nothing and saves memory as well!

Topic Outline