Java Array
An array is a collection of elements of the same data type, stored in a contiguous memory location. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
Features of Array
- In Java, all arrays are dynamically allocated.
- Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find length using sizeof function.
- A Java array variable can also be declared like other variables with [] after the data type.
- The variables in the array are ordered and each has an index beginning from 0.
- Java array can also be used as a static field, a local variable or a method parameter.
- The size of an array must be specified by an int value and not long or short.
- The direct superclass of an array type is Object.
Shortcomings of Java
- Every array type implements the interfaces Cloneable and java.io.Serializable.
- The size of an Array can not be increased or decreased dynamically.
- Array Class doesn't have an add or remove methods in Java
- Arrays Suffer from the issue of memory wastage.
- To delete an element in an array we need to traverse throughout the array so this will reduce performance.
- Arrays in java only support primitive data types.
Types of Array
1. One-Dimensional Array
This is a type of array which is arranged in the form of rows only i.e. all the elements are stored can only be visualized in a linear format/ 1D figure
- import java.util.Arrays;
- import static java.lang.System.out;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- out.println("Integer Array as List: " +
- Arrays.asList(demo));
- }
- }
In the above code, we are creating a 1D array named
demo.
2. Two-Dimensional Array
This is a type of array which is arranged in the form of rows and columns i.e. all the elements stored can be visualized as a Matrix or in 2D figure
- import static java.lang.System.out;
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[][] = {
- {
- 2,
- 7,
- 9
- },
- {
- 3,
- 6,
- 1
- },
- {
- 7,
- 4,
- 2
- }
- };
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++)
- out.print(demo[i][j] + " ");
- out.println();
- }
- }
- }
In the above code, we are creating a 2D array named
demo.
3. Multi-Dimensional / N-Dimensional Array
This is a type of array which is arranged in the form of (N-C) rows and C columns, where N is the dimension of array and C is the number of columns i.e all the elements stored can be visualized as (N-C) x C dimensional matrix or in an N-dimensional figure
- import java.util.Arrays;
- import static java.lang.System.out;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[][][] = {
- {
- {
- 1,
- -2,
- 3
- }, {
- 2,
- 3,
- 4
- }
- },
- {
- {
- -4, -5, 6, 9
- },
- {
- 1
- },
- {
- 2,
- 3
- }
- }
- };
- for (int[][] array2D: demo) {
- for (int[] array1D: array2D) {
- for (int item: array1D) {
- out.println(item);
- }
- }
- }
- }
- }
In the above code, we are creating a 3D array named
demo.
java.util.Arrays
array class is part of a java utility library, which comes pre-installed and pre-built as part of JDK (Java Development Environment).
A constructor can be used to create empty java arrays of various dimensions.
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int[] arr = new int[5];
- int[][] arr = new int[5][5];
- int[][][] arr = new int[5][5][5];
- }
- }
The above code demonstrates how we use a constructor to create 1D, 2D, and 3D Arrays
Array Methods
1. Arrays.asList()
Syntax
static <T> List<T> asList(T… a)
This method returns a fixed-size list backed by the specified Arrays.
- import java.util.Arrays;
- import static java.lang.System.out;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- out.println("Integer Array as List: " +
- Arrays.asList(demo));
- }
- }
In the above code, we will be getting a list type of result that is java.util.Arrays will get converted to java.util.List
2. Arrays.binarySearch()
Syntax
1. static int binarySearch(elementToBeSearched)
These methods search for the specified element in the array with the help of the Binary Search algorithm.
2. static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<T> c)
This method searches a range of the specified array for the specified object using the binary search algorithm.
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 15,
- 20,
- 22,
- 35
- };
- int Key = 22;
- int loc = Arrays.binarySearch(demo, Key)
- int loc1 = Arrays.binarySearch(demo, 1, 3, Key)
- }
- }
In the above code, we are using the binary search algorithm to search for 22, and the location of the element will be stored in the variable "loc". To demonstrate the use of the second version of binarySearch() we use variable "loc1", which will perform the search between on elements of location 1 to location 3. i.e we will get the output of loc=3 and loc1=-4 (loc1=-4 because we have specified the range to be between 1 and 3, had it be 1 to 4 we would have got the answer to be loc1=3)
3. Arrays.compare()
Syntax
compare(array 1, array 2)
This method compares two arrays passed as parameters lexicographically.
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- int demo1[] = {
- 10,
- 15,
- 22
- };
- int out = Arrays.compare(demo, demo1);
- }
- }
In the above code, we are comparing if some of the elements of Array
demo1 exist in the Array
demo. Since every element of
demo1 exists in
demo, hence the output will be 1 i.e true.
4. Arrays.compareUnsighned()
Syntax
compareUnsigned(array 1, array 2)
This method compares two arrays lexicographically, numerically treating elements as unsigned.
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- int demo1[] = {
- -10,
- -15,
- 22
- };
- int out = Arrays.compareUnsigned(demo, demo1);
- }
- }
Note: the above method may or may not run on systems, as some JDK versions support this method and some don't
In the above code, we are comparing if some of the elements of Array demo1 exist in the Array demo. Since every element of demo1 exists in the demo, hence the output will be 1 i.e true
5. Arrays.copyOf()
Syntax
copyOf(originalArray, newLength)
This method copies the specified array, truncating or padding with the default value (if necessary) so the copy has the specified length.
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- int demo1[] = Arrays.copyOf(demo, 10);
- }
- }
In the above code, we will be increasing the size of new array to 10, since we are copying the elements of Array
demo into Array
demo1, and demo has only 5 elements, hence the value of next 5 elements will be zero, i.e
demo1 will be {10, 20, 15, 22, 35, 0, 0, 0, 0, 0}
6. Arrays.copyOfRange()
Syntax
copyOfRange(originalArray, fromIndex, endIndex)
This method copies the specified range of the specified array into new Arrays.
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- int demo1[] = Arrays.copyOfRange(demo, 1, 3);
- }
- }
In the above code, we are creating a new Array
demo1 which contains the array elements of location 1 to 3 from array
demo.
7. Arrays.deepEquals()
Syntax
static boolean deepEquals(Object[] a1, Object[] a2)
This method returns true if the two specified arrays are deeply equal.
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- int demo1[] = {
- 10,
- 15,
- 22
- };
- boolean ans = Arrays.deepEquals(demo, demo1);
- }
- }
In the above code, we are comparing if all the elements of Array
demo1 exist in the Array
demo. Since every element of
demo1 does not exist in the
demo, hence the output will be 1 i.e false
8. Arrays.deepHashCode()
Syntax
static int deepHashCode(Object[] a)
This method returns a hash code based on the “deep contents” of the specified Arrays.
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[][] = {
- {
- 10,
- 20,
- 15,
- 22,
- 35
- }
- };
- int ans = Arrays.deepHashCode(demo);
- }
- }
Note: the method will not work on a 1D array
In the above code, we will get a Hash Code based on the given array, hence the output will be 38475344
9. Arrays.deepToString()
Syntax
static String deepToString(Object[] a)
This method returns a string representation of the “deep contents” of the specified Arrays.
- import java.util.Arrays;
- import static java.lang.System.out;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[][] = {
- {
- 10,
- 20,
- 15,
- 22,
- 35
- }
- };
- String ans;
- ans = Arrays.deepToString(demo);
- out.print(ans);
- }
- }
In the above code, the method will return a String object of array demo.
10. Arrays.equals()
Syntax
equals(array1, array2)
This method checks if both the arrays are equal or not.
- import java.util.Arrays;
- import static java.lang.System.out;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- int demo1[] = {
- 10,
- 15,
- 22
- };
- boolean ans;
- ans = Arrays.equals(demo, demo1);
- out.print(ans);
- }
- }
In the above code, we check whether both size and elements match in both the demo and demo1 array. Hence, the output will be false
11. Arrays.fill()
Syntax
fill(originalArray, fillValue)
This method assigns this fillvalue to each index of these Arrays.
- import static java.lang.System.out;
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- int intKey = 22;
- Arrays.fill(demo, intKey);
- out.print(Arrays.toString(demo));
- }
- }
In the above code, we will replace each element value with the fillValue i.e. 22
12. Arrays.hashCode()
Syntax
hashCode(originalArray)
This method returns an integer hashCode of this array instance.
- import static java.lang.System.out;
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[][] = {
- {
- 10,
- 20,
- 15,
- 22,
- 35
- }
- };
- int ans = Arrays.hashCode(demo);
- out.print(ans);
- }
- }
In the above code, we will be generating a hash code based on the given array. Here the output will be 366712673.
13. Arrays.mismatch()
Syntax
mismatch(array1, array2)
This method finds and returns the index of the first unmatched element between the two specified arrays
- import java.util.Arrays;
- import static java.lang.System.out;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- int demo1[] = {
- 10,
- 15,
- 22
- };
- int ans;
- ans = Arrays.mismatch(demo, demo1);
- out.print(ans);
- }
- }
Note: the above method may or may not run on systems, as some JDK versions support this method and some don't.
In the above code, the output will be 1 as demo1[1] and demo[0] does not match.
14. Arrays.parallelSort()
Syntax
parallelSort(originalArray)
This method sorts the specified array using a parallel sort.
- import java.util.Arrays;
- import static java.lang.System.out;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- Arrays.parallelSort(demo);
- out.print(Arrays.toString(demo));
- }
- }
In the above code, we will get an array demo sorted in ascending order.
15. Arrays.sort()
Syntax
1. sort(original arrayoriginalArray)
This method sorts the complete array in ascending order.
2. sort(originalArray, fromIndex, endIndex)
This method sorts the specified range of array in ascending order.
3. static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator< super T> c)
This method sorts the specified range of the specified array of objects according to the order induced by the specified comparator.
4. static <T> void sort(T[] a, Comparator< super T> c)
This method sorts the specified array of objects according to the order induced by the specified comparator.
- import java.util.Arrays;
- import static java.lang.System.out;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- Arrays.sort(demo);
- out.print(Arrays.toString(demo));
- Arrays.sort(demo, 1, 3);
- out.print(Arrays.toString(demo));
- }
- }
Note: the difference between parallelSort() and sort() is that Parallel Sort uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool.
In the above code, we will get an array demo sorted in ascending order in both cases as in the second case we are sorting demo[1] to demo[3], which is the only part that is unsorted
16. Arrays.spliterator()
Syntax
1. spliterator(originalArray)
This method returns a Spliterator covering all of the specified Arrays.
2. spliterator(originalArray, fromIndex, endIndex)
- import java.util.Arrays;
- import java.util.Spliterator;
- import static java.lang.System.out;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- Spliterator.OfInt demo1 = Arrays.spliterator(demo);
- out.print(demo1);
- Spliterator.OfInt demo2 = Arrays.spliterator(demo, 1, 3);
- out.print(demo2);
- }
- }
This method returns a Spliterator of the type of the array covering the specified range of the specified Arrays.
In the above code, we are first converting the whole of the array demo to spliterator and then converting a part of array demo to spliterator.
17. Arrays.stream()
Syntax
stream(originalArray)
This method returns a sequential stream with the specified array as its source.
- import java.util.Arrays;
- import static java.lang.System.out;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- out.println("Integer Array: " +
- Arrays.stream(demo));
- }
- }
In the above, we are trying to get a sequential stream with the specified array demo as the source i.e. Integer Array: java.util.stream.IntPipeline$Head@6d06d69c as the output
18. Arrays.toString()
Syntax
toString(originalArray)
This method returns a string representation of the contents of these Arrays. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters a comma followed by a space. Elements are converted to strings as by String.valueOf() function.
- import static java.lang.System.out;
- import java.util.Arrays;
- public class Csharpcorner {
- public static void main(String[] args) {
- int demo[] = {
- 10,
- 20,
- 15,
- 22,
- 35
- };
- out.println("Integer Array: " +
- Arrays.toString(demo));
- }
- }
In the above, we are converting java.util.Arrays to java.lang.String, i.e. converting to String from Array
Conclusion
In the article, we learned about Array, features of Array, Shortcomings of Array, Types of Arrays, Array Methods and how to use the Array Class and methods using Java.