Java Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets: String[] cars; We have now declared a variable that holds an java array of strings.
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[2];
int[] arr3 = new int[]{1, 2, 3, 4};
int[] arr4 = {1, 2, 3, 4, 5, 6, 7};
int len1 = arr1.length; // 0
int len2 = arr2.length; // 2
int len3 = arr3.length; // 4
int len4 = arr4.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
Finding an element in an java array
There are many ways find the location of a value in an array. The following example snippets all assume that the array is one of the following:
String[] strings = new String[] { "A", "B", "C" };
int[] ints = new int[] { 1, 2, 3, 4 };
In addition, each one sets index or index2 to either the index of required element, or -1 if the element is not present.
Using Arrays.binarySearch (for sorted arrays only) int index = Arrays.binarySearch(strings, "A"); int index2 = Arrays.binarySearch(ints, 1);
Using a Arrays.asList (for non-primitive arrays only) int index = Arrays.asList(strings).indexOf("A"); int index2 = Arrays.asList(ints).indexOf(1); // compilation error
Using a Stream Version ≥ Java SE 8 int index = IntStream.range(0, strings.length) .filter(i -> "A".equals(strings[i])) .findFirst() .orElse(-1); // If not present, gives us -1. // Similar for an array of primitives Linear search using a loop int index = -1; for (int i = 0; i < array.length; i++) { if ("A".equals(array[i])) { index = i; break; } } // Similar for an array of primitives
Linear search using 3rd-party libraries such as org.apache.commons int index = org.apache.commons.lang3.ArrayUtils.contains(strings, "A"); int index2 = org.apache.commons.lang3.ArrayUtils.contains(ints, 1);
Note: Using a direct linear search is more efficient than wrapping in a list.
Testing if an array contains an element
The examples above can be adapted to test if the array contains an element by simply testing to see if the index computed is greater or equal to zero.
Alternatively, there are also some more concise variations:
boolean isPresent = Arrays.asList(strings).contains("A"); Version ≥ Java SE 8 boolean isPresent = Stream.of(strings).anyMatch(x -> "A".equals(x)); boolean isPresent = false; for (String s : strings) { if ("A".equals(s)) { isPresent = true; break; } } boolean isPresent = org.apache.commons.lang3.ArrayUtils.contains(ints, 4);
How do you change the size of an array?
The simple answer is that you cannot do this. Once an array has been created, its size cannot be changed. Instead, an array can only be “resized” by creating a new array with the appropriate size and copying the elements from the existing array to the new one.
String[] listOfCities = new String[3]; // array created with size 3.
listOfCities[0] = "New York";
listOfCities[1] = "London";
listOfCities[2] = "Berlin";
Suppose (for example) that a new element needs to be added to the listOfCities array defined as above. To do this, you will need to:
Related Article: Array Covariance
- create a new array with size 4,
- copy the existing 3 elements of the old array to the new array at offsets 0, 1 and 2, and
- add the new element to the new array at offset 3.
There are various ways to do the above. Prior to Java 6, the most concise way was:
String[] newArray = new String[listOfCities.length + 1];
System.arraycopy(listOfCities, 0, newArray, 0, listOfCities.length);
newArray[listOfCities.length] = "Sydney";
From Java 6 onwards, the Arrays.copyOf and Arrays.copyOfRange methods can do this more simply:
String[] newArray = Arrays.copyOf(listOfCities, listOfCities.length + 1);
newArray[listOfCities.length] = "Sydney";
For other ways to copy an array, refer to the following example. Bear in mind that you need an array copy with a different length to the original when resizing.
- Copying arrays
A better alternatives to array resizing
There two major drawbacks with resizing an array as described above:
- It is inefficient. Making an array bigger (or smaller) involves copying many or all of the existing array elements, and allocating a new array object. The larger the array, the more expensive it gets.
- You need to be able to update any “live” variables that contain references to the old array.
One alternative is to create the array with a large enough size to start with. This is only viable if you can determine that size accurately before allocating the array. If you cannot do that, then the problem of resizing the array arises again.
The other alternative is to use a data structure class provided by the Java SE class library or a third-party library. For example, the Java SE “collections” framework provides a number of implementations of the List, Set and Map APIs with different runtime properties. The ArrayList class is closest to performance characteristics of a plain array (e.g. O(N) lookup, O(1) get and set, O(N) random insertion and deletion) while providing more efficient resizing without the reference update problem.
(The resize efficiency for ArrayList comes from its strategy of doubling the size of the backing array on each resize. For a typical use-case, this means that you only resize occasionally. When you amortize over the lifetime of the list, the resize cost per insert is O(1). It may be possible to use the same strategy when resizing a plain array.)
Converting arrays between primitives and boxed types
Sometimes conversion of primitive types to boxed types is necessary.
To convert the array, it’s possible to use streams (in Java 8 and above):
Version ≥ Java SE 8 int[] primitiveArray = {1, 2, 3, 4}; Integer[] boxedArray = Arrays.stream(primitiveArray).boxed().toArray(Integer[]::new);
With lower versions it can be by iterating the primitive array and explicitly copying it to the boxed array:
Version < Java SE 8 int[] primitiveArray = {1, 2, 3, 4}; Integer[] boxedArray = new Integer[primitiveArray.length]; for (int i = 0; i < primitiveArray.length; ++i) { boxedArray[i] = primitive Array[i]; // Each element is autoboxed here }
Similarly, a boxed array can be converted to an array of its primitive counterpart:
Version ≥ Java SE 8 Integer[] boxedArray = {1, 2, 3, 4}; int[] primitiveArray = Arrays.stream(boxedArray).mapToInt(Integer::intValue).toArray(); Version < Java SE 8 Integer[] boxedArray = {1, 2, 3, 4}; int[] primitiveArray = new int[boxedArray.length]; for (int i = 0; i < boxedArray.length; ++i) { primitiveArray[i] = boxedArray[i]; // Each element is outboxed here }
Remove an element from an array
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 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]
Comparing arrays for equality
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.
Copying arrays
Java provides several ways to copy an array.
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 arrays are Objects in Java, you can use Object.clone().
int[] a = { 4, 1, 3, 2 };
int[] b = a.clone(); // [4, 1, 3, 2]
Note that the Object.clone method for an array performs a shallow copy, i.e. it returns a reference to a new array which references the same elements as the source array.
Arrays.copyOf()
java.util.Arrays provides an 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]
Note that Arrays.copyOf also provides an overload which allows you to change the type of the array:
Double[] doubles = { 1.0, 2.0, 3.0 };
Number[] numbers = Arrays.copyOf(doubles, doubles.length, Number[].class);
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]
Casting Arrays
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[] 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);
Java SE provides the method Arrays.copyOf(original, newLength, newType) for this purpose:
Double[] doubles = { 1.0, 2.0, 3.0 };
Number[] numbers = Arrays.copyOf(doubles, doubles.length, Number[].class);