jdk源码_Collection

Collection

集合结构中的根接口

1
2
3
public interface Collection<E> extends Iterable<E> {

}

forEach

继承Iterable接口,故可调用默认方法forEach

AbstractCollection

提供了 Collection 接口的基本实现

1
2
3
public abstract class AbstractCollection<E> implements Collection<E> {

}

iterator()

1
2
3
4
5
6
/**
* Returns an iterator over the elements contained in this collection.
*
* @return an iterator over the elements contained in this collection
*/
public abstract Iterator<E> iterator();

AbstractList.iterator

public abstract class AbstractList extends AbstractCollection implements List

1
2
3
public Iterator<E> iterator() {
return new Itr();
}

Itr

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
private class Itr implements Iterator<E> {
/**
* Index of element to be returned by subsequent call to next.
*/
int cursor = 0;

/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;

/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
int expectedModCount = modCount;

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

public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}

size()

1
public abstract int size();

public abstract class AbstractList extends AbstractCollection implements List
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable

ArrayList.size()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;

/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size;
}

boolean isEmpty()

1
2
3
public boolean isEmpty() {
return size() == 0;
}

boolean contains(Object o)

1
2
3
4
5
6
7
8
9
10
11
12
13
public boolean contains(Object o) {
Iterator<E> it = iterator();
if (o == null) {
while (it.hasNext())
if (it.next() == null)
return true;
} else {
while (it.hasNext())
if (o.equals(it.next()))
return true;
}
return false;
}

集合可以存入空对象

1
2
3
4
5
6
public static void main(String[] args) {
Collection collection = new ArrayList();
collection.add(null);
System.out.println(collection.size()==0);//false
System.out.println(collection.contains(null));//true
}

toArray()

Object[] toArray()

1
2
3
4
5
6
7
8
9
10
11
public Object[] toArray() {
// Estimate size of array; be prepared to see more or fewer elements
Object[] r = new Object[size()];
Iterator<E> it = iterator();
for (int i = 0; i < r.length; i++) {
if (!it.hasNext()) // fewer elements than expected
return Arrays.copyOf(r, i);
r[i] = it.next();
}
return it.hasNext() ? finishToArray(r, it) : r;
}

先根据Size()方法预建立一个与集合长度相等的数组,然后进行判断,若迭代过程中发现对象没有预期的多,则直接截取当前的数组返回

T[] toArray(T[] a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public <T> T[] toArray(T[] a) {
// Estimate size of array; be prepared to see more or fewer elements
int size = size();
T[] r = a.length >= size ? a :
(T[]) java.lang.reflect.Array
.newInstance(a.getClass().getComponentType(), size);
Iterator<E> it = iterator();

for (int i = 0; i < r.length; i++) {
if (!it.hasNext()) { // fewer elements than expected
if (a == r) {
r[i] = null; // null-terminate
} else if (a.length < i) {
return Arrays.copyOf(r, i);
} else {
System.arraycopy(r, 0, a, 0, i);
if (a.length > i) {
a[i] = null;
}
}
return a;
}
r[i] = (T) it.next();
}
// more elements than expected
return it.hasNext() ? finishToArray(r, it) : r;
}

若参数数组a的长度大于集合的长度,则直接用a数组赋值,若小于则利用反射建立一个长度等于集合长度的数组

boolean remove(Object o)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public boolean remove(Object o) {
Iterator<E> it = iterator();
if (o == null) {
while (it.hasNext()) {
if (it.next() == null) {
it.remove();
return true;
}
}
} else {
while (it.hasNext()) {
if (o.equals(it.next())) {
it.remove();
return true;
}
}
}
return false;
}

Object.equals

1
2
3
public boolean equals(Object obj) {
return (this == obj);
}

boolean containsAll(Collection<?> c)

1
2
3
4
5
6
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}

boolean addAll(Collection<? extends E> c)

1
2
3
4
5
6
7
public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}

boolean removeAll(Collection<?> c)

1
2
3
4
5
6
7
8
9
10
11
12
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}

Objects.requireNonNull(c)

1
2
3
4
5
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}

default boolean removeIf(Predicate<? super E> filter)

1
2
3
4
5
6
7
8
9
10
11
12
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}

传入一个断言型功能函数,判断,若符合断言要求,remove

1
2
Collection<String> collection = new ArrayList<String>(Arrays.asList("first","second","third","--------"));
collection.removeIf(s->s.equals("first"));

boolean retainAll(Collection<?> c)

1
2
3
4
5
6
7
8
9
10
11
12
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<E> it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}

取交集 遍历集合,若元素存在于参数集合C,则移除,并将modified置为true返回

boolean equals(Object o)

AbstractList

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;

ListIterator<E> e1 = listIterator();
ListIterator<?> e2 = ((List<?>) o).listIterator();
while (e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1 == null ? o2 == null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}

先比较参数是否和当前List指向同一对象,再比较参数是否为List实例,然后将两个List中的元素一一对比(若List对象元素不为null,则用Object.equals方法对比,若为null则判断参数List对象中元素是否为null),最后判断长度是否相等

hasNext()

ArrayList

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

next()

ArrayList

1
2
3
4
5
6
7
8
9
10
11
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];
}

instanceof

instanceof是Java中的二元运算符,左边是对象,右边是类;当对象是右边类或子类所创建对象时,返回true;否则,返回false。

  • 类的实例包含本身的实例,以及所有直接或间接子类的实例
  • instanceof左边显式声明的类型与右边操作元必须是同种类或存在继承关系,也就是说需要位于同一个继承树,否则会编译错误
  • 左边的对象实例不能是基础数据类型
  • null用instanceof跟任何类型比较时都是false

int hashCode()

重写Object.equals方法时必须同样重写Object.hashCode方法

  • 如果两个对象equals相等,那么这两个对象的HashCode一定也相同
  • 如果两个对象的HashCode相同,不代表两个对象就相同,只能说明这两个对象在散列存储结构中,存放于同一个位置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Returns the hash code value for this collection. While the
* <tt>Collection</tt> interface adds no stipulations to the general
* contract for the <tt>Object.hashCode</tt> method, programmers should
* take note that any class that overrides the <tt>Object.equals</tt>
* method must also override the <tt>Object.hashCode</tt> method in order
* to satisfy the general contract for the <tt>Object.hashCode</tt> method.
* In particular, <tt>c1.equals(c2)</tt> implies that
* <tt>c1.hashCode()==c2.hashCode()</tt>.
*
* @return the hash code value for this collection
* @see Object#hashCode()
* @see Object#equals(Object)
*/
int hashCode();

default Stream stream()

返回一个不影响数据源的数据序列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Returns a sequential {@code Stream} with this collection as its source.
*
* <p>This method should be overridden when the {@link #spliterator()}
* method cannot return a spliterator that is {@code IMMUTABLE},
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
* for details.)
*
* @return a sequential {@code Stream} over the elements in this collection
* @implSpec The default implementation creates a sequential {@code Stream} from the
* collection's {@code Spliterator}.
* @since 1.8
*/
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020 李明华
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信