The Arrays is a utility class which can be found in the java.util package. It is very useful class and following are some of useful methods it has:
- asList(): returns a fixed-size list backed by an array.
- binarySearch(): searches for a specific value in an array. Returns the index of the element if found, or -1 if not found. Note that the array must be sorted first.
- copyOf(): copies a portion of the specified array to a new one.
- copyOfRange(): copies a specified range of an array to a new one.
- equals(): compares two arrays to determine if they are equal or not.
- fill(): fills same values to all or some elements in an array.
- sort(): sorts an array into ascending order.
void sort(X[] a, int fromIndex, int toIndex)
void sort(T[] a, Comparator<? super T> c)
void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)
- And other methods you can find in the Arrays class Javadoc.
In addition, the System.arraycopy()
is an efficient method for copying elements from one array to another.
Remember using this method instead of writing your own procedure because
this method is very efficient. Arrays.copyOf(originalArray, newLength) method internally uses that method .Refer this document for more about creating a copy of array.
System.arraycopy(Object copyFromArray, int startingPositionOfArrayToCopy,
Object copyToArray, int landingPositionOfArrayCopy, int totalNumerOfComponentsToBeCopy)
So far I have walked you through a tour of arrays in Java. Here’s the summary for today:
- An array is an object.
- Elements in an array are accessed by index (0-based).
- Advantage of array: very fast access to elements.
- Disadvantage of array: fixed length, not appropriate if a dynamic container is required.
- The java.util.Arrays class provides useful utility methods for working with arrays such as filling, searching and sorting.
- The System.arraycopy() method provides an efficient mechanism for copying elements from one array to another.
References Used :- Notes about Arrays in Java