This section contains the detail about the Methods of the array class in java.
Methods of the array class
The "java.util.Arrays" is the base class for arrays in Java which have many static methods for searching, sorting, comparing and filling arrays. All primitive type can be overloaded using these methods. The main methods are given below :
Method | Description |
public static int binarySearch(Object[] a, Object key) | Searches the specified array for the specified object using the binary search algorithm. |
public static boolean equals(long[] a, long[] a2) | Returns true if the two specified arrays of longs are equal to one another. |
public static void fill(int[] a, int val) | Assigns the specified int value to each element of the specified array of ints. |
public static void sort(Object[] a) | Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. |
Click here to see complete list of Array methods
Examples :
sort()
& binarysearch()
Methods' Example :
import java.util.Arrays; public class DevClass { public static void main(String args[]) throws Exception { int DevArray[] = { 1, 3, 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; Arrays.sort(DevArray); printArray("Sorted array", DevArray); int index = Arrays.binarySearch(DevArray, 2); System.out.println("2 is found at index " + index); } private static void printArray(String message, int DevArray[]) { System.out.println(message + ": [length: " + DevArray.length + "]"); for (int i = 0; i < DevArray.length; i++) { if (i != 0) { System.out.print(", "); } System.out.print(DevArray[i]); } System.out.println(); } }
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac DevClass.java C:\Program Files\Java\jdk1.6.0_18\bin>java DevClass Sorted array: [length: 12] -9, -7, -3, -2, 0, 1, 2, 3, 4, 5, 6, 8 2 is found at index 6 |
fill()
Method Example
import java.util.*; public class FillDemo { public static void main(String args[]) { int DevArray[] = new int[6]; Arrays.fill(DevArray, 100); for (int i = 0, n = DevArray.length; i < n; i++) { System.out.println(DevArray[i]); } System.out.println(); Arrays.fill(DevArray, 3, 6, 50); for (int i = 0, n = DevArray.length; i < n; i++) { System.out.println(DevArray[i]); } } }
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac FillDemo
.java C:\Program Files\Java\jdk1.6.0_18\bin>java FillDemo 100 100 100 100 100 100 100 100 100 50 50 50 |
[ 0 ] Comments