Java集合中不常用方法记录
List 篇
ArrayList篇
java.util.ArrayList#trimToSize()方法
此方法用于去除底层数组中未被使用的数组位置。比如:ArrayList的初始容量为10,当只向其中放入一个元素时候,则其他9个位置的值皆为null,此时集合中元素个数为1,数组长度为10, 调用次方法后,则会去掉为预留元素的位置,即元素位置为null的位置,即此时集合中元素个数为1, 数组长度也为1。
java.util.ArrayList#ensureCapacity(int minCapacity)
此方法用于减少集合内部分配次数,一般在使用add插入大量元素之前使用,比如,add方法新增10万条数据,在新增期间由于底层数组的不断扩容,copy创建新增数组,较为耗时,使用ensureCapacity方法后极大的减少了分配次数,节约了代码执行时间。
个人理解:使用ArrayList(int initialCapacity)构造函数也可以有效减少分配次数,ensureCapacity方法只是在某些特定情况下,集合初始容量固定,后需要大量扩展的情况下所提供。
java.util.ArrayList#retainAll(Collection<?> c)方法
此方法的意思是,只保留指定集合中的元素,其他不包含在内的元素删除。
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
List<Integer> list2 = new ArrayList<>();
list2.add(1);
list2.add(6);
list.retainAll(list2);
System.out.println(list); // 结果: [1]
LinkedList篇
java.util.LinkedList#peek()与 java.util.LinkedList#element()
这两个方法都是获取集合中第一个元素,并且不改变集合中的元素,不同的是,当集合是一个空集合的时候, peek()方法返回null,而element()方法则会抛出NoSuchElementException.class类型的异常。
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
public E element() {
return getFirst();
}
java.util.LinkedList#poll()与java.util.LinkedList#remove()
这两个方法都是删除集合中的第一个元素,并返回该元素,不同的是当集合为空的时候,poll取不到元素的时候,进行删除则返回null, remove方法则会抛出NoSuchElementException.class异常。
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public E remove() {
return removeFirst();
}