数组实用方法

Array类

java.util.Array

常用的方法

fill(type[] a, type val) : 给数组填充,就是简单地把一个数组全部或者某

段数据填成一个特殊的值。

equals(type[] a, type[] b) : 实现两个数组的比较,相等时返回true;

sort(type[] a) : 对数组排序;

binarySearch() :对数组元素进行二分查找;

asList(T... a) : 实现数组到ArrayList的转换;

抽象的T类型,任何数组都可以转换。

例:数组的填充和复制


package com.xuetang.four;

import java.util.Arrays;

/**
 * @author WuRoc
 * @GitHub www.github.com/WuRoc
 * @version 1.0
 * @2020年9月3日
 * import static com.wuroc.util.Print.*;
 * 
 */
public class CopyingArrays {
	public static void main(String[] args) {
		int[] i = new int[25];
		int[] j = new int[25];
		
		Arrays.fill(i,47);
		Arrays.fill(j,99);
		
		System.arraycopy(i, 0, j, 0, i.length);
		int[] k =new int[10];
		Arrays.fill(k, 103);
		System.arraycopy(i, 0, k, 0, k.length);
		Arrays.fill(k, 103);
		System.arraycopy(k, 0, i, 0, k.length);
		
		Integer[] u = new Integer[10];
		Integer[] v = new Integer[5];
		Arrays.fill(u, new Integer(47));     
		Arrays.fill(v, new Integer(99));
		System.arraycopy(v, 0, u, u.length/2, v.length);
		
	}

}

例:数组的比较

//: ComparingArrays.java

package com.xuetang.four;

import java.util.Arrays;

/**
 * @author WuRoc
 * @GitHub www.github.com/WuRoc
 * @version 1.0
 * @2020年9月3日
 * import static com.wuroc.util.Print.*;
 * 
 */
public class ComparingArrays {
	public static void main(String[] args) {
		int[] a1 = new int[10];
		int[] a2 = new int[10];
		
		Arrays.fill(a1, 47);
		Arrays.fill(a2, 47);
		
		System.out.println(Arrays.equals(a1, a2));
		a2[3] = 11;
		System.out.println(Arrays.equals(a1, a2));
		String[] s1 = new String[5];
		Arrays.fill(s1, "Hi");
		String[] s2 = {"Hi", "Hi", "Hi", "Hi","Hi"};
		System.out.println(Arrays.equals(s1, s2));
	}

}
如有错误,恳求读者指出,发送到wu13213786609@outlook.com。
原文地址:https://www.cnblogs.com/WLCYSYS/p/13608422.html