首页 > 代码库 > 【dataStructure】 Arrays and Java Source Review
【dataStructure】 Arrays and Java Source Review
According to the order of data structure book, Arrays should be introduced in the frist time. When reviewing the some information related to arrays, I feel shocked that many useful classes and methods in java language has been ignored. Now set a simple example of usage of arrays.
package com.albertshao.ds.array; import java.util.Arrays; public class TestArrays { public static void main(String[] args) { int[] a = { 44, 77, 55, 22, 99, 88, 33, 66 }; print(a); Arrays.sort(a); print(a); int k = Arrays.binarySearch(a, 44); System.out.printf("Arrays.binarySearch(a, 44): %d%n", k); System.out.printf("a[%d]: %d%n", k, a[k]); k = Arrays.binarySearch(a, 45); System.out.printf("Arrays.binarySearch(a, 45): %d%n", k); int[] b = new int[8]; print(a); Arrays.fill(b, 55); print(a); System.out.println("Arrays.equals(a,b): " + Arrays.equals(a, b)); } public static void print(int[] a) { System.out.printf("{%s", a[0]); for (int i = 1; i < a.length; i++) { System.out.printf(", %s", a[i]); } System.out.println("}"); } }
The result of execution is as follows:
{44, 77, 55, 22, 99, 88, 33, 66} {22, 33, 44, 55, 66, 77, 88, 99} Arrays.binarySearch(a, 44): 2 a[2]: 44 Arrays.binarySearch(a, 45): -4 {22, 33, 44, 55, 66, 77, 88, 99} {22, 33, 44, 55, 66, 77, 88, 99} Arrays.equals(a,b): false
Note:
First I have to say that the method ‘sort‘ in arrays is written so great and complesive that I spent much time on that, but now still have no idea about that. In future, this method should be attached importance to it. In a simple way, this function is used to sort the object list. The default order is ascending.
Second, Arrays.binarySearch method is used to searches the specified array of ints for the specified value using the binary search algorithm.
The source code:
private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. }
The picute for explanation:
then as for the Arrays.fill(), which means that array is filled with the argument. All the elments in array is the argument.
Lastly, if array a is equivent to b, it means the length\ element\elmentType of both are same.