Java集合

Java集合

Java版本:11.02

泛型编程

  • 通常情况下集合中可以存放不同类型的对象,是因为将所有对象都看做Object类型放入的,因此从集合中取出元素时也是Object类型,为了表达该元素真实的数据类型,则需要强制类型转换,而强制类型转换可能会引发类型转换异常。
  • 为了避免上述错误的发生,从Java5开始增加泛型机制,也就是在集合名称的右侧使用<数据类型>的方式来明确要求该集合中可以存放的元素类型,若放入其它类型的元素则编译报错。
  • 泛型只在编译时期有效,在运行时期不区分是什么类型。

原理

  • 泛型的本质就是类型参数化,也就是让数据类型作为参数传递,其中E相当于形式参数负责占位,而使用集合时<>中的数据类型相当于实际参数,用于给形式参数E进行初始化,从而使得集合中所有的E被实际参数替换,由于实际参数可以传递各种各样广泛的数据类型,因此得名为泛型。

  • 泛型接口和普通接口的区别就是后面添加了类型参数列表,可以有多个类型参数,如:<E, T, .. >等。

  • 实例化泛型类时应该指定具体的数据类型,并且是引用数据类型而不是基本数据类型。

  • 父类有泛型,子类可以选择保留泛型也可以选择指定泛型类型

  • 子类必须是“富二代”,子类除了指定或保留父类的泛型,还可以增加自己的泛型。

通配符

有时候我们希望传入的类型在一个指定的范围内,此时就可以使用泛型通配符了。例如:之前传入的类型要求为Integer类型,但是后来业务需要Integer的父类Number类也可以传入。

泛型中有三种通配符形式:

  • <?> 无限制通配符:表示我们可以传入任意类型的参数。
  • <? extends E> 表示类型的上界是E,只能是E或者是E的子类。
  • <? super E> 表示类型的下界是E,只能是E或者是E的父类。
List<?>

List<?>不支持元素添加,但可以用于取元素,当作Object处理。
请添加图片描述

public class Animal {
    private String name;

    public Animal() {
    }

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "I'm an Animal, my name is " + name;
    }
}

public class Cat extends Animal{
    public Cat(String name) {
        super(name);
    }

    public void bark() {
        System.out.println("mio, mio, mio~~~");
    }
}

获取测试:

public class GenericTest {
    @Test
    public void genericInheritance() {
        List<Cat> cats = new LinkedList<>();
        cats.add(new Cat("suger"));
        List<?> list = new LinkedList<>();
        list = cats; // List<Cat>可以转换为?
        System.out.println(list.get(0));
    }
}
List<? extends Animal>

请添加图片描述

public class GenericTest {
    @Test
    public void run() {
        People<Integer> p = new People<>("alex", 30, 1);
        System.out.println(p);
    }

    @Test
    public void genericInheritance() {
        List<Cat> cats = new LinkedList<>();
        cats.add(new Cat("suger"));
        List<? extends Animal> l2 = new LinkedList<>();
        l2 = cats;
        System.out.println(l2.get(0)); // 可以获取
//        l2.add(new Animal("alex")); // 类型匹配错误
    }
}
List<? super Animal>

请添加图片描述

public class GenericTest {
    @Test
    public void run() {
        People<Integer> p = new People<>("alex", 30, 1);
        System.out.println(p);
    }

    @Test
    public void genericInheritance() {
        List<? super Animal> l3 = new LinkedList<>();
        l3.add(new Ojbect()); // 类型匹配错误
        l3.add(new Cat("suger"));
        System.out.println(l3.get(0));
    }
}

请添加图片描述

自定义泛型

  • 泛型方法就是我们输入参数的时候,输入的是泛型参数,而不是具体的参数。我们在调用这个泛型方法的时需要对泛型参数进行实例化。
  • 泛型方法的格式:
    [访问权限] <泛型> 返回值类型 方法名([泛型标识 参数名称]) { 方法体; }
  • 在静态方法中使用泛型参数的时候,需要我们把静态方法定义为泛型方法。

泛型类

public class People<T> {
    private String name;
    private int age;
    private T gender;

    public People(String name, int age, T gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public People() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public T getGender() {
        return gender;
    }

    public void setGender(T gender) {
        this.gender = gender;
    }
    @Override
    public String toString() {
        return "People{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                '}';
    }
}

不指定类型时,当作Object

People p = new People("alex", 30, 1); // 第三个参数可以传入Object或其子类

泛型继承

  1. 擦除泛型,也不指定泛型类型

    public class SubPeople extends People{ // 丢弃泛型,也不指定泛型类型,泛型类型默认为Object
    }
    
  2. 擦除泛型,但指定泛型类型为String

    public class SubPeople extends People<String> {
    }
    
  3. 保留泛型T

    public class SubPeople<T> extends People<T> {
    }
    
  4. 保留父类泛型T,添加泛型类型E

    public class SubPeople<T, E> extends People<T> {
    }
    

BA的子类或子接口,而G<T>是泛型类或接口,则G<B>并不是G<A>的子类型。

泛型方法(参数中有泛型)

  1. 使用类的泛型

    public class SubPeople<T, E> extends People<T> {
        public void add(T p1, E p2) {
        }
    }
    
  2. 新增方法独立泛型

    public class SubPeople<T, E> extends People<T> {
        public <T1> void add(T1 p1) {
        }
    }
    

静态方法不能使用类的泛型 - 类的泛型,在实例化时指定,而静态方法直接通过类调用,无需实例化。

public class SubPeople<T, E> extends People<T> {
    public static void add(T p1) {
    }
}

编译错误:
请添加图片描述
只能使用方法独有泛型

public class SubPeople<T, E> extends People<T> {
    public static <T1> void add(T1 p1) {
    }
}

Java两大集合接口

  • Collection<E> - 数组
    请添加图片描述

