1. Declaring Array Variables:
dataType[] arrayRefvar;
dataType arrayRefVar[]; // C/C++风格,适应C/C++程序员
2. Creating Arrays:
arrayRefVar = new dataType[arraySize]
dataType[] arrayRefVar = new dataType[arraySize];
dataType[] arrayRefVar = new int[]{3, 1, 2, 4};
dataType[] arrayRefVar = {v0, v1, v2,..., vk}; // array length: arrayRefVar.length
3. Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
4. The Arrays Class
java.util.Arrays 类包含了若干个静态方法。
Sr.No. | Method & Description |
---|---|
1 | public static int binarySearch(Object[] a, Object key) Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, it returns ( – (insertion point + 1)). |
2 | public static boolean equals(long[] a, long[] a2) Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.) |
3 | public static void fill(int[] a, int val) Assigns the specified int value to each element of the specified array of ints. The same method could be used by all other primitive data types (Byte, short, Int, etc.) |
4 | public static void sort(Object[] a) Sorts the specified array of objects into an ascending order, according to the natural ordering of its elements. The same method could be used by all other primitive data types ( Byte, short, Int, etc.) |