Arrays&Collections总结

来源:互联网 发布:淘宝直通车使用条件 编辑:程序博客网 时间:2024/05/17 03:56

Java中最常用的容器就是数组和Collection子类容器,并且数组和Collection可以相互转换,这样他们基本上可以共享彼此的方法。为方便对他们进行操作,java.util包中提供了两个工具类,java.utils.Arrays用于对数组进行操作,java.utils.Collections用于操作Collection,工具类基本上都是static方法,并且针对不同的类型会进行方法重载。下面我们分别看看这两个工具类提供的主要方法。

Arrays

不同于Collection只能存Object,数组中既可以存Object,也能存原生类型char,byte,short,int,long,float,double,boolean,因此,Arrays中的辅助方法包含基础类型,Object及泛型重载,一般静态辅助方法第一个参数是操作的数组,因数组可以指定下标范围,辅助方法一般也有一个指定start和end范围的重载形式。

针对数组,首先就是查找和排序。

二分查找

二分查找需数组有序

//Primitiv Typepublic static int binarySearch(char[] a, char key);public static int binarySearch(char[] a, int fromIndex, int toIndex, char key);......//objectpublic static int binarySearch(Object[] a, Object key)public static int binarySearch(Object[] a, int fromIndex, int toIndex,                               Object key) //泛型T,需指定Comparatorpublic static <T> int binarySearch(T[] a, T key, Comparator<? super T> c);public static <T> int binarySearch(T[] a, int fromIndex, int toIndex,                                   T key, Comparator<? super T> c)

排序

排序与二分查找参数形式相同,采用DualPivotQuicksort排序方式,直接将原数组变成有序,jdk8还增加了parallelSort并行排序。

public static void sort(char[] a);public static void sort(char[] a, int fromIndex, int toIndex);public static void sort(Object[] a);public static void sort(Object[] a, int fromIndex, int toIndex);public static <T> void sort(T[] a, Comparator<? super T> c);public static <T> void sort(T[] a, int fromIndex, int toIndex,                                         Comparator<? super T> c);

Object方法

如果将数组类比Object,则数组应该具备Object的基本方法, hashCode 、toString、equals,此时参数则为所有基本类型数组以及Object数组。

hashCode

形式固定,每个元素对hash code产生影响。

public static int hashCode(int a[]) {    if (a == null)        return 0;    int result = 1;    for (int element : a)        result = 31 * result + element;    return result;}

deepHashCode版本对数组中元素是数组的做递归处理

public static int deepHashCode(Object a[]) {    if (a == null)        return 0;    int result = 1;    for (Object element : a) {        int elementHash = 0;        if (element instanceof Object[])            elementHash = deepHashCode((Object[]) element);        else if (element instanceof byte[])            elementHash = hashCode((byte[]) element);        else if (element instanceof short[])            elementHash = hashCode((short[]) element);        else if (element instanceof int[])            elementHash = hashCode((int[]) element);        else if (element instanceof long[])            elementHash = hashCode((long[]) element);        else if (element instanceof char[])            elementHash = hashCode((char[]) element);        else if (element instanceof float[])            elementHash = hashCode((float[]) element);        else if (element instanceof double[])            elementHash = hashCode((double[]) element);        else if (element instanceof boolean[])            elementHash = hashCode((boolean[]) element);        else if (element != null)            elementHash = element.hashCode();        result = 31 * result + elementHash;    }    return result;}

toStrinig

toString使用[]括起所有元素,元素间用逗号分隔

public static String toString(int[] a) {    if (a == null)        return "null";    int iMax = a.length - 1;    if (iMax == -1)        return "[]";    StringBuilder b = new StringBuilder();    b.append('[');    for (int i = 0; ; i++) {        b.append(a[i]);        if (i == iMax)            return b.append(']').toString();        b.append(", ");    }}

deepToString同deepHashCode,对数组中元素是数组的递归处理

equals

调用数组元素equls方法,依次比较每一个元素

public static boolean equals(boolean[] a, boolean[] a2);

deepEquals同deepHashCode,对数组中元素是数组的递归处理

填充

使用指定值填充整个数组或填充固定范围

public static void fill(byte[] a, byte val) {    for (int i = 0, len = a.length; i < len; i++)        a[i] = val;}public static void fill(byte[] a, int fromIndex, int toIndex, byte val) {    rangeCheck(a.length, fromIndex, toIndex);    for (int i = fromIndex; i < toIndex; i++)        a[i] = val;}

复制

copyOf使用System.arraycopy复制指定长度数据

public static float[] copyOf(float[] original, int newLength) {    float[] copy = new float[newLength];    System.arraycopy(original, 0, copy, 0,                     Math.min(original.length, newLength));    return copy;}

copyOfRange复制指定范围数据

public static float[] copyOfRange(float[] original, int from, int to) {    int newLength = to - from;    if (newLength < 0)        throw new IllegalArgumentException(from + " > " + to);    float[] copy = new float[newLength];    System.arraycopy(original, from, copy, 0,                     Math.min(original.length - from, newLength));    return copy;}

Collections

Collections主要是操作List/Set/Map,由于Collection本身已有CRUD相关方法,Collections主要用于返回Collection的属性或者固化其属性以及集合间操作。

增加查找排序

public static <T> boolean addAll(Collection<? super T> c, T... elements);//二分查找需List有序int binarySearch(List<? extends Comparable<? super T>> list, T key);//排序public static <T extends Comparable<? super T>> void sort(List<T> list);//替换public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal)

返回属性

//获取元素重复个数public static int frequency(Collection<?> c, Object o)//获取最大值public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)//获取最小值public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp)

Empty

返回单例空容器

public static <T> Iterator<T> emptyIterator() {    return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;}

Singleton

返回只有一个元素的常量容器,不能对容器增删该

public static <T> Set<T> singleton(T o) {    return new SingletonSet<>(o);}

Unmodifiable

返回容器常量形式,外层加proxy,增删该抛出UnsupportedOperationException。

public static <T> List<T> unmodifiableList(List<? extends T> list) {    return (list instanceof RandomAccess ?            new UnmodifiableRandomAccessList<>(list) :            new UnmodifiableList<>(list));}

Synchronize

容器默认一般是线程非安全的,返回线程安全容器

public static <T> Collection<T> synchronizedCollection(Collection<T> c) {    return new SynchronizedCollection<>(c);}static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {    return new SynchronizedCollection<>(c, mutex);}

Checked

每次添加或修改时都检查元素类型

public static <E> Collection<E> checkedCollection(Collection<E> c,Class<E> type)

reverse&rotate&shuffle

//反转容器public static void reverse(List<?> list);//移位public static void rotate(List<?> list, int distance)//随机化public static void shuffle(List<?> list)

copy&fill&disjoint&nCopies

//copy到另一listpublic static <T> void copy(List<? super T> dest, List<? extends T> src)//判断是否有交集public static boolean disjoint(Collection<?> c1, Collection<?> c2) //填充public static <T> void fill(List<? super T> list, T obj) //返回含n个相同元素的容器public static <T> List<T> nCopies(int n, T o)

Array&Collection 互转

Array转Collection

Array转Collection是底层数据共享,返回ArrayList类型view。

public static <T> List<T> asList(T... a)

Collection转Array

Collection转Array是通过自身toArray接口实现的,通用实现就是new一个Array,迭代Collection依次赋值。然而具体Collection内部存储方式不同,Collection实体类则可能重载toArray方法,比如ArrayList本身内部就是数组,直接使用System.arrayCopy则更高效。