Convert Array to List with asList
The Arrays.asList method wraps an array into a fixed-size list, enabling collection-based operations like iteration or passing to methods expecting a List.
Signature:
public static <T> List<T> asList(T... a)
Example:
import java.util.Arrays;
import java.util.List;
public class ArrayConversion {
public static void main(String[] args) {
String[] fruits = {"Mango", "Peach", "Grape"};
List<String> fruitList = Arrays.asList(fruits);
System.out.println(fruitList);
}
}
Output:
[Mango, Peach, Grape]
Implementation Note:
The method accepts a varargs parameter of generic type T. It creates and returns a new ArrayList instance containing the elements from the input array.
Searching with binarySearch
Use Arrays.binarySearch to locate an element in a sorted array. It returns the index if found; otherwise, it returns a negative value.
Signature:
public static int binarySearch(int[] a, int key)
// Overloads exist for other types and include an optional Comparator
Example:
import java.util.Arrays;
public class SearchDemo {
public static void main(String[] args) {
int[] data = {15, 30, 45, 60, 75};
int position = Arrays.binarySearch(data, 45);
System.out.println("Found 45 at index: " + position);
}
}
Output:
Found 45 at index: 2
Implementation Note:
The method delegates to an internal binarySearch0. It sets low and high bounds and iteratively checks the middle element. If the key is found, the index is returned; otherwise, -(low + 1) is returned.
Duplicating Arrays with copyOf
Arrays.copyOf creates a new array of a specified length, copying elements from the original. If the new length exceeds the original, the remaining slots are filled with default values (e.g., 0 for int).
Signature:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType)
Example:
import java.util.Arrays;
public class CopyExample {
public static void main(String[] args) {
int[] source = {10, 20, 30, 40};
int[] shorter = Arrays.copyOf(source, 2);
int[] longer = Arrays.copyOf(source, 6);
System.out.println(Arrays.toString(shorter));
System.out.println(Arrays.toString(longer));
}
}
Output:
[10, 20]
[10, 20, 30, 40, 0, 0]
Implementation Note:
It determines the new array type, instantiates it, and uses System.arraycopy to transfer the data up to the minimum of the original length or the new length.
Slicing Arrays with copyOfRange
This method extracts a portion of an array into a new array based on start (inclusive) and end (exclusive) indices.
Signature:
public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)
Example:
import java.util.Arrays;
public class RangeCopy {
public static void main(String[] args) {
String[] crew = {"Jake", "Amy", "Terry", "Rosa", "Charles"};
String[] subset = Arrays.copyOfRange(crew, 1, 4);
System.out.println(Arrays.toString(subset));
}
}
Output:
[Amy, Terry, Rosa]
Implementation Note:
It calculates the new length (to - from), creates the destination array, and copies the specified range using System.arraycopy.
Populating Arrays with fill
Arrays.fill sets every element in an array to a specific value.
Signature:
public static void fill(int[] a, int val)
// Multiple overloads for various data types
Example:
import java.util.Arrays;
public class FillDemo {
public static void main(String[] args) {
long[] ids = new long[4];
Arrays.fill(ids, 100L);
System.out.println(Arrays.toString(ids));
}
}
Output:
[100, 100, 100, 100]
Implementation Note: For each primitive type and objects, the method simply iterates through the array and assigns the value to every index.
Sorting Arrays with sort
Arrays.sort arranges the elements of an array into ascending order. For object arrays, a Comparator can be provided to define custom ordering.
Signature:
public static void sort(int[] a)
public static <T> void sort(T[] a, Comparator<? super T> c)
Example:
import java.util.Arrays;
public class SortExample {
public static void main(String[] args) {
double[] prices = {19.99, 5.49, 12.00, 8.75};
Arrays.sort(prices);
System.out.println(Arrays.toString(prices));
}
}
Output:
[5.49, 8.75, 12.0, 19.99]
Implementation Note: Primitive arrays typically use a Dual-Pivot Quicksort algorithm. Object arrays generally use TimSort or a legacy merge sort depending on JVM settings and whether a comparator is provided.
Displaying Arrays with toString
Convetrs an array into a readable string format, listing its elements.
Signature:
public static String toString(int[] a)
// Overloads for all primitive types and Object arrays
Example:
import java.util.Arrays;
public class PrintArray {
public static void main(String[] args) {
char[] letters = {'x', 'y', 'z'};
String representation = Arrays.toString(letters);
System.out.println(representation);
}
}
Output:
[x, y, z]
Implementation Note:
The method checks for null or empty arrays first. Otherwise, it iterates through the elements, appending them to a StringBuilder with comma separators and square brackets.