  • Map<K,V> - 键值对
    请添加图片描述

Collection<E>接口

public interface Collection<E>
extends Iterable<E>

Methods

Modifier and TypeMethodDescription
booleanadd(E e)Ensures that this collection contains the specified element (optional operation).
booleanaddAll(Collection<? extends E> c)Adds all of the elements in the specified collection to this collection (optional operation).
voidclear()Removes all of the elements from this collection (optional operation).
booleancontains(Object o)Returns true if this collection contains the specified element.
booleancontainsAll(Collection<?> c)Returns true if this collection contains all of the elements in the specified collection.
booleanequals(Object o)Compares the specified object with this collection for equality.
default voidforEach(Consumer<? super T> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. (Inherited from Iterable)
inthashCode()Returns the hash code value for this collection.
booleanisEmpty()Returns true if this collection contains no elements.
Iterator<E>iterator()Returns an iterator over the elements in this collection.
default Stream<E>parallelStream()Returns a possibly parallel Stream with this collection as its source.
booleanremove(Object o)Removes a single instance of the specified element from this collection, if it is present (optional operation).
booleanremoveAll(Collection<?> c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
default booleanremoveIf(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
booleanretainAll(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
intsize()Returns the number of elements in this collection.
default Spliterator<E>spliterator()Creates a Spliterator over the elements in this collection.
default Stream<E>stream()Returns a sequential Stream with this collection as its source.
Object[]toArray()Returns an array containing all of the elements in this collection.
default <T> T[]toArray(IntFunction<T[]> generator)Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
@Test
public void addElements() {
    Collection<String> col = new ArrayList<>(); // 接口类引用指向其实现类,形成多态
    col.add("one");
    col.add("three");
    System.out.println(col); // [one, three]
    Collection<String> col2 = new ArrayList<>();
    col2.add("two");
    col.addAll(col2);
    System.out.println(col); // [one, three, two]
}

List<E>接口

public interface List<E>
extends Collection<E>

请添加图片描述

Methods

Modifier and TypeMethodDescription
voidadd(int index, E element)Inserts the specified element at the specified position in this list (optional operation).
booleanadd(E e)Appends the specified element to the end of this list (optional operation).
booleanaddAll(int index, Collection<? extends E> c)Inserts all of the elements in the specified collection into this list at the specified position (optional operation).
booleanaddAll(Collection<? extends E> c)Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator (optional operation).
voidclear()Removes all of the elements from this list (optional operation).
booleancontains(Object o)Returns true if this list contains the specified element.
booleancontainsAll(Collection<?> c)Returns true if this list contains all of the elements of the specified collection.
static <E> List<E>copyOf(Collection<? extends E> coll)Returns an unmodifiable List containing the elements of the given Collection, in its iteration order.
booleanequals(Object o)Compares the specified object with this list for equality.
Eget(int index)Returns the element at the specified position in this list.
inthashCode()Returns the hash code value for this list.
intindexOf(Object o)Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
booleanisEmpty()Returns true if this list contains no elements.
Iterator<E>iterator()Returns an iterator over the elements in this list in proper sequence.
intlastIndexOf(Object o)Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
ListIterator<E>listIterator()Returns a list iterator over the elements in this list (in proper sequence).
ListIterator<E>listIterator(int index)Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
static <E> List<E>of()Returns an unmodifiable list containing zero elements.
static <E> List<E>of(E e1)Returns an unmodifiable list containing one element.
static <E> List<E>of(E... elements)Returns an unmodifiable list containing an arbitrary number of elements.
static <E> List<E>of(E e1, E e2)Returns an unmodifiable list containing two elements.
static <E> List<E>of(E e1, E e2, E e3)Returns an unmodifiable list containing three elements.
static <E> List<E>of(E e1, E e2, E e3, E e4)Returns an unmodifiable list containing four elements.
static <E> List<E>of(E e1, E e2, E e3, E e4, E e5)Returns an unmodifiable list containing five elements.
static <E> List<E>of(E e1, E e2, E e3, E e4, E e5, E e6)Returns an unmodifiable list containing six elements.
static <E> List<E>of(E e1, E e2, E e3, E e4, E e5, E e6, E e7)Returns an unmodifiable list containing seven elements.
static <E> List<E>of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8)Returns an unmodifiable list containing eight elements.
static <E> List<E>of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)Returns an unmodifiable list containing nine elements.
static <E> List<E>of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)Returns an unmodifiable list containing ten elements.
Eremove(int index)Removes the element at the specified position in this list (optional operation).
booleanremove(Object o)Removes the first occurrence of the specified element from this list, if it is present (optional operation).
booleanremoveAll(Collection<?> c)Removes from this list all of its elements that are contained in the specified collection (optional operation).
default voidreplaceAll(UnaryOperator<E> operator)Replaces each element of this list with the result of applying the operator to that element.
booleanretainAll(Collection<?> c)Retains only the elements in this list that are contained in the specified collection (optional operation).
Eset(int index, E element)Replaces the element at the specified position in this list with the specified element (optional operation).
intsize()Returns the number of elements in this list.
default voidsort(Comparator<? super E> c)Sorts this list according to the order induced by the specified Comparator.
default Spliterator<E>spliterator()Creates a Spliterator over the elements in this list.
List<E>subList(int fromIndex, int toIndex)Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Object[]toArray()Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
ArrayList<E>
public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable

请添加图片描述

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. This class is roughly equivalent to Vector, except that it is unsynchronized.

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically - 1.5x by default.

	/**
     * Returns a capacity at least as large as the given minimum capacity.
     * Returns the current capacity increased by 50% if that suffices.
     * Will not return a capacity greater than MAX_ARRAY_SIZE unless
     * the given minimum capacity is greater than MAX_ARRAY_SIZE.
     *
     * @param minCapacity the desired minimum capacity
     * @throws OutOfMemoryError if minCapacity is less than zero
     */
    private int newCapacity(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity <= 0) {
            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                return Math.max(DEFAULT_CAPACITY, minCapacity);
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
            return minCapacity;
        }
        return (newCapacity - MAX_ARRAY_SIZE <= 0)
            ? newCapacity
            : hugeCapacity(minCapacity);
    }

Constructors

ConstructorDescription
ArrayList()Constructs an empty list with an initial capacity of ten.
ArrayList(int initialCapacity)Constructs an empty list with the specified initial capacity.
ArrayList(Collection<? extends E> c)Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

Methods

Modifier and TypeMethodDescription
voidadd(int index, E element)Inserts the specified element at the specified position in this list.
booleanadd(E e)Appends the specified element to the end of this list.
booleanaddAll(int index, Collection<? extends E> c)Inserts all of the elements in the specified collection into this list, starting at the specified position.
booleanaddAll(Collection<? extends E> c)Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator.
voidclear()Removes all of the elements from this list.
Objectclone()Returns a shallow copy of this ArrayList instance.
booleancontains(Object o)Returns true if this list contains the specified element.
voidensureCapacity(int minCapacity)Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
voidforEach(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
Eget(int index)Returns the element at the specified position in this list.
intindexOf(Object o)Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
booleanisEmpty()Returns true if this list contains no elements.
Iterator<E>iterator()Returns an iterator over the elements in this list in proper sequence.
intlastIndexOf(Object o)Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
ListIterator<E>listIterator()Returns a list iterator over the elements in this list (in proper sequence).
ListIterator<E>listIterator(int index)Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
Eremove(int index)Removes the element at the specified position in this list.
booleanremove(Object o)Removes the first occurrence of the specified element from this list, if it is present.
booleanremoveAll(Collection<?> c)Removes from this list all of its elements that are contained in the specified collection.
booleanremoveIf(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
protected voidremoveRange(int fromIndex, int toIndex)Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
booleanretainAll(Collection<?> c)Retains only the elements in this list that are contained in the specified collection.
Eset(int index, E element)Replaces the element at the specified position in this list with the specified element.
intsize()Returns the number of elements in this list.
Spliterator<E>spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this list.
List<E>subList(int fromIndex, int toIndex)Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Object[]toArray()Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
voidtrimToSize()Trims the capacity of this ArrayList instance to be the list’s current size.

Methods declared in AbstractList<E>

equals, hashCode

Inherited from AbstractCollection<E>

Modifier and TypeMethodDescription
booleancontainsAll(Collection<?> c)Returns true if this collection contains all of the elements in the specified collection.
StringtoString()Returns a string representation of this collection.
Vector<E>
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable

The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.

Constructors

ConstructorDescription
Vector()Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.
Vector(int initialCapacity)Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero.
Vector(int initialCapacity, int capacityIncrement)Constructs an empty vector with the specified initial capacity and capacity increment.
Vector(Collection<? extends E> c)Constructs a vector containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

Methods

Modifier and TypeMethodDescription
voidadd(int index, E element)Inserts the specified element at the specified position in this Vector.
booleanadd(E e)Appends the specified element to the end of this Vector.
booleanaddAll(int index, Collection<? extends E> c)Inserts all of the elements in the specified Collection into this Vector at the specified position.
booleanaddAll(Collection<? extends E> c)Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection’s Iterator.
voidaddElement(E obj)Adds the specified component to the end of this vector, increasing its size by one.
intcapacity()Returns the current capacity of this vector.
voidclear()Removes all of the elements from this Vector.
Objectclone()Returns a clone of this vector.
booleancontains(Object o)Returns true if this vector contains the specified element.
booleancontainsAll(Collection<?> c)Returns true if this Vector contains all of the elements in the specified Collection.
voidcopyInto(Object[] anArray)Copies the components of this vector into the specified array.
EelementAt(int index)Returns the component at the specified index.
Enumeration<E>elements()Returns an enumeration of the components of this vector.
voidensureCapacity(int minCapacity)Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
booleanequals(Object o)Compares the specified Object with this Vector for equality.
EfirstElement()Returns the first component (the item at index 0) of this vector.
voidforEach(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
Eget(int index)Returns the element at the specified position in this Vector.
inthashCode()Returns the hash code value for this Vector.
intindexOf(Object o)Returns the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element.
intindexOf(Object o, int index)Returns the index of the first occurrence of the specified element in this vector, searching forwards from index, or returns -1 if the element is not found.
voidinsertElementAt(E obj, int index)Inserts the specified object as a component in this vector at the specified index.
booleanisEmpty()Tests if this vector has no components.
Iterator<E>iterator()Returns an iterator over the elements in this list in proper sequence.
ElastElement()Returns the last component of the vector.
intlastIndexOf(Object o)Returns the index of the last occurrence of the specified element in this vector, or -1 if this vector does not contain the element.
intlastIndexOf(Object o, int index)Returns the index of the last occurrence of the specified element in this vector, searching backwards from index, or returns -1 if the element is not found.
ListIterator<E>listIterator()Returns a list iterator over the elements in this list (in proper sequence).
ListIterator<E>listIterator(int index)Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
Eremove(int index)Removes the element at the specified position in this Vector.
booleanremove(Object o)Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged.
booleanremoveAll(Collection<?> c)Removes from this Vector all of its elements that are contained in the specified Collection.
voidremoveAllElements()Removes all components from this vector and sets its size to zero.
booleanremoveElement(Object obj)Removes the first (lowest-indexed) occurrence of the argument from this vector.
voidremoveElementAt(int index)Deletes the component at the specified index.
booleanremoveIf(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
protected voidremoveRange(int fromIndex, int toIndex)Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
voidreplaceAll(UnaryOperator<E> operator)Replaces each element of this list with the result of applying the operator to that element.
booleanretainAll(Collection<?> c)Retains only the elements in this Vector that are contained in the specified Collection.
Eset(int index, E element)Replaces the element at the specified position in this Vector with the specified element.
voidsetElementAt(E obj, int index)Sets the component at the specified index of this vector to be the specified object.
voidsetSize(int newSize)Sets the size of this vector.
intsize()Returns the number of components in this vector.
Spliterator<E>spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this list.
List<E>subList(int fromIndex, int toIndex)Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.
Object[]toArray()Returns an array containing all of the elements in this Vector in the correct order.
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.
StringtoString()Returns a string representation of this Vector, containing the String representation of each element.
voidtrimToSize()Trims the capacity of this vector to be the vector’s current size.
Stack<E>
public class Stack<E>
extends Vector<E>

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top.

When a stack is first created, it contains no items.

A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class. For example:

Deque<Integer> stack = new ArrayDeque<Integer>();

Constructor

ConstructorDescription
Stack()Creates an empty Stack.

Methods

Modifier and TypeMethodDescription
booleanempty()Tests if this stack is empty.
Epeek()Looks at the object at the top of this stack without removing it from the stack.
Epop()Removes the object at the top of this stack and returns that object as the value of this function.
Epush(E item)Pushes an item onto the top of this stack.
intsearch(Object o)Returns the 1-based position where an object is on this stack.
LinkedList<E>
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, Serializable

请添加图片描述

Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).

Note that this implementation is not synchronized.

Constructors

ConstructorDescription
LinkedList()Constructs an empty list.
LinkedList(Collection<? extends E> c)Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

Methods

Modifier and TypeMethodDescription
voidadd(int index, E element)Inserts the specified element at the specified position in this list.
booleanadd(E e)Appends the specified element to the end of this list.
booleanaddAll(int index, Collection<? extends E> c)Inserts all of the elements in the specified collection into this list, starting at the specified position.
booleanaddAll(Collection<? extends E> c)Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
voidaddFirst(E e)Inserts the specified element at the beginning of this list.
voidaddLast(E e)Appends the specified element to the end of this list.
voidclear()Removes all of the elements from this list.
Objectclone()Returns a shallow copy of this LinkedList.
booleancontains(Object o)Returns true if this list contains the specified element.
Iterator<E>descendingIterator()Returns an iterator over the elements in this deque in reverse sequential order.
Eelement()Retrieves, but does not remove, the head (first element) of this list.
Eget(int index)Returns the element at the specified position in this list.
EgetFirst()Returns the first element in this list.
EgetLast()Returns the last element in this list.
intindexOf(Object o)Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
intlastIndexOf(Object o)Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
ListIterator<E>listIterator(int index)Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list.
booleanoffer(E e)Adds the specified element as the tail (last element) of this list.
booleanofferFirst(E e)Inserts the specified element at the front of this list.
booleanofferLast(E e)Inserts the specified element at the end of this list.
Epeek()Retrieves, but does not remove, the head (first element) of this list.
EpeekFirst()Retrieves, but does not remove, the first element of this list, or returns null if this list is empty.
EpeekLast()Retrieves, but does not remove, the last element of this list, or returns null if this list is empty.
Epoll()Retrieves and removes the head (first element) of this list.
EpollFirst()Retrieves and removes the first element of this list, or returns null if this list is empty.
EpollLast()Retrieves and removes the last element of this list, or returns null if this list is empty.
Epop()Pops an element from the stack represented by this list.
voidpush(E e)Pushes an element onto the stack represented by this list.
Eremove()Retrieves and removes the head (first element) of this list.
Eremove(int index)Removes the element at the specified position in this list.
booleanremove(Object o)Removes the first occurrence of the specified element from this list, if it is present.
EremoveFirst()Removes and returns the first element from this list.
booleanremoveFirstOccurrence(Object o)Removes the first occurrence of the specified element in this list (when traversing the list from head to tail).
EremoveLast()Removes and returns the last element from this list.
booleanremoveLastOccurrence(Object o)Removes the last occurrence of the specified element in this list (when traversing the list from head to tail).
Eset(int index, E element)Replaces the element at the specified position in this list with the specified element.
intsize()Returns the number of elements in this list.
Spliterator<E>spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this list.
Object[]toArray()Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
List example
@Test
public void listTest() {
    Collection<Object> col = new ArrayList<>(); // 接口类引用指向其实现类,形成多态
    col.add("one");
    col.add("three");
    System.out.println(col); // [one, three]
    Collection<String> col2 = new ArrayList<>();
    col2.add("two");
    col.addAll(col2);
    System.out.println(col); // [one, three, two]
    boolean contains = col.contains("one");
    System.out.println(contains); // true
    Person p = new Person("alex", 20);
    col.add(p);
    Person p1 = new Person("alex", 20);
    contains = col.contains(p1);
    System.out.println(contains); // false, compare address by default, if you didn't override equals method
    contains = col.containsAll(col2);
    System.out.println(contains); // true
    System.out.println(col); // [one, three, two, Person{name='alex', age=20}]
    contains = col.retainAll(col);
    System.out.println(contains); // false, 当col元素发生变化时,返回true
    contains = col.retainAll(col2);
    System.out.println(contains); // true, 保留交集
    System.out.println(col); // [two]
    col.add("one");
    col.add("two");
    col.add("three");
    col.add(p);
    col.remove("three");
    System.out.println(col); // [two, one, two, Person{name='alex', age=20}]
    col2.add("four");
    col.removeAll(col2);
    System.out.println(col); // [one, Person{name='alex', age=20}]
}
Collection和数组转换
Modifier and TypeMethodDescription
Object[]toArray()Returns an array containing all of the elements in this collection.
default <T> T[]toArray(IntFunction<T[]> generator)Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
final Object[] objects = col.toArray();
System.out.println(Arrays.toString(objects)); // [one, Person{name='alex', age=20}]
final List<Object> objects1 = Arrays.asList(objects);
System.out.println(objects1); // [one, Person{name='alex', age=20}]

Queue<E>接口

public interface Queue<E>
extends Collection<E>

请添加图片描述

Methods

Modifier and TypeMethodDescription
booleanadd(E e)Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
Eelement()Retrieves, but does not remove, the head of this queue.
booleanoffer(E e)Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
Epeek()Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
Epoll()Retrieves and removes the head of this queue, or returns null if this queue is empty.
Eremove()Retrieves and removes the head of this queue.
PriorityQueue<E>
public class PriorityQueue<E>
extends AbstractQueue<E>
implements Serializable

An unbounded priority Queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException).

Constructors

ConstructorDescription
PriorityQueue()Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
PriorityQueue(int initialCapacity)Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering.
PriorityQueue(int initialCapacity, Comparator<? super E> comparator)Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.
PriorityQueue(Collection<? extends E> c)Creates a PriorityQueue containing the elements in the specified collection.
PriorityQueue(Comparator<? super E> comparator)Creates a PriorityQueue with the default initial capacity and whose elements are ordered according to the specified comparator.
PriorityQueue(PriorityQueue<? extends E> c)Creates a PriorityQueue containing the elements in the specified priority queue.
PriorityQueue(SortedSet<? extends E> c)Creates a PriorityQueue containing the elements in the specified sorted set.

Methods

Modifier and TypeMethodDescription
booleanadd(E e)Inserts the specified element into this priority queue.
voidclear()Removes all of the elements from this priority queue.
Comparator<? super E>comparator()Returns the comparator used to order the elements in this queue, or null if this queue is sorted according to the natural ordering of its elements.
booleancontains(Object o)Returns true if this queue contains the specified element.
voidforEach(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
Iterator<E>iterator()Returns an iterator over the elements in this queue.
booleanoffer(E e)Inserts the specified element into this priority queue.
booleanremove(Object o)Removes a single instance of the specified element from this queue, if it is present.
booleanremoveAll(Collection<?> c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
booleanremoveIf(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
booleanretainAll(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
Spliterator<E>spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this queue.
Object[]toArray()Returns an array containing all of the elements in this queue.
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.
SynchronousQueue<E>
public class SynchronousQueue<E>
extends AbstractQueue<E>
implements BlockingQueue<E>, Serializable

A BlockingQueue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one. You cannot peek at a synchronous queue because an element is only present when you try to remove it; you cannot insert an element (using any method) unless another thread is trying to remove it; you cannot iterate as there is nothing to iterate. The head of the queue is the element that the first queued inserting thread is trying to add to the queue; if there is no such queued thread then no element is available for removal and poll() will return null. For purposes of other Collection methods (for example contains), a SynchronousQueue acts as an empty collection. This queue does not permit null elements.

Constructors

ConstructorDescription
SynchronousQueue()Creates a SynchronousQueue with nonfair access policy.
SynchronousQueue(boolean fair)Creates a SynchronousQueue with the specified fairness policy.

Methods

Modifier and TypeMethodDescription
voidclear()Does nothing.
booleancontains(Object o)Always returns false.
booleancontainsAll(Collection<?> c)Returns false unless the given collection is empty.
intdrainTo(Collection<? super E> c)Removes all available elements from this queue and adds them to the given collection.
intdrainTo(Collection<? super E> c, int maxElements)Removes at most the given number of available elements from this queue and adds them to the given collection.
booleanisEmpty()Always returns true.
Iterator<E>iterator()Returns an empty iterator in which hasNext always returns false.
booleanoffer(E e)Inserts the specified element into this queue, if another thread is waiting to receive it.
booleanoffer(E e, long timeout, TimeUnit unit)Inserts the specified element into this queue, waiting if necessary up to the specified wait time for another thread to receive it.
Epeek()Always returns null.
Epoll()Retrieves and removes the head of this queue, if another thread is currently making an element available.
Epoll(long timeout, TimeUnit unit)Retrieves and removes the head of this queue, waiting if necessary up to the specified wait time, for another thread to insert it.
voidput(E e)Adds the specified element to this queue, waiting if necessary for another thread to receive it.
intremainingCapacity()Always returns zero.
booleanremove(Object o)Always returns false.
booleanremoveAll(Collection<?> c)Always returns false.
booleanretainAll(Collection<?> c)Always returns false.
intsize()Always returns zero.
Spliterator<E>spliterator()Returns an empty spliterator in which calls to trySplit always return null.
Etake()Retrieves and removes the head of this queue, waiting if necessary for another thread to insert it.
Object[]toArray()Returns a zero-length array.
<T> T[]toArray(T[] a)Sets the zeroth element of the specified array to null (if the array has non-zero length) and returns it.
StringtoString()Always returns "[]".
PriorityBlockingQueue<E>
public class PriorityBlockingQueue<E>
extends AbstractQueue<E>
implements BlockingQueue<E>, Serializable

An unbounded BlockingQueue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. While this queue is logically unbounded, attempted additions may fail due to resource exhaustion (causing OutOfMemoryError). This class does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so results in ClassCastException).

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() and the Spliterator provided in method spliterator() are not guaranteed to traverse the elements of the PriorityBlockingQueue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()). Also, method drainTo can be used to remove some or all elements in priority order and place them in another collection.

Operations on this class make no guarantees about the ordering of elements with equal priority. If you need to enforce an ordering, you can define custom classes or comparators that use a secondary key to break ties in primary priority values. For example, here is a class that applies first-in-first-out tie-breaking to comparable elements. To use it, you would insert a new FIFOEntry(anEntry) instead of a plain entry object.

Constructors

ConstructorDescription
PriorityBlockingQueue()Creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
PriorityBlockingQueue(int initialCapacity)Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to their natural ordering.
PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator)Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator.
PriorityBlockingQueue(Collection<? extends E> c)Creates a PriorityBlockingQueue containing the elements in the specified collection.

Methods

Modifier and TypeMethodDescription
booleanadd(E e)Inserts the specified element into this priority queue.
voidclear()Atomically removes all of the elements from this queue.
Comparator<? super E>comparator()Returns the comparator used to order the elements in this queue, or null if this queue uses the natural ordering of its elements.
booleancontains(Object o)Returns true if this queue contains the specified element.
intdrainTo(Collection<? super E> c)Removes all available elements from this queue and adds them to the given collection.
intdrainTo(Collection<? super E> c, int maxElements)Removes at most the given number of available elements from this queue and adds them to the given collection.
voidforEach(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
Iterator<E>iterator()Returns an iterator over the elements in this queue.
booleanoffer(E e)Inserts the specified element into this priority queue.
booleanoffer(E e, long timeout, TimeUnit unit)Inserts the specified element into this priority queue.
voidput(E e)Inserts the specified element into this priority queue.
intremainingCapacity()Always returns Integer.MAX_VALUE because a PriorityBlockingQueue is not capacity constrained.
booleanremove(Object o)Removes a single instance of the specified element from this queue, if it is present.
booleanremoveAll(Collection<?> c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
booleanremoveIf(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
booleanretainAll(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
Spliterator<E>spliterator()Returns a Spliterator over the elements in this queue.
Object[]toArray()Returns an array containing all of the elements in this queue.
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.
ArrayBlockingQueue<E>
public class ArrayBlockingQueue<E>
extends AbstractQueue<E>
implements BlockingQueue<E>, Serializable

A bounded BlockingQueue backed by an array. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue.

This is a classic “bounded buffer”, in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Once created, the capacity cannot be changed. Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block.

This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to true grants threads access in FIFO order. Fairness generally decreases throughput but reduces variability and avoids starvation.

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

Constructors

ConstructorDescription
ArrayBlockingQueue(int capacity)Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy.
ArrayBlockingQueue(int capacity, boolean fair)Creates an ArrayBlockingQueue with the given (fixed) capacity and the specified access policy.
ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c)Creates an ArrayBlockingQueue with the given (fixed) capacity, the specified access policy and initially containing the elements of the given collection, added in traversal order of the collection’s iterator.

Methods

Modifier and TypeMethodDescription
booleanadd(E e)Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue’s capacity, returning true upon success and throwing an IllegalStateException if this queue is full.
voidclear()Atomically removes all of the elements from this queue.
booleancontains(Object o)Returns true if this queue contains the specified element.
intdrainTo(Collection<? super E> c)Removes all available elements from this queue and adds them to the given collection.
intdrainTo(Collection<? super E> c, int maxElements)Removes at most the given number of available elements from this queue and adds them to the given collection.
voidforEach(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
Iterator<E>iterator()Returns an iterator over the elements in this queue in proper sequence.
booleanoffer(E e)Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue’s capacity, returning true upon success and false if this queue is full.
booleanoffer(E e, long timeout, TimeUnit unit)Inserts the specified element at the tail of this queue, waiting up to the specified wait time for space to become available if the queue is full.
voidput(E e)Inserts the specified element at the tail of this queue, waiting for space to become available if the queue is full.
intremainingCapacity()Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking.
booleanremove(Object o)Removes a single instance of the specified element from this queue, if it is present.
booleanremoveAll(Collection<?> c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
booleanremoveIf(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
booleanretainAll(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
intsize()Returns the number of elements in this queue.
Spliterator<E>spliterator()Returns a Spliterator over the elements in this queue.
Object[]toArray()Returns an array containing all of the elements in this queue, in proper sequence.
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this queue, in proper sequence; the runtime type of the returned array is that of the specified array.

Deque<E>接口

public interface Deque<E>
extends Queue<E>

请添加图片描述

Methods

Modifier and TypeMethodDescription
booleanadd(E e)Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
booleanaddAll(Collection<? extends E> c)Adds all of the elements in the specified collection at the end of this deque, as if by calling addLast(E) on each one, in the order that they are returned by the collection’s iterator.
voidaddFirst(E e)Inserts the specified element at the front of this deque if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.
voidaddLast(E e)Inserts the specified element at the end of this deque if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.
booleancontains(Object o)Returns true if this deque contains the specified element.
Iterator<E>descendingIterator()Returns an iterator over the elements in this deque in reverse sequential order.
Eelement()Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque).
EgetFirst()Retrieves, but does not remove, the first element of this deque.
EgetLast()Retrieves, but does not remove, the last element of this deque.
Iterator<E>iterator()Returns an iterator over the elements in this deque in proper sequence.
booleanoffer(E e)Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
booleanofferFirst(E e)Inserts the specified element at the front of this deque unless it would violate capacity restrictions.
booleanofferLast(E e)Inserts the specified element at the end of this deque unless it would violate capacity restrictions.
Epeek()Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
EpeekFirst()Retrieves, but does not remove, the first element of this deque, or returns null if this deque is empty.
EpeekLast()Retrieves, but does not remove, the last element of this deque, or returns null if this deque is empty.
Epoll()Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
EpollFirst()Retrieves and removes the first element of this deque, or returns null if this deque is empty.
EpollLast()Retrieves and removes the last element of this deque, or returns null if this deque is empty.
Epop()Pops an element from the stack represented by this deque.
voidpush(E e)Pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.
Eremove()Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque).
booleanremove(Object o)Removes the first occurrence of the specified element from this deque.
EremoveFirst()Retrieves and removes the first element of this deque.
booleanremoveFirstOccurrence(Object o)Removes the first occurrence of the specified element from this deque.
EremoveLast()Retrieves and removes the last element of this deque.
booleanremoveLastOccurrence(Object o)Removes the last occurrence of the specified element from this deque.
intsize()Returns the number of elements in this deque.
ArrayDeque<E>
public class ArrayDeque<E>
extends AbstractCollection<E>
implements Deque<E>, Cloneable, Serializable

Resizable-array implementation of the Deque interface. Array deques have no capacity restrictions; they grow as necessary to support usage. They are not thread-safe; in the absence of external synchronization, they do not support concurrent access by multiple threads. Null elements are prohibited. This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue.

Most ArrayDeque operations run in amortized constant time. Exceptions include remove, removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(), and the bulk operations, all of which run in linear time.

The iterators returned by this class’s iterator method are fail-fast: If the deque is modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will generally throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

Constructors

ConstructorDescription
ArrayDeque()Constructs an empty array deque with an initial capacity sufficient to hold 16 elements.
ArrayDeque(int numElements)Constructs an empty array deque with an initial capacity sufficient to hold the specified number of elements.
ArrayDeque(Collection<? extends E> c)Constructs a deque containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

Methods

Modifier and TypeMethodDescription
booleanadd(E e)Inserts the specified element at the end of this deque.
booleanaddAll(Collection<? extends E> c)Adds all of the elements in the specified collection at the end of this deque, as if by calling addLast(E) on each one, in the order that they are returned by the collection’s iterator.
voidaddFirst(E e)Inserts the specified element at the front of this deque.
voidaddLast(E e)Inserts the specified element at the end of this deque.
voidclear()Removes all of the elements from this deque.
ArrayDeque<E>clone()Returns a copy of this deque.
booleancontains(Object o)Returns true if this deque contains the specified element.
Eelement()Retrieves, but does not remove, the head of the queue represented by this deque.
voidforEach(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
EgetFirst()Retrieves, but does not remove, the first element of this deque.
EgetLast()Retrieves, but does not remove, the last element of this deque.
booleanisEmpty()Returns true if this deque contains no elements.
Iterator<E>iterator()Returns an iterator over the elements in this deque.
booleanoffer(E e)Inserts the specified element at the end of this deque.
booleanofferFirst(E e)Inserts the specified element at the front of this deque.
booleanofferLast(E e)Inserts the specified element at the end of this deque.
Epeek()Retrieves, but does not remove, the head of the queue represented by this deque, or returns null if this deque is empty.
Epoll()Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
Epop()Pops an element from the stack represented by this deque.
voidpush(E e)Pushes an element onto the stack represented by this deque.
Eremove()Retrieves and removes the head of the queue represented by this deque.
booleanremove(Object o)Removes a single instance of the specified element from this deque.
booleanremoveAll(Collection<?> c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
EremoveFirst()Retrieves and removes the first element of this deque.
booleanremoveFirstOccurrence(Object o)Removes the first occurrence of the specified element in this deque (when traversing the deque from head to tail).
booleanremoveIf(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
EremoveLast()Retrieves and removes the last element of this deque.
booleanremoveLastOccurrence(Object o)Removes the last occurrence of the specified element in this deque (when traversing the deque from head to tail).
booleanretainAll(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
intsize()Returns the number of elements in this deque.
Spliterator<E>spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this deque.
Object[]toArray()Returns an array containing all of the elements in this deque in proper sequence (from first to last element).
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this deque in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
ConcurrentLinkedDeque<E>
public class ConcurrentLinkedDeque<E>
extends AbstractCollection<E>
implements Deque<E>, Serializable

An unbounded concurrent deque based on linked nodes. Concurrent insertion, removal, and access operations execute safely across multiple threads. A ConcurrentLinkedDeque is an appropriate choice when many threads will share access to a common collection. Like most other concurrent collection implementations, this class does not permit the use of null elements.

Iterators and spliterators are weakly consistent.

Beware that, unlike in most collections, the size method is NOT a constant-time operation. Because of the asynchronous nature of these deques, determining the current number of elements requires a traversal of the elements, and so may report inaccurate results if this collection is modified during traversal.

Bulk operations that add, remove, or examine multiple elements, such as addAll(java.util.Collection), removeIf(java.util.function.Predicate) or forEach(java.util.function.Consumer), are not guaranteed to be performed atomically. For example, a forEach traversal concurrent with an addAll operation might observe only some of the added elements.

This class and its iterator implement all of the optional methods of the Deque and Iterator interfaces.

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a ConcurrentLinkedDeque happen-before actions subsequent to the access or removal of that element from the ConcurrentLinkedDeque in another thread.

Constructors

ConstructorDescription
ConcurrentLinkedDeque()Constructs an empty deque.
ConcurrentLinkedDeque(Collection<? extends E> c)Constructs a deque initially containing the elements of the given collection, added in traversal order of the collection’s iterator.

Methods

Modifier and TypeMethodDescription
booleanadd(E e)Inserts the specified element at the tail of this deque.
booleanaddAll(Collection<? extends E> c)Appends all of the elements in the specified collection to the end of this deque, in the order that they are returned by the specified collection’s iterator.
voidaddFirst(E e)Inserts the specified element at the front of this deque.
voidaddLast(E e)Inserts the specified element at the end of this deque.
voidclear()Removes all of the elements from this deque.
booleancontains(Object o)Returns true if this deque contains the specified element.
Iterator<E>descendingIterator()Returns an iterator over the elements in this deque in reverse sequential order.
Eelement()Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque).
voidforEach(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
EgetFirst()Retrieves, but does not remove, the first element of this deque.
EgetLast()Retrieves, but does not remove, the last element of this deque.
booleanisEmpty()Returns true if this collection contains no elements.
Iterator<E>iterator()Returns an iterator over the elements in this deque in proper sequence.
booleanoffer(E e)Inserts the specified element at the tail of this deque.
booleanofferFirst(E e)Inserts the specified element at the front of this deque.
booleanofferLast(E e)Inserts the specified element at the end of this deque.
Epop()Pops an element from the stack represented by this deque.
voidpush(E e)Pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.
Eremove()Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque).
booleanremove(Object o)Removes the first occurrence of the specified element from this deque.
booleanremoveAll(Collection<?> c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
EremoveFirst()Retrieves and removes the first element of this deque.
booleanremoveFirstOccurrence(Object o)Removes the first occurrence of the specified element from this deque.
booleanremoveIf(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
EremoveLast()Retrieves and removes the last element of this deque.
booleanremoveLastOccurrence(Object o)Removes the last occurrence of the specified element from this deque.
booleanretainAll(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
intsize()Returns the number of elements in this deque.
Spliterator<E>spliterator()Returns a Spliterator over the elements in this deque.
Object[]toArray()Returns an array containing all of the elements in this deque, in proper sequence (from first to last element).
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this deque, in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
LinkedBlockingDeque<E>
public class LinkedBlockingDeque<E>
extends AbstractQueue<E>
implements BlockingDeque<E>, Serializable

An optionally-bounded blocking deque based on linked nodes.

The optional capacity bound constructor argument serves as a way to prevent excessive expansion. The capacity, if unspecified, is equal to Integer.MAX_VALUE. Linked nodes are dynamically created upon each insertion unless this would bring the deque above capacity.

Most operations run in constant time (ignoring time spent blocking). Exceptions include remove, removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(), and the bulk operations, all of which run in linear time.

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

Constructors

ConstructorDescription
LinkedBlockingDeque()Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE.
LinkedBlockingDeque(int capacity)Creates a LinkedBlockingDeque with the given (fixed) capacity.
LinkedBlockingDeque(Collection<? extends E> c)Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection, added in traversal order of the collection’s iterator.

Methods

Modifier and TypeMethodDescription
booleanadd(E e)Inserts the specified element at the end of this deque unless it would violate capacity restrictions.
booleanaddAll(Collection<? extends E> c)Appends all of the elements in the specified collection to the end of this deque, in the order that they are returned by the specified collection’s iterator.
voidaddFirst(E e)Inserts the specified element at the front of this deque if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.
voidaddLast(E e)Inserts the specified element at the end of this deque if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.
voidclear()Atomically removes all of the elements from this deque.
booleancontains(Object o)Returns true if this deque contains the specified element.
Iterator<E>descendingIterator()Returns an iterator over the elements in this deque in reverse sequential order.
intdrainTo(Collection<? super E> c)Removes all available elements from this queue and adds them to the given collection.
intdrainTo(Collection<? super E> c, int maxElements)Removes at most the given number of available elements from this queue and adds them to the given collection.
Eelement()Retrieves, but does not remove, the head of the queue represented by this deque.
voidforEach(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
EgetFirst()Retrieves, but does not remove, the first element of this deque.
EgetLast()Retrieves, but does not remove, the last element of this deque.
Iterator<E>iterator()Returns an iterator over the elements in this deque in proper sequence.
booleanoffer(E e)Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
booleanoffer(E e, long timeout, TimeUnit unit)Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque), waiting up to the specified wait time if necessary for space to become available.
booleanofferFirst(E e)Inserts the specified element at the front of this deque if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
booleanofferFirst(E e, long timeout, TimeUnit unit)Inserts the specified element at the front of this deque, waiting up to the specified wait time if necessary for space to become available.
booleanofferLast(E e)Inserts the specified element at the end of this deque if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
booleanofferLast(E e, long timeout, TimeUnit unit)Inserts the specified element at the end of this deque, waiting up to the specified wait time if necessary for space to become available.
Epop()Pops an element from the stack represented by this deque.
voidpush(E e)Pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.
voidput(E e)Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque), waiting if necessary for space to become available.
voidputFirst(E e)Inserts the specified element at the front of this deque, waiting if necessary for space to become available.
voidputLast(E e)Inserts the specified element at the end of this deque, waiting if necessary for space to become available.
intremainingCapacity()Returns the number of additional elements that this deque can ideally (in the absence of memory or resource constraints) accept without blocking.
Eremove()Retrieves and removes the head of the queue represented by this deque.
booleanremove(Object o)Removes the first occurrence of the specified element from this deque.
booleanremoveAll(Collection<?> c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
EremoveFirst()Retrieves and removes the first element of this deque.
booleanremoveIf(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
EremoveLast()Retrieves and removes the last element of this deque.
booleanretainAll(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
intsize()Returns the number of elements in this deque.
Spliterator<E>spliterator()Returns a Spliterator over the elements in this deque.
Object[]toArray()Returns an array containing all of the elements in this deque, in proper sequence (from first to last element).
<T> T[]toArray(T[] a)Returns an array containing all of the elements in this deque, in proper sequence; the runtime type of the returned array is that of the specified array.

Set<E>接口

public interface Set<E>
extends Collection<E>

请添加图片描述

  • java.util.Set集合是Collection集合的子集合,与List集合平级。
  • 该集合中元素没有先后放入次序,且不允许重复。
  • 该集合的主要实现类是:HashSet类 和 TreeSet类以及LinkedHashSet类。
  • 其中HashSet类的底层是采用哈希表进行数据管理的。
  • 其中TreeSet类的底层是采用红黑树进行数据管理的。
  • 其中LinkedHashSet类与HashSet类的不同之处在于内部维护了一个双向链表,链表中记录了元素的迭代顺序,也就是元素插入集合中的先后顺序,因此便于迭代。
HashSet<E>
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, Serializable

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance’s size (the number of elements) plus the “capacity” of the backing HashMap instance (the number of buckets). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

Note that this implementation is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be “wrapped” using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:

Set s = Collections.synchronizedSet(new HashSet(...));

The iterators returned by this class’s iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the Iterator throws a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

元素放入HashSet集合的原理
  • 使用元素调用hashCode方法获取对应的哈希码值,再由某种哈希算法计算出该元素在数组中的索引位置。
  • 若该位置没有元素,则将该元素直接放入即可。
  • 若该位置有元素,则使用新元素与已有元素依次比较哈希值,若哈希值不相同,则将该元素直接放入。
  • 若新元素与已有元素的哈希值相同,则使用新元素调用equals方法与已有元素依次比较。
  • 若相等则添加元素失败,否则将元素直接放入即可。
  • 思考:为什么要求重写equals方法后要重写hashCode方法呢?
  • 解析:
    当两个元素调用equals方法相等时证明这两个元素相同,重写hashCode方法后保证这两个元素得到的哈希码值相同,由同一个哈希算法生成的索引位置相同,此时只需要与该索引位置已有元素比较即可,从而提高效率并避免重复元素的出现。

Constructors

ConstructorDescription
HashSet()Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
HashSet(int initialCapacity)Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).
HashSet(int initialCapacity, float loadFactor)Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.
HashSet(Collection<? extends E> c)Constructs a new set containing the elements in the specified collection.

Methods

Modifier and TypeMethodDescription
booleanadd(E e)Adds the specified element to this set if it is not already present.
voidclear()Removes all of the elements from this set.
Objectclone()Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
booleancontains(Object o)Returns true if this set contains the specified element.
booleanisEmpty()Returns true if this set contains no elements.
Iterator<E>iterator()Returns an iterator over the elements in this set.
booleanremove(Object o)Removes the specified element from this set if it is present.
intsize()Returns the number of elements in this set (its cardinality).
Spliterator<E>spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this set.
TreeSet<E>
public class TreeSet<E>
extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, Serializable

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

Note that this implementation is not synchronized. If multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be “wrapped” using the Collections.synchronizedSortedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:

   SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

The iterators returned by this class’s iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

  • 二叉树主要指每个节点最多只有两个子节点的树形结构。
  • 满足以下3个特征的二叉树叫做有序二叉树。
    a.左子树中的任意节点元素都小于根节点元素值;
    b.右子树中的任意节点元素都大于根节点元素值;
    c.左子树和右子树的内部也遵守上述规则;
  • 由于TreeSet集合的底层采用红黑树进行数据的管理,当有新元素插入到TreeSet集合时,需要使用新元素与集合中已有的元素依次比较来确定新元素的合理位置。
  • 比较元素大小的规则有两种方式:
    使用元素的自然排序规则进行比较并排序,让元素类型实现java.lang.Comparable接口;
    使用比较器规则进行比较并排序,构造TreeSet集合时传入java.util.Comparator接口;
  • 自然排序的规则比较单一,而比较器的规则比较多元化,而且比较器优先于自然排序;

Constructors

ConstructorDescription
TreeSet()Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
TreeSet(Collection<? extends E> c)Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
TreeSet(Comparator<? super E> comparator)Constructs a new, empty tree set, sorted according to the specified comparator.
TreeSet(SortedSet<E> s)Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.

Methods

Modifier and TypeMethodDescription
booleanadd(E e)Adds the specified element to this set if it is not already present.
booleanaddAll(Collection<? extends E> c)Adds all of the elements in the specified collection to this set.
Eceiling(E e)Returns the least element in this set greater than or equal to the given element, or null if there is no such element.
voidclear()Removes all of the elements from this set.
Objectclone()Returns a shallow copy of this TreeSet instance.
booleancontains(Object o)Returns true if this set contains the specified element.
Iterator<E>descendingIterator()Returns an iterator over the elements in this set in descending order.
NavigableSet<E>descendingSet()Returns a reverse order view of the elements contained in this set.
Efirst()Returns the first (lowest) element currently in this set.
Efloor(E e)Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
SortedSet<E>headSet(E toElement)Returns a view of the portion of this set whose elements are strictly less than toElement.
NavigableSet<E>headSet(E toElement, boolean inclusive)Returns a view of the portion of this set whose elements are less than (or equal to, if inclusive is true) toElement.
Ehigher(E e)Returns the least element in this set strictly greater than the given element, or null if there is no such element.
booleanisEmpty()Returns true if this set contains no elements.
Iterator<E>iterator()Returns an iterator over the elements in this set in ascending order.
Elast()Returns the last (highest) element currently in this set.
Elower(E e)Returns the greatest element in this set strictly less than the given element, or null if there is no such element.
EpollFirst()Retrieves and removes the first (lowest) element, or returns null if this set is empty.
EpollLast()Retrieves and removes the last (highest) element, or returns null if this set is empty.
booleanremove(Object o)Removes the specified element from this set if it is present.
intsize()Returns the number of elements in this set (its cardinality).
Spliterator<E>spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this set.
NavigableSet<E>subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)Returns a view of the portion of this set whose elements range from fromElement to toElement.
SortedSet<E>subSet(E fromElement, E toElement)Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
SortedSet<E>tailSet(E fromElement)Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
NavigableSet<E>tailSet(E fromElement, boolean inclusive)Returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.
LinkedHashSet<E>

加入了双向链表保存插入顺序

public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, Serializable

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashSet, without incurring the increased cost associated with TreeSet. It can be used to produce a copy of a set that has the same order as the original, regardless of the original set’s implementation:

     void foo(Set s) {
         Set copy = new LinkedHashSet(s);
         ...
     }
 

This technique is particularly useful if a module takes a set on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.)

This class provides all of the optional Set operations, and permits null elements. Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity.

A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity.

Note that this implementation is not synchronized. If multiple threads access a linked hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be “wrapped” using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:

   Set s = Collections.synchronizedSet(new LinkedHashSet(...));

The iterators returned by this class’s iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

Constructors

ConstructorDescription
LinkedHashSet()Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).
LinkedHashSet(int initialCapacity)Constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75).
LinkedHashSet(int initialCapacity, float loadFactor)Constructs a new, empty linked hash set with the specified initial capacity and load factor.
LinkedHashSet(Collection<? extends E> c)Constructs a new linked hash set with the same elements as the specified collection.

Methods

Modifier and TypeMethodDescription
Spliterator<E>spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this set.

Iterator<E>接口

public interface Iterator<E>

iterator()方法返回一个实现了Iterator<E>接口的内部类的实例。比如ArrayList<E>中的内部类:

/**
     * An optimized version of AbstractList.Itr
     */
private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    // prevent creating a synthetic constructor
    Itr() {}

    public boolean hasNext() {
        return cursor != size;
    }

    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    @Override
    public void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int size = ArrayList.this.size;
        int i = cursor;
        if (i < size) {
            final Object[] es = elementData;
            if (i >= es.length)
                throw new ConcurrentModificationException();
            for (; i < size && modCount == expectedModCount; i++)
                action.accept(elementAt(es, i));
            // update once at end to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

Methods

Modifier and TypeMethodDescription
default voidforEachRemaining(Consumer<? super E> action)Performs the given action for each remaining element until all elements have been processed or the action throws an exception.
booleanhasNext()Returns true if the iteration has more elements.
Enext()Returns the next element in the iteration.
default voidremove()Removes from the underlying collection the last element returned by this iterator (optional operation).
final Iterator<Object> iterator = col.iterator();
while (iterator.hasNext()) {
    final Object next = iterator.next();
    // col.remove(e); -> raise ConcurrentModificationException
    System.out.println(next);
}

通常建议使用for循环代替:

for (Object next : col) {
    System.out.println(next);
}

Map<E>接口

Type Parameters:

K - the type of keys maintained by this map

V - the type of mapped values

public interface Map<K, V>

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
请添加图片描述

  • java.util.Map<K,V>集合中存取元素的基本单位是:单对元素,其中类型参数如下:
    K - 此映射所维护的键(Key)的类型,相当于目录。
    V- 映射值(Value)的类型,相当于内容。
  • 该集合中key是不允许重复的,而且一个key只能对应一个value
  • 该集合的主要实现类有:HashMap类、TreeMap类、LinkedHashMap类、Hashtable类、Properties类。
  • 其中HashMap类的底层是采用哈希表进行数据管理的。
  • 其中TreeMap类的底层是采用红黑树进行数据管理的。
  • 其中LinkedHashMap类与HashMap类的不同之处在于内部维护了一个双向链表,链表中记录了元素的迭代顺序,也就是元素插入集合中的先后顺序,因此便于迭代。
  • 其中Hashtable类是古老的Map实现类,与HashMap类相比属于线程安全的类,且不允许null作为key或者value的数值。
  • 其中Properties类是Hashtable类的子类,该对象用于处理属性文件,keyvalue都是String类型的。
  • Map集合是面向查询优化的数据结构, 在大数据量情况下有着优良的查询性能。
  • 经常用于根据key检索value的业务场景。

元素放入HashMap集合的原理

  • 使用元素的key调用hashCode方法获取对应的哈希码值,再由某种哈希算法计算在数组中的索引位置。
  • 若该位置没有元素,则将该键值对直接放入即可。
  • 若该位置有元素,则使用key与已有元素依次比较哈希值,若哈希值不相同,则将该元素直接放入。
  • 若key与已有元素的哈希值相同,则使用key调用equals方法与已有元素依次比较。
  • 若相等则将对应的value修改,否则将键值对直接放入即可。

相关的常量

  • DEFAULT_INITIAL_CAPACITY: HashMap的默认容量是16。
  • DEFAULT_LOAD_FACTORHashMap的默认加载因子是0.75。
  • threshold:扩容的临界值,该数值为:容量*填充因子,也就是12。
  • TREEIFY_THRESHOLD:若Bucket中链表长度大于该默认值则转化为红黑树存储,该数值是8。
  • MIN_TREEIFY_CAPACITY:桶中的Node被树化时最小的hash表容量,该数值是64。

Methods

Modifier and TypeMethodDescription
voidclear()Removes all of the mappings from this map (optional operation).
default Vcompute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
default VcomputeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
default VcomputeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
booleancontainsKey(Object key)Returns true if this map contains a mapping for the specified key.
booleancontainsValue(Object value)Returns true if this map maps one or more keys to the specified value.
static <K,V>Map<K,V>copyOf(Map<? extends K,? extends V> map)Returns an unmodifiable Map containing the entries of the given Map.
static <K,V>Map.Entry<K,V>entry(K k, V v)Returns an unmodifiable Map.Entry containing the given key and value.
Set<Map.Entry<K,V>>entrySet()Returns a Set view of the mappings contained in this map.
booleanequals(Object o)Compares the specified object with this map for equality.
default voidforEach(BiConsumer<? super K,? super V> action)Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
Vget(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
default VgetOrDefault(Object key, V defaultValue)Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
inthashCode()Returns the hash code value for this map.
booleanisEmpty()Returns true if this map contains no key-value mappings.
Set<K>keySet()Returns a Set view of the keys contained in this map.
default Vmerge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
static <K,V>Map<K,V>of()Returns an unmodifiable map containing zero mappings.
static <K,V>Map<K,V>of(K k1, V v1)Returns an unmodifiable map containing a single mapping.
static <K,V>Map<K,V>of(K k1, V v1, K k2, V v2)Returns an unmodifiable map containing two mappings.
static <K,V>Map<K,V>of(K k1, V v1, K k2, V v2, K k3, V v3)Returns an unmodifiable map containing three mappings.
static <K,V>Map<K,V>of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4)Returns an unmodifiable map containing four mappings.
static <K,V>Map<K,V>of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5)Returns an unmodifiable map containing five mappings.
static <K,V>Map<K,V>of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6)Returns an unmodifiable map containing six mappings.
static <K,V>Map<K,V>of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7)Returns an unmodifiable map containing seven mappings.
static <K,V>Map<K,V>of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8)Returns an unmodifiable map containing eight mappings.
static <K,V>Map<K,V>of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9)Returns an unmodifiable map containing nine mappings.
static <K,V>Map<K,V>of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10)Returns an unmodifiable map containing ten mappings.
static <K,V>Map<K,V>ofEntries(Map.Entry<? extends K,? extends V>... entries)Returns an unmodifiable map containing keys and values extracted from the given entries.
Vput(K key, V value)Associates the specified value with the specified key in this map (optional operation).
voidputAll(Map<? extends K,? extends V> m)Copies all of the mappings from the specified map to this map (optional operation).
default VputIfAbsent(K key, V value)If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
Vremove(Object key)Removes the mapping for a key from this map if it is present (optional operation).
default booleanremove(Object key, Object value)Removes the entry for the specified key only if it is currently mapped to the specified value.
default Vreplace(K key, V value)Replaces the entry for the specified key only if it is currently mapped to some value.
default booleanreplace(K key, V oldValue, V newValue)Replaces the entry for the specified key only if currently mapped to the specified value.
default voidreplaceAll(BiFunction<? super K,? super V,? extends V> function)Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
intsize()Returns the number of key-value mappings in this map.
Collection<V>values()Returns a Collection view of the values contained in this map.

AbstractMap<K,V>抽象类

public abstract class AbstractMap<K, V>
extends Object
implements Map<K, V>

This class provides a skeletal implementation of the Map interface, to minimize the effort required to implement this interface.

To implement an unmodifiable map, the programmer needs only to extend this class and provide an implementation for the entrySet method, which returns a set-view of the map’s mappings. Typically, the returned set will, in turn, be implemented atop AbstractSet. This set should not support the add or remove methods, and its iterator should not support the remove method.

To implement a modifiable map, the programmer must additionally override this class’s put method (which otherwise throws an UnsupportedOperationException), and the iterator returned by entrySet().iterator() must additionally implement its remove method.

The programmer should generally provide a void (no argument) and map constructor, as per the recommendation in the Map interface specification.

The documentation for each non-abstract method in this class describes its implementation in detail. Each of these methods may be overridden if the map being implemented admits a more efficient implementation.

Methods

Modifier and TypeMethodDescription
voidclear()Removes all of the mappings from this map (optional operation).
protected Objectclone()Returns a shallow copy of this AbstractMap instance: the keys and values themselves are not cloned.
booleancontainsKey(Object key)Returns true if this map contains a mapping for the specified key.
booleancontainsValue(Object value)Returns true if this map maps one or more keys to the specified value.
booleanequals(Object o)Compares the specified object with this map for equality.
Vget(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
inthashCode()Returns the hash code value for this map.
booleanisEmpty()Returns true if this map contains no key-value mappings.
Set<K>keySet()Returns a Set view of the keys contained in this map.
Vput(K key, V value)Associates the specified value with the specified key in this map (optional operation).
voidputAll(Map<? extends K,? extends V> m)Copies all of the mappings from the specified map to this map (optional operation).
Vremove(Object key)Removes the mapping for a key from this map if it is present (optional operation).
intsize()Returns the number of key-value mappings in this map.
StringtoString()Returns a string representation of this map.
Collection<V>values()Returns a Collection view of the values contained in this map.
HashMap<K,V>
public class HashMap<K, V>
extends AbstractMap<K, V>
implements Map<K, V>, Cloneable, Serializable

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the “capacity” of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table. Note that using many keys with the same hashCode() is a sure way to slow down performance of any hash table. To ameliorate impact, when keys are Comparable, this class may use comparison order among keys to help break ties.

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be “wrapped” using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

   Map m = Collections.synchronizedMap(new HashMap(...));

The iterators returned by all of this class’s “collection view methods” are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

Constructors

ConstructorDescription
HashMap()Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
HashMap(int initialCapacity)Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).
HashMap(int initialCapacity, float loadFactor)Constructs an empty HashMap with the specified initial capacity and load factor.
HashMap(Map<? extends K,? extends V> m)Constructs a new HashMap with the same mappings as the specified Map.

Methods

Modifier and TypeMethodDescription
voidclear()Removes all of the mappings from this map.
Objectclone()Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Vcompute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
VcomputeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
VcomputeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
booleancontainsKey(Object key)Returns true if this map contains a mapping for the specified key.
booleancontainsValue(Object value)Returns true if this map maps one or more keys to the specified value.
Set<Map.Entry<K,V>>entrySet()Returns a Set view of the mappings contained in this map.
Vget(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
booleanisEmpty()Returns true if this map contains no key-value mappings.
Set<K>keySet()Returns a Set view of the keys contained in this map.
Vmerge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
Vput(K key, V value)Associates the specified value with the specified key in this map.
voidputAll(Map<? extends K,? extends V> m)Copies all of the mappings from the specified map to this map.
Vremove(Object key)Removes the mapping for the specified key from this map if present.
intsize()Returns the number of key-value mappings in this map.
Collection<V>values()Returns a Collection view of the values contained in this map.
LinkedHashMap<K,V>
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable), without incurring the increased cost associated with TreeMap. It can be used to produce a copy of a map that has the same order as the original, regardless of the original map’s implementation:

     void foo(Map m) {
         Map copy = new LinkedHashMap(m);
         ...
     }
 

This technique is particularly useful if a module takes a map on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.)

A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches. Invoking the put, putIfAbsent, get, getOrDefault, compute, computeIfAbsent, computeIfPresent, or merge methods results in an access to the corresponding entry (assuming it exists after the invocation completes). The replace methods only result in an access of the entry if the value is replaced. The putAll method generates one entry access for each mapping in the specified map, in the order that key-value mappings are provided by the specified map’s entry set iterator. No other methods generate entry accesses. In particular, operations on collection-views do not affect the order of iteration of the backing map.

The removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.

This class provides all of the optional Map operations, and permits null elements. Like HashMap, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashMap, due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity.

A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.

Note that this implementation is not synchronized. If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be “wrapped” using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

   Map m = Collections.synchronizedMap(new LinkedHashMap(...));

A structural modification is any operation that adds or deletes one or more mappings or, in the case of access-ordered linked hash maps, affects iteration order. In insertion-ordered linked hash maps, merely changing the value associated with a key that is already contained in the map is not a structural modification. In access-ordered linked hash maps, merely querying the map with get is a structural modification. )

The iterators returned by the iterator method of the collections returned by all of this class’s collection view methods are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

The spliterators returned by the spliterator method of the collections returned by all of this class’s collection view methods are late-binding, fail-fast, and additionally report Spliterator.ORDERED.

This class is a member of the Java Collections Framework.

  • Implementation Note:

    The spliterators returned by the spliterator method of the collections returned by all of this class’s collection view methods are created from the iterators of the corresponding collections.

Constructors

ConstructorDescription
LinkedHashMap()Constructs an empty insertion-ordered LinkedHashMap instance with the default initial capacity (16) and load factor (0.75).
LinkedHashMap(int initialCapacity)Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and a default load factor (0.75).
LinkedHashMap(int initialCapacity, float loadFactor)Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and load factor.
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode.
LinkedHashMap(Map<? extends K,? extends V> m)Constructs an insertion-ordered LinkedHashMap instance with the same mappings as the specified map.

Methods

Modifier and TypeMethodDescription
booleancontainsValue(Object value)Returns true if this map maps one or more keys to the specified value.
Set<Map.Entry<K,V>>entrySet()Returns a Set view of the mappings contained in this map.
Vget(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
Set<K>keySet()Returns a Set view of the keys contained in this map.
protected booleanremoveEldestEntry(Map.Entry<K,V> eldest)Returns true if this map should remove its eldest entry.
Collection<V>values()Returns a Collection view of the values contained in this map.

Dictionary<K,V>

public abstract class Dictionary<K,V>
extends Object

The Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values. Every key and every value is an object. In any one Dictionary object, every key is associated with at most one value. Given a Dictionary and a key, the associated element can be looked up. Any non-null object can be used as a key and as a value.

As a rule, the equals method should be used by implementations of this class to decide if two keys are the same.

NOTE: This class is obsolete. New implementations should implement the Map interface, rather than extending this class.

Constructors

ConstructorDescription
Dictionary()Sole constructor.

Methods

Modifier and TypeMethodDescription
abstract Enumeration<V>elements()Returns an enumeration of the values in this dictionary.
abstract Vget(Object key)Returns the value to which the key is mapped in this dictionary.
abstract booleanisEmpty()Tests if this dictionary maps no keys to value.
abstract Enumeration<K>keys()Returns an enumeration of the keys in this dictionary.
abstract Vput(K key, V value)Maps the specified key to the specified value in this dictionary.
abstract Vremove(Object key)Removes the key (and its corresponding value) from this dictionary.
abstract intsize()Returns the number of entries (distinct keys) in this dictionary.
Hashtable<K,V>
public class Hashtable<K, V>
extends Dictionary<K, V>
implements Map<K, V>, Cloneable, Serializable

This class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value.

To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a “hash collision”, a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.

Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put).

The initial capacity controls a tradeoff between wasted space and the need for rehash operations, which are time-consuming. No rehash operations will ever occur if the initial capacity is greater than the maximum number of entries the Hashtable will contain divided by its load factor. However, setting the initial capacity too high can waste space.

If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

This example creates a hashtable of numbers. It uses the names of the numbers as keys:

   Hashtable<String, Integer> numbers
     = new Hashtable<String, Integer>();
   numbers.put("one", 1);
   numbers.put("two", 2);
   numbers.put("three", 3);

To retrieve a number, use the following code:

   Integer n = numbers.get("two");
   if (n != null) {
     System.out.println("two = " + n);
   }

The iterators returned by the iterator method of the collections returned by all of this class’s “collection view methods” are fail-fast: if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Hashtable’s keys and elements methods are not fail-fast; if the Hashtable is structurally modified at any time after the enumeration is created then the results of enumerating are undefined.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

Constructors

ConstructorDescription
Hashtable()Constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75).
Hashtable(int initialCapacity)Constructs a new, empty hashtable with the specified initial capacity and default load factor (0.75).
Hashtable(int initialCapacity, float loadFactor)Constructs a new, empty hashtable with the specified initial capacity and the specified load factor.
Hashtable(Map<? extends K,? extends V> t)Constructs a new hashtable with the same mappings as the given Map.

Methods

Modifier and TypeMethodDescription
voidclear()Clears this hashtable so that it contains no keys.
Objectclone()Creates a shallow copy of this hashtable.
Vcompute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
VcomputeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
VcomputeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
booleancontains(Object value)Tests if some key maps into the specified value in this hashtable.
booleancontainsKey(Object key)Tests if the specified object is a key in this hashtable.
booleancontainsValue(Object value)Returns true if this hashtable maps one or more keys to this value.
Enumeration<V>elements()Returns an enumeration of the values in this hashtable.
Set<Map.Entry<K,V>>entrySet()Returns a Set view of the mappings contained in this map.
booleanequals(Object o)Compares the specified Object with this Map for equality, as per the definition in the Map interface.
Vget(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
inthashCode()Returns the hash code value for this Map as per the definition in the Map interface.
booleanisEmpty()Tests if this hashtable maps no keys to values.
Enumeration<K>keys()Returns an enumeration of the keys in this hashtable.
Set<K>keySet()Returns a Set view of the keys contained in this map.
Vmerge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
Vput(K key, V value)Maps the specified key to the specified value in this hashtable.
voidputAll(Map<? extends K,? extends V> t)Copies all of the mappings from the specified map to this hashtable.
protected voidrehash()Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently.
Vremove(Object key)Removes the key (and its corresponding value) from this hashtable.
intsize()Returns the number of keys in this hashtable.
StringtoString()Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters “,” (comma and space).
Collection<V>values()Returns a Collection view of the values contained in this map.
Properties
public class Properties
extends Hashtable<Object, Object>

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

A property list can contain another property list as its “defaults”; this second property list is searched if the property key is not found in the original property list.

Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a “compromised” Properties object that contains a non-String key or value, the call will fail. Similarly, the call to the propertyNames or list method will fail if it is called on a “compromised” Properties object that contains a non-String key.

The iterators returned by the iterator method of this class’s “collection views” (that is, entrySet(), keySet(), and values()) may not fail-fast (unlike the Hashtable implementation). These iterators are guaranteed to traverse elements as they existed upon construction exactly once, and may (but are not guaranteed to) reflect any modifications subsequent to construction.

The load(Reader) / store(Writer, String) methods load and store properties from and to a character based stream in a simple line-oriented format specified below. The load(InputStream) / store(OutputStream, String) methods work the same way as the load(Reader)/store(Writer, String) pair, except the input/output stream is encoded in ISO 8859-1 character encoding. Characters that cannot be directly represented in this encoding can be written using Unicode escapes as defined in section 3.3 of The Java™ Language Specification; only a single ‘u’ character is allowed in an escape sequence.

The loadFromXML(InputStream) and storeToXML(OutputStream, String, String) methods load and store properties in a simple XML format. By default the UTF-8 character encoding is used, however a specific encoding may be specified if required. Implementations are required to support UTF-8 and UTF-16 and may support other encodings. An XML properties document has the following DOCTYPE declaration:

 <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
 

Note that the system URI (http://java.sun.com/dtd/properties.dtd) is not accessed when exporting or importing properties; it merely serves as a string to uniquely identify the DTD, which is:

    <?xml version="1.0" encoding="UTF-8"?>

    <!-- DTD for properties -->

    <!ELEMENT properties ( comment?, entry* ) >

    <!ATTLIST properties version CDATA #FIXED "1.0">

    <!ELEMENT comment (#PCDATA) >

    <!ELEMENT entry (#PCDATA) >

    <!ATTLIST entry key CDATA #REQUIRED>
 

This class is thread-safe: multiple threads can share a single Properties object without the need for external synchronization.

  • API Note:

    The Properties class does not inherit the concept of a load factor from its superclass, Hashtable.

Fields

Modifier and TypeFieldDescription
protected PropertiesdefaultsA property list that contains default values for any keys not found in this property list.

Constructors

ConstructorDescription
Properties()Creates an empty property list with no default values.
Properties(int initialCapacity)Creates an empty property list with no default values, and with an initial size accommodating the specified number of elements without the need to dynamically resize.
Properties(Properties defaults)Creates an empty property list with the specified defaults.

Methods

Modifier and TypeMethodDescription
StringgetProperty(String key)Searches for the property with the specified key in this property list.
StringgetProperty(String key, String defaultValue)Searches for the property with the specified key in this property list.
voidlist(PrintStream out)Prints this property list out to the specified output stream.
voidlist(PrintWriter out)Prints this property list out to the specified output stream.
voidload(InputStream inStream)Reads a property list (key and element pairs) from the input byte stream.
voidload(Reader reader)Reads a property list (key and element pairs) from the input character stream in a simple line-oriented format.
voidloadFromXML(InputStream in)Loads all of the properties represented by the XML document on the specified input stream into this properties table.
Enumeration<?>propertyNames()Returns an enumeration of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.
voidsave(OutputStream out, String comments)**Deprecated.**This method does not throw an IOException if an I/O error occurs while saving the property list.
ObjectsetProperty(String key, String value)Calls the Hashtable method put.
voidstore(OutputStream out, String comments)Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method.
voidstore(Writer writer, String comments)Writes this property list (key and element pairs) in this Properties table to the output character stream in a format suitable for using the load(Reader) method.
voidstoreToXML(OutputStream os, String comment)Emits an XML document representing all of the properties contained in this table.
voidstoreToXML(OutputStream os, String comment, String encoding)Emits an XML document representing all of the properties contained in this table, using the specified encoding.
voidstoreToXML(OutputStream os, String comment, Charset charset)Emits an XML document representing all of the properties contained in this table, using the specified encoding.
Set<String>stringPropertyNames()Returns an unmodifiable set of keys from this property list where the key and its corresponding value are strings, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.

SortedMap<K,V>接口

public interface SortedMap<K, V>
extends Map<K, V>

A Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map’s collection views (returned by the entrySet, keySet and values methods). Several additional operations are provided to take advantage of the ordering. (This interface is the map analogue of SortedSet.)

All keys inserted into a sorted map must implement the Comparable interface (or be accepted by the specified comparator). Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) (or comparator.compare(k1, k2)) must not throw a ClassCastException for any keys k1 and k2 in the sorted map. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException.

Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if the sorted map is to correctly implement the Map interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a tree map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

All general-purpose sorted map implementation classes should provide four “standard” constructors. It is not possible to enforce this recommendation though as required constructors cannot be specified by interfaces. The expected “standard” constructors for all sorted map implementations are:

  1. A void (no arguments) constructor, which creates an empty sorted map sorted according to the natural ordering of its keys.
  2. A constructor with a single argument of type Comparator, which creates an empty sorted map sorted according to the specified comparator.
  3. A constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument, sorted according to the keys’ natural ordering.
  4. A constructor with a single argument of type SortedMap, which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map.

Note: several methods return submaps with restricted key ranges. Such ranges are half-open, that is, they include their low endpoint but not their high endpoint (where applicable). If you need a closed range (which includes both endpoints), and the key type allows for calculation of the successor of a given key, merely request the subrange from lowEndpoint to successor(highEndpoint). For example, suppose that m is a map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high, inclusive:

   SortedMap<String, V> sub = m.subMap(low, high+"\0");

A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high, exclusive:

   SortedMap<String, V> sub = m.subMap(low+"\0", high);

Methods

Modifier and TypeMethodDescription
Comparator<? super K>comparator()Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.
Set<Map.Entry<K,V>>entrySet()Returns a Set view of the mappings contained in this map.
KfirstKey()Returns the first (lowest) key currently in this map.
SortedMap<K,V>headMap(K toKey)Returns a view of the portion of this map whose keys are strictly less than toKey.
Set<K>keySet()Returns a Set view of the keys contained in this map.
KlastKey()Returns the last (highest) key currently in this map.
SortedMap<K,V>subMap(K fromKey, K toKey)Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
SortedMap<K,V>tailMap(K fromKey)Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
Collection<V>values()Returns a Collection view of the values contained in this map.
NavigableMap<K,V>接口
public interface NavigableMap<K, V>
extends SortedMap<K, V>

A SortedMap extended with navigation methods returning the closest matches for given search targets. Methods lowerEntry(K), floorEntry(K), ceilingEntry(K), and higherEntry(K) return Map.Entry objects associated with keys respectively less than, less than or equal, greater than or equal, and greater than a given key, returning null if there is no such key. Similarly, methods lowerKey(K), floorKey(K), ceilingKey(K), and higherKey(K) return only the associated keys. All of these methods are designed for locating, not traversing entries.

A NavigableMap may be accessed and traversed in either ascending or descending key order. The descendingMap() method returns a view of the map with the senses of all relational and directional methods inverted. The performance of ascending operations and views is likely to be faster than that of descending ones. Methods subMap(K, boolean, K, boolean), headMap(K, boolean), and tailMap(K, boolean) differ from the like-named SortedMap methods in accepting additional arguments describing whether lower and upper bounds are inclusive versus exclusive. Submaps of any NavigableMap must implement the NavigableMap interface.

This interface additionally defines methods firstEntry(), pollFirstEntry(), lastEntry(), and pollLastEntry() that return and/or remove the least and greatest mappings, if any exist, else returning null.

Implementations of entry-returning methods are expected to return Map.Entry pairs representing snapshots of mappings at the time they were produced, and thus generally do not support the optional Entry.setValue method. Note however that it is possible to change mappings in the associated map using method put.

Methods subMap(K, K), headMap(K), and tailMap(K) are specified to return SortedMap to allow existing implementations of SortedMap to be compatibly retrofitted to implement NavigableMap, but extensions and implementations of this interface are encouraged to override these methods to return NavigableMap. Similarly, SortedMap.keySet() can be overridden to return NavigableSet.

TreeMap<K,V>
public class TreeMap<K, V>
extends AbstractMap<K, V>
implements NavigableMap<K, V>, Cloneable, Serializable

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest’s Introduction to Algorithms.

Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be “wrapped” using the Collections.synchronizedSortedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

   SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));

The iterators returned by the iterator method of the collections returned by all of this class’s “collection view methods” are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
All Map.Entry pairs returned by methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method. (Note however that it is possible to change mappings in the associated map using put.)
Constructors

ConstructorDescription
TreeMap()Constructs a new, empty tree map, using the natural ordering of its keys.
TreeMap(Comparator<? super K> comparator)Constructs a new, empty tree map, ordered according to the given comparator.
TreeMap(Map<? extends K,? extends V> m)Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys.
TreeMap(SortedMap<K,? extends V> m)Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map.

Methods

Modifier and TypeMethodDescription
Map.Entry<K,V>ceilingEntry(K key)Returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key.
KceilingKey(K key)Returns the least key greater than or equal to the given key, or null if there is no such key.
voidclear()Removes all of the mappings from this map.
Objectclone()Returns a shallow copy of this TreeMap instance.
booleancontainsKey(Object key)Returns true if this map contains a mapping for the specified key.
booleancontainsValue(Object value)Returns true if this map maps one or more keys to the specified value.
NavigableSet<K>descendingKeySet()Returns a reverse order NavigableSet view of the keys contained in this map.
NavigableMap<K,V>descendingMap()Returns a reverse order view of the mappings contained in this map.
Set<Map.Entry<K,V>>entrySet()Returns a Set view of the mappings contained in this map.
Map.Entry<K,V>firstEntry()Returns a key-value mapping associated with the least key in this map, or null if the map is empty.
KfirstKey()Returns the first (lowest) key currently in this map.
Map.Entry<K,V>floorEntry(K key)Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.
KfloorKey(K key)Returns the greatest key less than or equal to the given key, or null if there is no such key.
Vget(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
SortedMap<K,V>headMap(K toKey)Returns a view of the portion of this map whose keys are strictly less than toKey.
NavigableMap<K,V>headMap(K toKey, boolean inclusive)Returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.
Map.Entry<K,V>higherEntry(K key)Returns a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key.
KhigherKey(K key)Returns the least key strictly greater than the given key, or null if there is no such key.
Set<K>keySet()Returns a Set view of the keys contained in this map.
Map.Entry<K,V>lastEntry()Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
KlastKey()Returns the last (highest) key currently in this map.
Map.Entry<K,V>lowerEntry(K key)Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
KlowerKey(K key)Returns the greatest key strictly less than the given key, or null if there is no such key.
NavigableSet<K>navigableKeySet()Returns a NavigableSet view of the keys contained in this map.
Map.Entry<K,V>pollFirstEntry()Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
Map.Entry<K,V>pollLastEntry()Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
Vput(K key, V value)Associates the specified value with the specified key in this map.
voidputAll(Map<? extends K,? extends V> map)Copies all of the mappings from the specified map to this map.
Vremove(Object key)Removes the mapping for this key from this TreeMap if present.
intsize()Returns the number of key-value mappings in this map.
NavigableMap<K,V>subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)Returns a view of the portion of this map whose keys range from fromKey to toKey.
SortedMap<K,V>subMap(K fromKey, K toKey)Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
SortedMap<K,V>tailMap(K fromKey)Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
NavigableMap<K,V>tailMap(K fromKey, boolean inclusive)Returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.
Collection<V>values()Returns a Collection view of the values contained in this map.

Collections

public class Collections
extends Object

This class consists exclusively of static methods that operate on or return collections.

Fields

Modifier and TypeFieldDescription
static ListEMPTY_LISTThe empty list (immutable).
static MapEMPTY_MAPThe empty map (immutable).
static SetEMPTY_SETThe empty set (immutable).

Methods

Modifier and TypeMethodDescription
static <T> booleanaddAll(Collection<? super T> c, T... elements)Adds all of the specified elements to the specified collection.
static <T> Queue<T>asLifoQueue(Deque<T> deque)Returns a view of a Deque as a Last-in-first-out (Lifo) Queue.
static <T> intbinarySearch(List<? extends Comparable<? super T>> list, T key)Searches the specified list for the specified object using the binary search algorithm.
static <T> intbinarySearch(List<? extends T> list, T key, Comparator<? super T> c)Searches the specified list for the specified object using the binary search algorithm.
static <E> Collection<E>checkedCollection(Collection<E> c, Class<E> type)Returns a dynamically typesafe view of the specified collection.
static <E> List<E>checkedList(List<E> list, Class<E> type)Returns a dynamically typesafe view of the specified list.
static <K,V>Map<K,V>checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType)Returns a dynamically typesafe view of the specified map.
static <K,V>NavigableMap<K,V>checkedNavigableMap(NavigableMap<K,V> m, Class<K> keyType, Class<V> valueType)Returns a dynamically typesafe view of the specified navigable map.
static <E> NavigableSet<E>checkedNavigableSet(NavigableSet<E> s, Class<E> type)Returns a dynamically typesafe view of the specified navigable set.
static <E> Queue<E>checkedQueue(Queue<E> queue, Class<E> type)Returns a dynamically typesafe view of the specified queue.
static <E> Set<E>checkedSet(Set<E> s, Class<E> type)Returns a dynamically typesafe view of the specified set.
static <K,V>SortedMap<K,V>checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType)Returns a dynamically typesafe view of the specified sorted map.
static <E> SortedSet<E>checkedSortedSet(SortedSet<E> s, Class<E> type)Returns a dynamically typesafe view of the specified sorted set.
static <T> voidcopy(List<? super T> dest, List<? extends T> src)Copies all of the elements from one list into another.
static booleandisjoint(Collection<?> c1, Collection<?> c2)Returns true if the two specified collections have no elements in common.
static <T> Enumeration<T>emptyEnumeration()Returns an enumeration that has no elements.
static <T> Iterator<T>emptyIterator()Returns an iterator that has no elements.
static <T> List<T>emptyList()Returns an empty list (immutable).
static <T> ListIterator<T>emptyListIterator()Returns a list iterator that has no elements.
static <K,V>Map<K,V>emptyMap()Returns an empty map (immutable).
static <K,V>NavigableMap<K,V>emptyNavigableMap()Returns an empty navigable map (immutable).
static <E> NavigableSet<E>emptyNavigableSet()Returns an empty navigable set (immutable).
static <T> Set<T>emptySet()Returns an empty set (immutable).
static <K,V>SortedMap<K,V>emptySortedMap()Returns an empty sorted map (immutable).
static <E> SortedSet<E>emptySortedSet()Returns an empty sorted set (immutable).
static <T> Enumeration<T>enumeration(Collection<T> c)Returns an enumeration over the specified collection.
static <T> voidfill(List<? super T> list, T obj)Replaces all of the elements of the specified list with the specified element.
static intfrequency(Collection<?> c, Object o)Returns the number of elements in the specified collection equal to the specified object.
static intindexOfSubList(List<?> source, List<?> target)Returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
static intlastIndexOfSubList(List<?> source, List<?> target)Returns the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
static <T> ArrayList<T>list(Enumeration<T> e)Returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.
static <T extends Object & Comparable<? super T>>Tmax(Collection<? extends T> coll)Returns the maximum element of the given collection, according to the natural ordering of its elements.
static <T> Tmax(Collection<? extends T> coll, Comparator<? super T> comp)Returns the maximum element of the given collection, according to the order induced by the specified comparator.
static <T extends Object & Comparable<? super T>>Tmin(Collection<? extends T> coll)Returns the minimum element of the given collection, according to the natural ordering of its elements.
static <T> Tmin(Collection<? extends T> coll, Comparator<? super T> comp)Returns the minimum element of the given collection, according to the order induced by the specified comparator.
static <T> List<T>nCopies(int n, T o)Returns an immutable list consisting of n copies of the specified object.
static <E> Set<E>newSetFromMap(Map<E,Boolean> map)Returns a set backed by the specified map.
static <T> booleanreplaceAll(List<T> list, T oldVal, T newVal)Replaces all occurrences of one specified value in a list with another.
static voidreverse(List<?> list)Reverses the order of the elements in the specified list.
static <T> Comparator<T>reverseOrder()Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
static <T> Comparator<T>reverseOrder(Comparator<T> cmp)Returns a comparator that imposes the reverse ordering of the specified comparator.
static voidrotate(List<?> list, int distance)Rotates the elements in the specified list by the specified distance.
static voidshuffle(List<?> list)Randomly permutes the specified list using a default source of randomness.
static voidshuffle(List<?> list, Random rnd)Randomly permute the specified list using the specified source of randomness.
static <T> Set<T>singleton(T o)Returns an immutable set containing only the specified object.
static <T> List<T>singletonList(T o)Returns an immutable list containing only the specified object.
static <K,V>Map<K,V>singletonMap(K key, V value)Returns an immutable map, mapping only the specified key to the specified value.
static <T extends Comparable<? super T>>voidsort(List<T> list)Sorts the specified list into ascending order, according to the natural ordering of its elements.
static <T> voidsort(List<T> list, Comparator<? super T> c)Sorts the specified list according to the order induced by the specified comparator.
static voidswap(List<?> list, int i, int j)Swaps the elements at the specified positions in the specified list.
static <T> Collection<T>synchronizedCollection(Collection<T> c)Returns a synchronized (thread-safe) collection backed by the specified collection.
static <T> List<T>synchronizedList(List<T> list)Returns a synchronized (thread-safe) list backed by the specified list.
static <K,V>Map<K,V>synchronizedMap(Map<K,V> m)Returns a synchronized (thread-safe) map backed by the specified map.
static <K,V>NavigableMap<K,V>synchronizedNavigableMap(NavigableMap<K,V> m)Returns a synchronized (thread-safe) navigable map backed by the specified navigable map.
static <T> NavigableSet<T>synchronizedNavigableSet(NavigableSet<T> s)Returns a synchronized (thread-safe) navigable set backed by the specified navigable set.
static <T> Set<T>synchronizedSet(Set<T> s)Returns a synchronized (thread-safe) set backed by the specified set.
static <K,V>SortedMap<K,V>synchronizedSortedMap(SortedMap<K,V> m)Returns a synchronized (thread-safe) sorted map backed by the specified sorted map.
static <T> SortedSet<T>synchronizedSortedSet(SortedSet<T> s)Returns a synchronized (thread-safe) sorted set backed by the specified sorted set.
static <T> Collection<T>unmodifiableCollection(Collection<? extends T> c)Returns an unmodifiable view of the specified collection.
static <T> List<T>unmodifiableList(List<? extends T> list)Returns an unmodifiable view of the specified list.
static <K,V>Map<K,V>unmodifiableMap(Map<? extends K,? extends V> m)Returns an unmodifiable view of the specified map.
static <K,V>NavigableMap<K,V>unmodifiableNavigableMap(NavigableMap<K,? extends V> m)Returns an unmodifiable view of the specified navigable map.
static <T> NavigableSet<T>unmodifiableNavigableSet(NavigableSet<T> s)Returns an unmodifiable view of the specified navigable set.
static <T> Set<T>unmodifiableSet(Set<? extends T> s)Returns an unmodifiable view of the specified set.
static <K,V>SortedMap<K,V>unmodifiableSortedMap(SortedMap<K,? extends V> m)Returns an unmodifiable view of the specified sorted map.
static <T> SortedSet<T>unmodifiableSortedSet(SortedSet<T> s)Returns an unmodifiable view of the specified sorted set.

Arrays

public class Arrays
extends Object

This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.

The methods in this class all throw a NullPointerException, if the specified array reference is null, except where noted.

Methods

Modifier and TypeMethodDescription
static <T> List<T>asList(T... a)Returns a fixed-size list backed by the specified array.
static intbinarySearch(byte[] a, byte key)Searches the specified array of bytes for the specified value using the binary search algorithm.
static intbinarySearch(byte[] a, int fromIndex, int toIndex, byte key)Searches a range of the specified array of bytes for the specified value using the binary search algorithm.
static intbinarySearch(char[] a, char key)Searches the specified array of chars for the specified value using the binary search algorithm.
static intbinarySearch(char[] a, int fromIndex, int toIndex, char key)Searches a range of the specified array of chars for the specified value using the binary search algorithm.
static intbinarySearch(double[] a, double key)Searches the specified array of doubles for the specified value using the binary search algorithm.
static intbinarySearch(double[] a, int fromIndex, int toIndex, double key)Searches a range of the specified array of doubles for the specified value using the binary search algorithm.
static intbinarySearch(float[] a, float key)Searches the specified array of floats for the specified value using the binary search algorithm.
static intbinarySearch(float[] a, int fromIndex, int toIndex, float key)Searches a range of the specified array of floats for the specified value using the binary search algorithm.
static intbinarySearch(int[] a, int key)Searches the specified array of ints for the specified value using the binary search algorithm.
static intbinarySearch(int[] a, int fromIndex, int toIndex, int key)Searches a range of the specified array of ints for the specified value using the binary search algorithm.
static intbinarySearch(long[] a, int fromIndex, int toIndex, long key)Searches a range of the specified array of longs for the specified value using the binary search algorithm.
static intbinarySearch(long[] a, long key)Searches the specified array of longs for the specified value using the binary search algorithm.
static intbinarySearch(short[] a, int fromIndex, int toIndex, short key)Searches a range of the specified array of shorts for the specified value using the binary search algorithm.
static intbinarySearch(short[] a, short key)Searches the specified array of shorts for the specified value using the binary search algorithm.
static intbinarySearch(Object[] a, int fromIndex, int toIndex, Object key)Searches a range of the specified array for the specified object using the binary search algorithm.
static intbinarySearch(Object[] a, Object key)Searches the specified array for the specified object using the binary search algorithm.
static <T> intbinarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)Searches a range of the specified array for the specified object using the binary search algorithm.
static <T> intbinarySearch(T[] a, T key, Comparator<? super T> c)Searches the specified array for the specified object using the binary search algorithm.
static intcompare(boolean[] a, boolean[] b)Compares two boolean arrays lexicographically.
static intcompare(boolean[] a, int aFromIndex, int aToIndex, boolean[] b, int bFromIndex, int bToIndex)Compares two boolean arrays lexicographically over the specified ranges.
static intcompare(byte[] a, byte[] b)Compares two byte arrays lexicographically.
static intcompare(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Compares two byte arrays lexicographically over the specified ranges.
static intcompare(char[] a, char[] b)Compares two char arrays lexicographically.
static intcompare(char[] a, int aFromIndex, int aToIndex, char[] b, int bFromIndex, int bToIndex)Compares two char arrays lexicographically over the specified ranges.
static intcompare(double[] a, double[] b)Compares two double arrays lexicographically.
static intcompare(double[] a, int aFromIndex, int aToIndex, double[] b, int bFromIndex, int bToIndex)Compares two double arrays lexicographically over the specified ranges.
static intcompare(float[] a, float[] b)Compares two float arrays lexicographically.
static intcompare(float[] a, int aFromIndex, int aToIndex, float[] b, int bFromIndex, int bToIndex)Compares two float arrays lexicographically over the specified ranges.
static intcompare(int[] a, int[] b)Compares two int arrays lexicographically.
static intcompare(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Compares two int arrays lexicographically over the specified ranges.
static intcompare(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Compares two long arrays lexicographically over the specified ranges.
static intcompare(long[] a, long[] b)Compares two long arrays lexicographically.
static intcompare(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Compares two short arrays lexicographically over the specified ranges.
static intcompare(short[] a, short[] b)Compares two short arrays lexicographically.
static <T extends Comparable<? super T>>intcompare(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex)Compares two Object arrays lexicographically over the specified ranges.
static <T> intcompare(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)Compares two Object arrays lexicographically over the specified ranges.
static <T extends Comparable<? super T>>intcompare(T[] a, T[] b)Compares two Object arrays, within comparable elements, lexicographically.
static <T> intcompare(T[] a, T[] b, Comparator<? super T> cmp)Compares two Object arrays lexicographically using a specified comparator.
static intcompareUnsigned(byte[] a, byte[] b)Compares two byte arrays lexicographically, numerically treating elements as unsigned.
static intcompareUnsigned(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Compares two byte arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
static intcompareUnsigned(int[] a, int[] b)Compares two int arrays lexicographically, numerically treating elements as unsigned.
static intcompareUnsigned(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Compares two int arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
static intcompareUnsigned(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Compares two long arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
static intcompareUnsigned(long[] a, long[] b)Compares two long arrays lexicographically, numerically treating elements as unsigned.
static intcompareUnsigned(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Compares two short arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
static intcompareUnsigned(short[] a, short[] b)Compares two short arrays lexicographically, numerically treating elements as unsigned.
static boolean[]copyOf(boolean[] original, int newLength)Copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.
static byte[]copyOf(byte[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
static char[]copyOf(char[] original, int newLength)Copies the specified array, truncating or padding with null characters (if necessary) so the copy has the specified length.
static double[]copyOf(double[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
static float[]copyOf(float[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
static int[]copyOf(int[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
static long[]copyOf(long[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
static short[]copyOf(short[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
static <T> T[]copyOf(T[] original, int newLength)Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.
static <T,U>T[]copyOf(U[] original, int newLength, Class<? extends T[]> newType)Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.
static boolean[]copyOfRange(boolean[] original, int from, int to)Copies the specified range of the specified array into a new array.
static byte[]copyOfRange(byte[] original, int from, int to)Copies the specified range of the specified array into a new array.
static char[]copyOfRange(char[] original, int from, int to)Copies the specified range of the specified array into a new array.
static double[]copyOfRange(double[] original, int from, int to)Copies the specified range of the specified array into a new array.
static float[]copyOfRange(float[] original, int from, int to)Copies the specified range of the specified array into a new array.
static int[]copyOfRange(int[] original, int from, int to)Copies the specified range of the specified array into a new array.
static long[]copyOfRange(long[] original, int from, int to)Copies the specified range of the specified array into a new array.
static short[]copyOfRange(short[] original, int from, int to)Copies the specified range of the specified array into a new array.
static <T> T[]copyOfRange(T[] original, int from, int to)Copies the specified range of the specified array into a new array.
static <T,U>T[]copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)Copies the specified range of the specified array into a new array.
static booleandeepEquals(Object[] a1, Object[] a2)Returns true if the two specified arrays are deeply equal to one another.
static intdeepHashCode(Object[] a)Returns a hash code based on the “deep contents” of the specified array.
static StringdeepToString(Object[] a)Returns a string representation of the “deep contents” of the specified array.
static booleanequals(boolean[] a, boolean[] a2)Returns true if the two specified arrays of booleans are equal to one another.
static booleanequals(boolean[] a, int aFromIndex, int aToIndex, boolean[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of booleans, over the specified ranges, are equal to one another.
static booleanequals(byte[] a, byte[] a2)Returns true if the two specified arrays of bytes are equal to one another.
static booleanequals(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of bytes, over the specified ranges, are equal to one another.
static booleanequals(char[] a, char[] a2)Returns true if the two specified arrays of chars are equal to one another.
static booleanequals(char[] a, int aFromIndex, int aToIndex, char[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of chars, over the specified ranges, are equal to one another.
static booleanequals(double[] a, double[] a2)Returns true if the two specified arrays of doubles are equal to one another.
static booleanequals(double[] a, int aFromIndex, int aToIndex, double[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of doubles, over the specified ranges, are equal to one another.
static booleanequals(float[] a, float[] a2)Returns true if the two specified arrays of floats are equal to one another.
static booleanequals(float[] a, int aFromIndex, int aToIndex, float[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of floats, over the specified ranges, are equal to one another.
static booleanequals(int[] a, int[] a2)Returns true if the two specified arrays of ints are equal to one another.
static booleanequals(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of ints, over the specified ranges, are equal to one another.
static booleanequals(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of longs, over the specified ranges, are equal to one another.
static booleanequals(long[] a, long[] a2)Returns true if the two specified arrays of longs are equal to one another.
static booleanequals(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of shorts, over the specified ranges, are equal to one another.
static booleanequals(short[] a, short[] a2)Returns true if the two specified arrays of shorts are equal to one another.
static booleanequals(Object[] a, int aFromIndex, int aToIndex, Object[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of Objects, over the specified ranges, are equal to one another.
static booleanequals(Object[] a, Object[] a2)Returns true if the two specified arrays of Objects are equal to one another.
static <T> booleanequals(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)Returns true if the two specified arrays of Objects, over the specified ranges, are equal to one another.
static <T> booleanequals(T[] a, T[] a2, Comparator<? super T> cmp)Returns true if the two specified arrays of Objects are equal to one another.
static voidfill(boolean[] a, boolean val)Assigns the specified boolean value to each element of the specified array of booleans.
static voidfill(boolean[] a, int fromIndex, int toIndex, boolean val)Assigns the specified boolean value to each element of the specified range of the specified array of booleans.
static voidfill(byte[] a, byte val)Assigns the specified byte value to each element of the specified array of bytes.
static voidfill(byte[] a, int fromIndex, int toIndex, byte val)Assigns the specified byte value to each element of the specified range of the specified array of bytes.
static voidfill(char[] a, char val)Assigns the specified char value to each element of the specified array of chars.
static voidfill(char[] a, int fromIndex, int toIndex, char val)Assigns the specified char value to each element of the specified range of the specified array of chars.
static voidfill(double[] a, double val)Assigns the specified double value to each element of the specified array of doubles.
static voidfill(double[] a, int fromIndex, int toIndex, double val)Assigns the specified double value to each element of the specified range of the specified array of doubles.
static voidfill(float[] a, float val)Assigns the specified float value to each element of the specified array of floats.
static voidfill(float[] a, int fromIndex, int toIndex, float val)Assigns the specified float value to each element of the specified range of the specified array of floats.
static voidfill(int[] a, int val)Assigns the specified int value to each element of the specified array of ints.
static voidfill(int[] a, int fromIndex, int toIndex, int val)Assigns the specified int value to each element of the specified range of the specified array of ints.
static voidfill(long[] a, int fromIndex, int toIndex, long val)Assigns the specified long value to each element of the specified range of the specified array of longs.
static voidfill(long[] a, long val)Assigns the specified long value to each element of the specified array of longs.
static voidfill(short[] a, int fromIndex, int toIndex, short val)Assigns the specified short value to each element of the specified range of the specified array of shorts.
static voidfill(short[] a, short val)Assigns the specified short value to each element of the specified array of shorts.
static voidfill(Object[] a, int fromIndex, int toIndex, Object val)Assigns the specified Object reference to each element of the specified range of the specified array of Objects.
static voidfill(Object[] a, Object val)Assigns the specified Object reference to each element of the specified array of Objects.
static inthashCode(boolean[] a)Returns a hash code based on the contents of the specified array.
static inthashCode(byte[] a)Returns a hash code based on the contents of the specified array.
static inthashCode(char[] a)Returns a hash code based on the contents of the specified array.
static inthashCode(double[] a)Returns a hash code based on the contents of the specified array.
static inthashCode(float[] a)Returns a hash code based on the contents of the specified array.
static inthashCode(int[] a)Returns a hash code based on the contents of the specified array.
static inthashCode(long[] a)Returns a hash code based on the contents of the specified array.
static inthashCode(short[] a)Returns a hash code based on the contents of the specified array.
static inthashCode(Object[] a)Returns a hash code based on the contents of the specified array.
static intmismatch(boolean[] a, boolean[] b)Finds and returns the index of the first mismatch between two boolean arrays, otherwise return -1 if no mismatch is found.
static intmismatch(boolean[] a, int aFromIndex, int aToIndex, boolean[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two boolean arrays over the specified ranges, otherwise return -1 if no mismatch is found.
static intmismatch(byte[] a, byte[] b)Finds and returns the index of the first mismatch between two byte arrays, otherwise return -1 if no mismatch is found.
static intmismatch(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two byte arrays over the specified ranges, otherwise return -1 if no mismatch is found.
static intmismatch(char[] a, char[] b)Finds and returns the index of the first mismatch between two char arrays, otherwise return -1 if no mismatch is found.
static intmismatch(char[] a, int aFromIndex, int aToIndex, char[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two char arrays over the specified ranges, otherwise return -1 if no mismatch is found.
static intmismatch(double[] a, double[] b)Finds and returns the index of the first mismatch between two double arrays, otherwise return -1 if no mismatch is found.
static intmismatch(double[] a, int aFromIndex, int aToIndex, double[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two double arrays over the specified ranges, otherwise return -1 if no mismatch is found.
static intmismatch(float[] a, float[] b)Finds and returns the index of the first mismatch between two float arrays, otherwise return -1 if no mismatch is found.
static intmismatch(float[] a, int aFromIndex, int aToIndex, float[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two float arrays over the specified ranges, otherwise return -1 if no mismatch is found.
static intmismatch(int[] a, int[] b)Finds and returns the index of the first mismatch between two int arrays, otherwise return -1 if no mismatch is found.
static intmismatch(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two int arrays over the specified ranges, otherwise return -1 if no mismatch is found.
static intmismatch(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two long arrays over the specified ranges, otherwise return -1 if no mismatch is found.
static intmismatch(long[] a, long[] b)Finds and returns the index of the first mismatch between two long arrays, otherwise return -1 if no mismatch is found.
static intmismatch(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two short arrays over the specified ranges, otherwise return -1 if no mismatch is found.
static intmismatch(short[] a, short[] b)Finds and returns the index of the first mismatch between two short arrays, otherwise return -1 if no mismatch is found.
static intmismatch(Object[] a, int aFromIndex, int aToIndex, Object[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two Object arrays over the specified ranges, otherwise return -1 if no mismatch is found.
static intmismatch(Object[] a, Object[] b)Finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found.
static <T> intmismatch(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)Finds and returns the relative index of the first mismatch between two Object arrays over the specified ranges, otherwise return -1 if no mismatch is found.
static <T> intmismatch(T[] a, T[] b, Comparator<? super T> cmp)Finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found.
static voidparallelPrefix(double[] array, int fromIndex, int toIndex, DoubleBinaryOperator op)Performs parallelPrefix(double[\], DoubleBinaryOperator) for the given subrange of the array.
static voidparallelPrefix(double[] array, DoubleBinaryOperator op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
static voidparallelPrefix(int[] array, int fromIndex, int toIndex, IntBinaryOperator op)Performs parallelPrefix(int[\], IntBinaryOperator) for the given subrange of the array.
static voidparallelPrefix(int[] array, IntBinaryOperator op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
static voidparallelPrefix(long[] array, int fromIndex, int toIndex, LongBinaryOperator op)Performs parallelPrefix(long[\], LongBinaryOperator) for the given subrange of the array.
static voidparallelPrefix(long[] array, LongBinaryOperator op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
static <T> voidparallelPrefix(T[] array, int fromIndex, int toIndex, BinaryOperator<T> op)Performs parallelPrefix(Object[\], BinaryOperator) for the given subrange of the array.
static <T> voidparallelPrefix(T[] array, BinaryOperator<T> op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
static voidparallelSetAll(double[] array, IntToDoubleFunction generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
static voidparallelSetAll(int[] array, IntUnaryOperator generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
static voidparallelSetAll(long[] array, IntToLongFunction generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
static <T> voidparallelSetAll(T[] array, IntFunction<? extends T> generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
static voidparallelSort(byte[] a)Sorts the specified array into ascending numerical order.
static voidparallelSort(byte[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
static voidparallelSort(char[] a)Sorts the specified array into ascending numerical order.
static voidparallelSort(char[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
static voidparallelSort(double[] a)Sorts the specified array into ascending numerical order.
static voidparallelSort(double[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
static voidparallelSort(float[] a)Sorts the specified array into ascending numerical order.
static voidparallelSort(float[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
static voidparallelSort(int[] a)Sorts the specified array into ascending numerical order.
static voidparallelSort(int[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
static voidparallelSort(long[] a)Sorts the specified array into ascending numerical order.
static voidparallelSort(long[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
static voidparallelSort(short[] a)Sorts the specified array into ascending numerical order.
static voidparallelSort(short[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
static <T extends Comparable<? super T>>voidparallelSort(T[] a)Sorts the specified array of objects into ascending order, according to the natural ordering of its elements.
static <T extends Comparable<? super T>>voidparallelSort(T[] a, int fromIndex, int toIndex)Sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements.
static <T> voidparallelSort(T[] a, int fromIndex, int toIndex, Comparator<? super T> cmp)Sorts the specified range of the specified array of objects according to the order induced by the specified comparator.
static <T> voidparallelSort(T[] a, Comparator<? super T> cmp)Sorts the specified array of objects according to the order induced by the specified comparator.
static voidsetAll(double[] array, IntToDoubleFunction generator)Set all elements of the specified array, using the provided generator function to compute each element.
static voidsetAll(int[] array, IntUnaryOperator generator)Set all elements of the specified array, using the provided generator function to compute each element.
static voidsetAll(long[] array, IntToLongFunction generator)Set all elements of the specified array, using the provided generator function to compute each element.
static <T> voidsetAll(T[] array, IntFunction<? extends T> generator)Set all elements of the specified array, using the provided generator function to compute each element.
static voidsort(byte[] a)Sorts the specified array into ascending numerical order.
static voidsort(byte[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
static voidsort(char[] a)Sorts the specified array into ascending numerical order.
static voidsort(char[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
static voidsort(double[] a)Sorts the specified array into ascending numerical orde
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值