Java.util.Arrays
java.util.Arrays类中提供了许多实用的方法,可用于数组的复制、排序等操作处理。
以下是常用的方法和属性:
- Arrays.sort() 串行排序:
源代码:
public static void sort(int[] a, int fromIndex, int toIndex) {
rangeCheck(a.length, fromIndex, toIndex);
DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
//双轴快速排序比一般的快速排序更快,优化后的快速排序
}
sort(数组名,起始下标,结束下标) //填充指定索引范围,按照升序进行数组排序,如果指定范围,则排序范围从起始索引(包括)到结束索引(不包括)。如果起始索引==结束索引,则排序范围为空。如果指定下标索引越界,则会抛出异常ArrayIndexOutOfBoundsException。这里底层用到rangeCheck()方法即范围检查,rangeCheck()方法具体如何实现如下:
private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) {
if (fromIndex > toIndex) {
throw new IllegalArgumentException(
"fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
}
if (fromIndex < 0) {
throw new ArrayIndexOutOfBoundsException(fromIndex);
}
if (toIndex > arrayLength) {
throw new ArrayIndexOutOfBoundsException(toIndex);
}
}
- 举例:
package kkee;
import java.util.Arrays;
/**
* @Package: kkee
* @Author:kkz
* @Description:
* @Date:Created in 2018/10/18 20:53
*/
public class Arraysort {
public static void main(String[] args) {
int[] array1 = {1,4,2,5,7,3,8,6};
Arrays.sort(array1);
System.out.println(Arrays.toString(array1));
}
}
[1, 2, 3, 4, 5, 6, 7, 8]
- Arrays.binarySearch() 二分查找:
使用二分查找来搜索指定类型的数组,以查找指定的键值。源代码:
public static int binarySearch(int[] a, int key) {
return binarySearch0(a, 0, a.length, key);
}
public static int binarySearch(int[] a, int fromIndex, int toIndex,
int key) {
rangeCheck(a.length, fromIndex, toIndex);
return binarySearch0(a, fromIndex, toIndex, key);
}
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; //无符号右移 = mid=low+(high-low)/2
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.
}
binarySearch(数组名,键值) / binarySearch(数组名,起始索引,结束索引,键值) //在指定索引范围内搜索,键值即我们要查找的数字,如果搜索键包含在数组中,则返回其索引,即在数组中的下标;否则返回(—(插入点)—1)。插入点为第一个大于键值的元素索引。如果指定下标索引越界,则会抛出异常ArrayIndexOutOfBoundsException。
- Arrays.equals() :
判断两个数组是否相等,结果为true或者false。源代码:
public static boolean equals(int[] a, int[] a2) {
if (a==a2)
return true; //判断数组是否相同;若相同,则结果为true
if (a==null || a2==null)
return false; //判断两个数组是否为空
int length = a.length; //声明数组长度
if (a2.length != length) //判断两个数组长度是否相等
return false;
for (int i=0; i<length; i++)
if (a[i] != a2[i]) //判断数组中元素是否相同
return false;
return true;
如果两个数组以相同顺序包含相同的元素,则两个数组是相等的。注:如果两个数组引用均为null,则认为他们是相等的。
- 举例:
public class Arraysort {
public static void main(String[] args) {
int[] array1 = {1,4,2,5,7,3,8,6};
int[] array2 = {1,2,3,4,5};
int[] array3 = {1,4,2,5,7,3,8,6};
int[] array4 = {1,2,3,4,5,6,7,8};
boolean b1 = Arrays.equals(array1,array2);
boolean b2 = Arrays.equals(array1,array3);
boolean b3 = Arrays.equals(array1,array4);
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
}
}
false
true
false
- Arrays.fill():
使用指定值填充数组。源代码:
public static void fill(int[] a, int val) {
for (int i = 0, len = a.length; i < len; i++)
a[i] = val;
}
public static void fill(int[] a, int fromIndex, int toIndex, int val) {
rangeCheck(a.length, fromIndex, toIndex);
for (int i = fromIndex; i < toIndex; i++)
a[i] = val;
}
fill(数组名,值)/fill(数组名,起始索引,结束索引,键值,值)//填充指定索引范围,如果指定范围,则填充从起始索引(包括)到结束索引(不包括)。注:如果起始索引==结束索引,则填充范围为空。如果指定下标索引越界,则会抛出异常ArrayIndexOutOfBoundsException。
- 举例:
public class Arraysort {
public static void main(String[] args) {
int[] array1 = {1,4,2,5,7,3,8,6};
int[] array2 = {1,2,3,4,5};
int[] array3 = {1,4,2,5,7,3,8,6};
int[] array4 = {1,2,3,4,5,6,7,8};
Arrays.fill(array4 , 5); //用一个数填充整个数组,未定义起始索引和结束索引则默认整个
System.out.println(Arrays.toString(array4));
Arrays.fill(array4 , 0 ,5,0); //从array[0]开始到aaray[5]用0填充,剩余不变
System.out.println(Arrays.toString(array4));
Arrays.fill(array4 , 0 ,10,0); //下标索引越界,运行时异常
System.out.println(Arrays.toString(array4));
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 10
[5, 5, 5, 5, 5, 5, 5, 5]
[0, 0, 0, 0, 0, 5, 5, 5]
at java.util.Arrays.rangeCheck(Arrays.java:120)
at java.util.Arrays.fill(Arrays.java:2903)
at kkee.Arraysort.main(Arraysort.java:21)
- Arrays.toString():
返回指定数组的字符串表示形式。源代码:
public static String toString(int[] a) {
if (a == null) //若数组为空,则返回null
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('['); //append()是往动态字符串数组添加 添加[
for (int i = 0; ; i++) {
b.append(a[i]); //添加数组的元素 按下标输出
if (i == iMax) // 如果i==iMax即数组中元素添加结束
return b.append(']').toString(); //添加]
b.append(", ");
}
}
前面的例子中已经使用过,可以查看结果。
练习:
- {1,2,3,4,5,6}数组将奇数放在偶数前面,大小顺序不要求。
package kkee;
import java.util.Arrays;
/**
* @Package: kkee
* @Author:kkz
* @Description:
* @Date:Created in 2018/10/19 1:16
*/
public class EvenoddChange {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6};
for (int i = 0; i < array.length; i++) {
int temp; //设置临时变量
for (int j = array.length - 1; j > 0; j--) {
//将后面的奇数放在偶数前
if (array[j] % 2 == 1 && array[j - 1] % 2 == 0) {
temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
System.out.println(Arrays.toString(array));
}
}
[1, 3, 5, 2, 4, 6]
- 一个数组是有序的,给定一个key:数字 有两个数字的和加起来等于key,
找到这两个数字的下标,例 {1,2,3,4,5,6} 7
public class NewArray {
public static void findIndex(int[] array,int key){
for(int i = 0; i < array.length ; i++){
for(int j = 1; j < array.length; j++){
int sum = 0;
sum = array[i] + array[j];
if(sum == key){
System.out.println("所加和等于key对应数组下标及元素: " + i + ": " + array[i]+ " " + " " + "" + j + ": " + array[j] );
}
}
}
}
public static void main(String[] args) {
int[] array = {1,2,3,4,5,6};
int key = 7;
findIndex(array, key);
}
}
所加和等于key对应数组下标及元素: 0: 1 5: 6
所加和等于key对应数组下标及元素: 1: 2 4: 5
所加和等于key对应数组下标及元素: 2: 3 3: 4
所加和等于key对应数组下标及元素: 3: 4 2: 3
所加和等于key对应数组下标及元素: 4: 5 1: 2
- 一个整形数组,除了两个数字只出现一次外, 其他数字都是两次,找到这两个数字。{1,3,1,2,3,4}
解题思路:运用异或的方法:
1^1= 0
1^0= 1
0^1= 1
(1)对于出现两次的元素,使用“异或”操作后结果肯定为0,那么我们就可以遍历一遍数组,对所有元素使用异或操作,那么得到的结果就是两个出现一次的元素的异或结果。
(2)因为这两个元素不相等,所以异或的结果肯定不是0,也就是可以再异或的结果中找到1位不为0的位,例如异或结果的最后一位不为0。
(3)这样我们就可以最后一位将原数组元素分为两组,一组该位全为1,另一组该位全为0。
(4)再次遍历原数组,最后一位为0的一起异或,最后一位为1的一起异或,两组异或的结果分别对应着两个结果。
package kkee;
import java.util.Arrays;
/**
* @Package: kkee
* @Author:kkz
* @Description:
* @Date:Created in 2018/10/19 10:12
*/
public class ValueGroup {
public static void main(String[] args) {
int[] array = {1, 3, 1, 2, 3, 4};
int[] value = findNums(array);
System.out.println(Arrays.toString(value));
}
public static int[] findNums(int[] arr) {
if(arr.length < 2)
return arr;//判断数组长度是否满足题目要求,至少有3个数组元素
int[] result = new int[2]; //要返回的结果,即只出现一次的两个数字
int res = arr[0]; //第一次对所有元素进行亦或操作结果
for(int i=1; i<arr.length; i++) {
res ^= arr[i];
}
int bitIndex = 0;
for(int i=0; i<32; i++) { //找出异或结果为1的位。
if((res>>i & 1) == 1) {
bitIndex = i;
break;
}
}
for(int i=0; i<arr.length; i++) { //根据bitIndex为1,将元素分为两组
if((arr[i] >> bitIndex & 1) == 1)
result[0] ^= arr[i]; //对应位为1,亦或得到的结果
else
result[1] ^= arr[i]; //对应位为0,亦或得到的结果
}
return result;
}
}
[2, 4]
- 如何排序数组并插入某个元素?
package kkee;
import java.util.Arrays;
import java.util.Scanner;
public class NewArray {
public static void main(String[] args) {
int[] array = {9, 2, 4, 5};
Arrays.sort(array);
System.out.println(Arrays.toString(array));
Scanner input = new Scanner(System.in);
int[] barry = new int[array.length + 1]; //声明并初始化一个新的数组,插入一个数,长度加1
for (int i = 0;i < array.length;i ++){
barry[i] = array[i];
} //将原数组的元素赋给新数组
System.out.print("插入新的元素:");
int value = input.nextInt();
int index = array.length; //插入的数组在新数组的下标
barry[index] = value;
Arrays.sort(barry);
System.out.println("插入后的数组:"+Arrays.toString(barry));
[2, 4, 5, 9]
插入新的元素:8
插入后的数组:[2, 4, 5, 8, 9]
- 如何搜索数组中的最小值和最大元素?
package kkee;
public class NewArray {
public static void main(String[] args) {
int[] array = {9, 2, 4, 5};
// 查找最大元素
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max)
max = array[i];
}
//查找最小元素
int min = array[0];
for (int i = 0;i < array.length; i++){
if(array[i] < min)
min = array[i];
}
System.out.println("Max is " + max);
System.out.println("Min is " + min);
}
}
Max is 9
Min is 2
- 如何合并两个数组(合并到一个新的数组)?
package kkee;
import java.util.Arrays;
public class NewArray {
public static void main(String[] args) {
int[] array = {9, 2, 4, 5};
int[] carry = {2, 3, 4, 5, 6, 7};
int[] darry = new int[10];
System.arraycopy(array, 0, darry, 0,array.length);
System.arraycopy(carry, 0, darry, array.length,carry.length);
System.out.println("darry =" + Arrays.toString(darry));
}
}
darry =[9, 2, 4, 5, 2, 3, 4, 5, 6, 7]
- 如何填充数组(一次填充,部分填充)?
package kkee;
import java.util.Arrays;
public class NewArray {
public static void main(String[] args) {
int[] array = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5};
Arrays.fill(array,1,3,1); //起始索引包括,结束索引不包括 部分填充
System.out.println(Arrays.toString(array));
Arrays.fill(array, 2); //一次填充
System.out.println(Arrays.toString(array));
Arrays.fill(array, 0, 5, 3);
System.out.println(Arrays.toString(array));
}
}
[1, 1, 1, 2, 3, 3, 4, 4, 5, 5]
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
[3, 3, 3, 3, 3, 2, 2, 2, 2, 2]
- 如何删除数组指定元素?
package kkee;
import java.util.Arrays;
import java.util.Scanner;
public class NewArray {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int[] array = new int[]{1,2,4,5,9,8,0};
System.out.println(Arrays.toString(array));
System.out.println("输入要删除第几个元素:");
int n = sc.nextInt();
array[n-1] = array[array.length-1];//把最后一个元素替代指定删除的元素
array = Arrays.copyOf(array, array.length-1);//数组长度减一,再赋给原来的数组
System.out.println(Arrays.toString(array));
}
}
[1, 2, 4, 5, 9, 8, 0]
输入要删除第几个元素:
3
[1, 2, 0, 5, 9, 8]
- 如何从数组中查找常见的元素?数组有的可以查并返回下标,没有的返回-1。
public class OrderArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 11, 15, 17};
System.out.println("所查找元素在数组中的下标为:" + binarySearch(arr, 15, 0, 10));
System.out.println("所查找元素在数组中的下标为:" + binarySearch(arr, 25, 0, 10));
}
public static int binarySearch(int[] arr, int key,int start,int end) {
start = 0;
end = arr.length - 1;
while (start <= end) {
int middle = start + (end - start) / 2;
if (arr[middle] == key) {
return middle;
} else if (arr[middle] < key) {
start = middle + 1;
} else {
end = middle - 1;
}
}
return -1;
}
}
所查找元素在数组中的下标为:9
所查找元素在数组中的下标为:-1