Arrays
和 Collections
是分别操作数组和集合的两个工具类。今天就来对 Arrays
中的内容作个总结。
Arrays
类位于 java.util
包中。Arrays
继承 Object
java.lang.Object
? java.util.Arrays
Arrays
类中的静态方法可以对数组进行排序、查询、搜索等等操作。
Arrays.asList()
该方法返回一个 ArrayList , 其返回的 ArrayList 从下面的代码可以看出不是我们平常 new 出来的动态可扩展的 ArrayList。可以看这篇 ArrayList
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
/**
* @serial include
*/
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;
ArrayList(E[] array) {
a = Objects.requireNonNull(array);
}
@Override
public int size() {
return a.length;
}
@Override
public Object[] toArray() {
return a.clone();
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size)
return Arrays.copyOf(this.a, size,
(Class<? extends T[]>) a.getClass());
System.arraycopy(this.a, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
@Override
public E get(int index) {
return a[index];
}
@Override
public E set(int index, E element) {
E oldValue = a[index];
a[index] = element;
return oldValue;
}
@Override
public int indexOf(Object o) {
E[] a = this.a;
if (o == null) {
for (int i = 0; i < a.length; i++)
if (a[i] == null)
return i;
} else {
for (int i = 0; i < a.length; i++)
if (o.equals(a[i]))
return i;
}
return -1;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
public Spliterator<E> spliterator() {
return Spliterators.spliterator(a, Spliterator.ORDERED);
}
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
for (E e : a) {
action.accept(e);
}
}
@Override
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
E[] a = this.a;
for (int i = 0; i < a.length; i++) {
a[i] = operator.apply(a[i]);
}
}
@Override
public void sort(Comparator<? super E> c) {
Arrays.sort(a, c);
}
}
public static void main(String[] args) {
//创建一个数组
int[] a = {1,2,3};
//new 一个 ArrayList
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list);//[1, 2, 3]
System.out.println(a); //[I@1540e19d
System.out.println(Arrays.toString(a));//[1, 2, 3]
/*如果将基本数据类型的数组作为参数传入,该方法会把整个数组当成一个元素*/
System.out.println(Arrays.asList(a));//[[I@1540e19d]
System.out.println(Arrays.asList(1,2,3));//[1, 2, 3]
}
Arrays.sort(originalArray)
对数组所有元素进行升序排序,没有返回值。
int[] a = {1,2,3,9,4,5,6,7,8};
Arrays.sort(a);
System.out.println(Arrays.toString(a));//[1, 2, 3, 4, 5, 6, 7, 8, 9]
Arrays.sort(originalArray, fromIndex, endIndex)
对数组特定序列进行升序排序,从 [fromIndex, endIndex]区域的数组元素进行排序
int[] a = {1,2,3,9,4,5,6,7,8};
Arrays.sort(a,0,5);
System.out.println(Arrays.toString(a));//[1, 2, 3, 4, 9, 5, 6, 7, 8]
Arrays.sort(T[] a, Comparator<super T> c )
利用自定义的比较器,来对数组元素进行排序
// Java program to demonstrate working of Comparator
// interface
import java.util.*;
import java.lang.*;
import java.io.*;
// A class to represent a student.
class Student {
int rollno;
String name, address;
// Constructor
public Student(int rollno, String name,
String address)
{
this.rollno = rollno;
this.name = name;
this.address = address;
}
// Used to print student details in main()
public String toString()
{
return this.rollno + " "
+ this.name + " "
+ this.address;
}
}
//自定义的比较器,对两个对象的 rollno 属性进行比较
class Sortbyroll implements Comparator<Student> {
// Used for sorting in ascending order of
// roll number
public int compare(Student a, Student b)
{
return a.rollno - b.rollno;
}
}
// Driver class
class Main {
public static void main(String[] args)
{
Student[] arr = { new Student(1, "bbbb", "london"),
new Student(3, "aaaa", "nyc"),
new Student(2, "cccc", "jaipur") };
System.out.println("Unsorted-未排序前");
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
Arrays.sort(arr, new Sortbyroll());
System.out.println("\nSorted by rollno-排序后");
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
/** 输出结果:
*Unsorted-未排序前
*1 bbbb london
*3 aaaa nyc
*2 cccc jaipur
*
*Sorted by rollno-排序后
*1 bbbb london
*2 cccc jaipur
*3 aaaa nyc
*
**/
Arrays.sort(T[] a, int fromIndex, int toIndex, Comparator<super T> c)
利用自定义的比较器,来对数组中指定范围元素进行排序
把4中代码换成
Arrays.sort(arr, 1, 2, new Sortbyroll());//对第一、二个元素进行比较
/** 输出结果:
*Unsorted-未排序前
*1 bbbb london
*3 aaaa nyc
*2 cccc jaipur
*
*Sorted by rollno-排序后
*1 bbbb london
*3 aaaa nyc
*2 cccc jaipur
*
**/
Arrays.parallelSort(originalArray)
对数组元素进行升序排序,当数据规模较大时,性能更好(并行排序)。
int[] a = {1,2,3,9,4,5,6,7,8};
Arrays.parallelSort(a);
System.out.println(Arrays.toString(a));//[1, 2, 3, 4, 9, 5, 6, 7, 8]
Arrays.fill(originalArray, fillValue)
和 Arrays.fill(originalArray, intfromIndex, int toIndex, fillValue)
用 fillValue 值来填充数组。前一个函数填充所有,后面的函数填充指定范围。
int[] a = {1,2,3,9,4,5,6,7,8};
Arrays.fill(a,1);//[1, 1, 1, 1, 1, 1, 1, 1, 1]
Arrays.fill(a,1,3,1);//[1, 1, 1, 9, 4, 5, 6, 7, 8]
Arrays.equals(array1, array2)
和 Arrays.deepEquals(array1, array2)
判断两个数组是否相等, 返回布尔值
equals()
主要针对基本数据和Object 一维数组,其比较规则如下:
if (a==a2)
return 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++) {
Object o1 = a[i];
Object o2 = a2[i];
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return true;
deepEquals()
主要是多维数组的比较,其比较规则为:
if (a1 == a2)
return true;
if (a1 == null || a2==null)
return false;
int length = a1.length;
if (a2.length != length)
return false;
for (int i = 0; i < length; i++) {
Object e1 = a1[i];
Object e2 = a2[i];
if (e1 == e2)
continue;
if (e1 == null)
return false;
// Figure out whether the two elements are equal
boolean eq = deepEquals0(e1, e2);
if (!eq)
return false;
}
int[] a = {1,2,3,9,4,5,6,7,8};
int[] b = {1,2};
int[][] c = {{1,2},{1,3}};
int[][] d = {{1,2},{1,3}};
Arrays.equals(a,b);//false
Arrays.equals(c,d);//true
Arrays.hashCode(originalArray)
和 Arrays.deepHashCode(originalArray)
返回该数组的哈希值
前面一个函数是返回一维数组,后面是多维数组
int[] a = {1,2,3,9,4,5,6,7,8};
int[][] c = {{1,2},{1,3}};
System.out.println(Arrays.hashCode(a));//887857437
System.out.println(Arrays.deepHashCode(c));//31776
Arrays.binarySearch(originalArray, key)
和Arrays.binarySearch(originalArray,fromIndex,toIndex,key,Comparator)
方法一:在数组中对某值进行二分查找(注意要先对数组排序!),如果存在返回其下标,否则返回 -(数组极值下标 +1)。
方法二:方法中的参数限定数组的范围,Comparator 是自定义的比较器
int[] a = {1,2,3,4,5,9,6,7,8};
Arrays.sort(a);
System.out.println(Arrays.binarySearch(a,1));//0
System.out.println(Arrays.binarySearch(a,0));//-1
System.out.println(Arrays.binarySearch(a,10));//-10
Arrays.copyOf(originalArray, newLength)
和 Arrays.copyOfRange(originalArray,fromIndex,endIndex)
方法一:拷贝数组,newLength 是拷贝的长度,如果超过原数组的长度,则用 null 进行填充。并返回一个新数组。
方法二:拷贝数组,fromIndex 和 endIndex 是数组的范围下标。并返回一个新数组。
int[] a = {1,2,3,9,4,5,6,7,8};
System.out.println(Arrays.toString(Arrays.copyOf(a,3)));//[1,2,3]
System.out.println(Arrays.toString(Arrays.copyOfRange(a,0,3)));//[1,2,3]
Arrays.toString(originalArray)
和 Arrays.deepToString(originalArray)
返回数组元素的字符串形式,方法一是一维数组,方法二是多维数组。
int[] a = {1,2,3,9,4,5,6,7,8};
System.out.println(Arrays.toString(a));//[1,2,3,9,4,5,6,7,8]
int[][] c = {{1,2},{3}};
System.out.println(Arrays.deepToString(c));//[[1, 2], [3]]
Arrays.setAll(originalArray,functionalGenerator)
和 Arrays.parallelSetAll(originalArray, functionalGenerator)
方法一:将数组中的所有元素,串行的使用方法提供的生成器函数来计算每个元素(一元操作)
方法二:将数组中的所有元素,串行的使用方法提供的生成器来计算每个元素(一元操作)适用于大规模数据
int[] a = {1,2,3,9,4,5,6,7,8};
Arrays.setAll(a, i -> a[i] * 2);
System.out.println(Arrays.toString(a));//[2,4,6,18,8,10,12,14,16]
Arrays.parallelSetAll(a, i -> a[i] * 2);
System.out.println(Arrays.toString(a));//[2,4,6,18,8,10,12,14,16]
Arrays.parallelPrefix(originalArray, BinaryOperator op)
和 Arrays.parallelPrefix(originalArray, int fromIndex, int toIndex, BinaryOperator op)
方法一:将数组中所有元素,并行使用生成器函数来计算每个元素(二元操作)
方法二:将数组中部分序列元素,并行使用生成器函数来计算每个元素(二元操作)
int[] a = {1,2,3,9,4,5,6,7,8};
Arrays.parallelPrefix(a, (x,y) -> x*y);//依次累乘
System.out.println(Arrays.toString(a));//[1, 2, 6, 54, 216, 1080, 6480, 45360, 362880]
Arrays.parallelPrefix(a, 0, 3, (x,y) -> x*y);//依次累乘
System.out.println(Arrays.toString(a));//[1, 2, 6, 9, 4, 5, 6, 7, 8]
Arrays.spliterator(originalArray)
和 Arrays.spliterator(originalArray,fromIndex,endIndex)
返回数组的分片迭代器,用于并行的遍历数组
int[] a = {1,2,3,9,4,5,6,7,8};
Spliterator<Integer> s = Arrays.spliterator(a);
s.forEachRemaining(System.out::println);
/**
*
*1
*2
*3
*9
*4
*5
*6
*7
*8
**/
Arrays.stream(originalArray)
返回数组的流,可以对数组使用 Stream 相关的方法。
int[] a = {1,2,3,9,4,5,6,7,8};
List<Integer> list = Arrays.stream(a).collect(toList());
System.out.println(list);//[1,2,3,9,4,5,6,7,]