Java源码学习(JDK11)——java.lang.Collection :接⼝
:抽象类
:抽象类
:实现 Set 接⼝
:实现 Set 接⼝
:实现 NavigableSet 接⼝
:抽象类
:实现 List 接⼝
:实现 List 接⼝
:抽象类
:实现 List 和 Deque 接⼝
Set:接⼝
SortedSet:接⼝
NavigableSet:接⼝
List:接⼝
Queue:接⼝
Deque:接⼝
Collection
public interface Collection<E> extends Iterable<E> {
// Query Operations
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(0));
}
// Modification Operations
boolean add(E e);
boolean remove(Object o);
// Bulk Operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
default boolean removeIf(Predicate<? super E> filter) {
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (())) {
removed = true;
}
}
return removed;
}
boolean retainAll(Collection<?> c);
void clear();
// Comparison and hashing
boolean equals(Object o);
int hashCode();
@Override
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, 0);
}
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
default Stream<E> parallelStream() {
return StreamSupport.stream(spliterator(), true);
}
}
Collection 实现 Iterable 接⼝,具有 iterator() ⽅法,可以迭代。AbstractCollection
public abstract class AbstractCollection<E> implements Collection<E> {
protected AbstractCollection() {
}
// Query Operations
public abstract Iterator<E> iterator();学习java的学习方法
public abstract int size();
public boolean isEmpty() {
return size() == 0;
}
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.()))
return true;
}
return false;
}
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
pyOf(r, i);
r[i] = it.next();
}
return it.hasNext() ? finishToArray(r, it) : r;
}
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) { /*...*/ }
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
// 重新分配数组空间供 toArray ⽅法使⽤
@SuppressWarnings("unchecked")
private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
int i = r.length;
while (it.hasNext()) {
int cap = r.length;
if (i == cap) {
int newCap = cap + (cap >> 1) + 1; // 扩容⼤⼩ 1.5 倍 + 1
// overflow-conscious code
if (newCap - MAX_ARRAY_SIZE > 0)
newCap = hugeCapacity(cap + 1);
r = pyOf(r, newCap);
}
r[i++] = (();
}
// trim if overallocated
return (i == r.length) ? r : pyOf(r, i);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError("Required array size too large");
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
// Modification Operations
public boolean add(E e) { // ⽀持 add 的 Collection 覆盖该⽅法不⽀持的直接抛出异常
throw new UnsupportedOperationException();
}
public boolean remove(Object o) {
Iterator<E> it = iterator();
if (o==null) {
while (it.hasNext()) {
if (it.next()==null) {
return true;
}
}
} else {
while (it.hasNext()) {
if (o.())) {
return true;
}
}
}
return false;
}
// Bulk Operations
public boolean containsAll(Collection<?> c) { /*...*/ }
public boolean addAll(Collection<? extends E> c) { /*...*/ }
public boolean removeAll(Collection<?> c) { /*...*/ }
public boolean retainAll(Collection<?> c) { /*...*/ }
public void clear() {
Iterator<E> it = iterator();
while (it.hasNext()) {
<();
}
}
// String conversion
public String toString() { /*...*/ }
}
AbstractCollection 提供了⼏乎所有⽅法的实现,各种操作基于 iterator() 抽象⽅法,因此⼦类只需要实现 iterator() 和 size() ⽅法,可修改的 Collection 需要提供 add 的实现。
AbstractSet
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
protected AbstractSet() {
}
// Comparison and hashing
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Set))
return false;
Collection<?> c = (Collection<?>) o;
if (c.size() != size())
return false;
try {
return containsAll(c);
} catch (ClassCastException | NullPointerException unused) {
return false;
}
}
public int hashCode() { /*...*/ }
public boolean removeAll(Collection<?> c) {
boolean modified = false;
if (size() > c.size()) {
for (Object e : c)
modified |= remove(e);
} else {
for (Iterator<?> i = iterator(); i.hasNext(); ) {
if (c.())) {
modified = true;
}
}
}
return modified;
}
}
AbstractSet 覆盖了 hashCode 和 equals ⽅法,equals 利⽤ containsAll 来实现。
AbstractSet 覆盖了 removeAll ⽅法,对于容量较⼤的情况不需要使⽤迭代器。HashSet
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
static final long serialVersionUID = -5024744406713321676L;
// HashSet 内部利⽤ HashMap 的 keySet() 来实现
private transient HashMap<E,Object> map;
/
/ Dummy value to associate with an Object in the backing Map
// 作为 Map 键值对⾥的 value
private static final Object PRESENT = new Object();
// default initial capacity (16) and load factor (0.75).
public HashSet() {
map = new HashMap<>();
}
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
// 提供给 LinkedHashSet 使⽤
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
public Iterator<E> iterator() {
return map.keySet().iterator();
}
public int size() {
return map.size();
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean contains(Object o) {
ainsKey(o);
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
public boolean remove(Object o) {
ve(o)==PRESENT;
}
public void clear() {
map.clear();
}
@SuppressWarnings("unchecked")
public Object clone() { /*...*/ }
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { /*...*/ }
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { /*...*/ } public Spliterator<E> spliterator() {
return new HashMap.KeySpliterator<>(map, 0, -1, 0, 0);
}
}
HashSet 内部基于 HashMap 来实现,并覆盖了 add,remove 等⽅法以提⾼效率。LinkedHashSet
public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, java.io.Serializable {
// 构造函数借助于 HashSet 中的 HashSet(int initialCapacity, float loadFactor, boolean dummy) ⽅法
// 该⽅法实际创建了⼀个 LinkedHashMap
public LinkedHashSet(Collection<? extends E> c) {
super(Math.max(2*c.size(), 11), .75f, true);
addAll(c);
}
@Override
public Spliterator<E> spliterator() {
return Spliterators.spliterator(this, Spliterator.DISTINCT | Spliterator.ORDERED);
}
}
LinkedHashSet ⼏乎与 HashSet 完全⼀致,只是内部借助的是 LinkedHashMap。
LinkedHashSet 维护了插⼊顺序。
TreeSet
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, java.io.Serializable
{
private transient NavigableMap<E,Object> m;
private static final Object PRESENT = new Object();
TreeSet(NavigableMap<E,Object> m) {
this.m = m;
}
// 内部基于 TreeMap
public TreeSet() {
this(new TreeMap<>());
}
// 构造器
public Iterator<E> iterator() {
return m.navigableKeySet().iterator();
}
public Iterator<E> descendingIterator() {
return m.descendingKeySet().iterator();
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论