揭秘Android泛型源码:解锁编程高效秘诀

泛型是Java编程语言的一个特性,它允许在编写代码时进行类型参数化,从而提高代码的复用性和安全性。在Android开发中,泛型被广泛应用于集合类、泛型方法、泛型类等场景。本文将深入解析Android泛型的源码,帮助开发者更好地理解和使用泛型。
一、泛型原理
泛型的核心思想是类型参数化,它允许我们在编写代码时定义一个与具体类型无关的类或方法。这样,我们可以在不修改代码的情况下,使用不同的类型来创建对象或调用方法。
1.1 类型擦除
Java泛型在运行时是不存在的,这是由于类型擦除(Type Erasure)机制。类型擦除意味着在编译后,泛型信息会被丢弃,只保留具体类型信息。因此,泛型方法或类在运行时无法获取泛型类型信息。
1.2 类型边界
泛型类型可以设置边界,包括上限边界(
? extends T
)和下限边界(
? super T
)。上限边界表示泛型类型只能是T或其子类,下限边界表示泛型类型只能是T或其父类。
二、Android泛型源码解析
2.1 集合类
Android中常用的集合类如ArrayList、LinkedList等,都使用了泛型来提高代码复用性。
2.1.1 ArrayList源码解析
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable {
private static final long serialVersionUID = 8683452581122892189L;

private static final int DEFAULT_CAPACITY = 10;

private E[] elementData;

public ArrayList() {
this.elementData = (E[]) Array.newInstance(Object.class, DEFAULT_CAPACITY);
}

public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = (E[]) Array.newInstance(Object.class, initialCapacity);
} else {
this.elementData = (E[]) Array.newInstance(Object.class, DEFAULT_CAPACITY);
}
}

public ArrayList(Collection c) {
elementData = c.toArray(size());
if (elementData.length == 0) {
this.elementData = (E[]) Array.newInstance(Object.class, DEFAULT_CAPACITY);
}
}

@Override
public E get(int index) {
return elementData(index);
}

@Override
public E set(int index, E element) {
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}

private E elementData(int index) {
if (index >= size()) {
throw new ArrayIndexOutOfBoundsException(index);
}
return (E) elementData[index];
}
}
2.1.2 LinkedList源码解析
public class LinkedList extends AbstractSequentialList implements List, Deque, Cloneable, Serializable {
private static final long serialVersionUID = -2858819069240916161L;

private transient int size = 0;

private transient Node first;

private transient Node last;

private static class Node {
E item;
Node next;
Node prev;

Node(E element, Node prev, Node next) {
item = element;
this.prev = prev;
this.next = next;
}
}

public LinkedList() {
}

public LinkedList(Collection c) {
this();
addAll(c);
}

@Override
public boolean add(E e) {
linkLast(e);
return true;
}

private void linkLast(E e) {
final Node l = last;
final Node newNode = new Node<>(e, l, null);
last = newNode;
if (l == null) {
first = newNode;
} else {
l.next = newNode;
}
size++;
}

@Override
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}

private Node node(int index) {
if (index < (size >> 1)) {
Node x = first;
for (int i = 0; i < index; i++) { x = x.next; } return x; } else { Node x = last;
for (int i = size – 1 & ~-1; i > index; i–) {
x = x.prev;
}
return x;
}
}
}
2.2 泛型方法
Android中常用的泛型方法如
Collections.sort()
、
Arrays.sort()
等。
2.2.1 Collections.sort()源码解析
public static > void sort(List list) {
if (!(list instanceof RandomAccess)) {
list = new ArrayList<>(list);
}
Object[] a = list.toArray();
Arrays.sort(a);
if (list instanceof RandomAccess) {
System.arraycopy(a, 0, list, 0, a.length);
} else {
ListIterator li = list.listIterator();
for (int i = 0; i < a.length; i++) { li.next(); li.set((T) a[i]); } } } 2.3 泛型类 Android中常用的泛型类如 Map 、 Set 等。 2.3.1 HashMap源码解析 ”`java public class HashMap extends AbstractMap implements Map , Cloneable, Serializable { private static final long serialVersionUID = 362498820763181265L; static class Node implements Map.Entry {
final K key;
V value;
Node next;
int hash;

Node(int hash, K key, V value, Node next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}

public final K getKey() {
return key;
}

public final V getValue() {
return value;
}

public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}

public final boolean equals(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry e = (Map.Entry) o;
Object k = key;
Object v = value;
return k == e.getKey() && (v == ((e.getValue()) == null ? null : e.getValue()) || v.equals(e.getValue()));
}

public final int hashCode() {
return hash ^ (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
}
}

transient int size;

transient Set> entrySet;

transient Node[] table;

transient int threshold;

static final int DEFAULT_INITIAL_CAPACITY = 16;

static final float DEFAULT_LOAD_FACTOR = 0.75f;

static final int HashTablecapacity = (int) (DEFAULT_INITIAL_CAPACITY / DEFAULT_LOAD_FACTOR) + 1;

public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
threshold = (int) (DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
table = new Node[DEFAULT_INITIAL_CAPACITY];
}

public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0) { throw new IllegalArgumentException("Initial capacity: " + initialCapacity); } if (initialCapacity > MAXIMUM_CAPACITY) {
initialCapacity = MAXIMUM_CAPACITY;
}
if (loadFactor <= 0 || Float.isNaN(loadFactor)) { throw new IllegalArgumentException("Load factor: " + loadFactor); } this.loadFactor = loadFactor; this.threshold = (int) (loadFactor * initialCapacity); table = new Node[initialCapacity]; } public HashMap(Map m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
threshold = (int) (loadFactor * Math.max(1, m.size()));
table = new Node[threshold];

putAll(m);
}

@Override
public int size() {
return size;
}

@Override
public boolean isEmpty() {
return size == 0;
}

@Override
public V get(Object key) {
Node e = getNode(hash(key), key);
if (e == null) {
return null;
}
return e.value;
}

@Override
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

private V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node[] tab; Node p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0) {
n = (tab = resize()).length;
}
if ((p = tab[i = (n – 1) & hash]) == null) {
tab[i] = newNode(hash, key, value, null);
} else {
Node e; K k;
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) {
e = p;
} else if (p instanceof TreeNode) {
e = ((TreeNode) p).putTreeVal(this, tab, hash, key, value);
} else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD – 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
break;
}
p = e;
}
}
if (e != null) { // existing mapping found
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

private void treeifyBin(Node[] tab, int hash) {
final Node[] ntab = (Node[]) new Node[tab.length << 1]; int index = (hash & (tab.length - 1)); Node e;
for (e = tab[index]; e != null; e = e.next) {
Node p = e;
int ph = e.hash;
K pk = e.key;
V pv = e.value;
if ((p.next = ntab[ph & (ntab.length – 1)]) == null) {
ntab[ph & (ntab.length – 1)] = p;
}
}
tab = ntab;
}

private void resize() {
int oldCapacity = table.length;
int newCapacity = oldCapacity << 1; if (newCapacity - MAXIMUM_CAPACITY < 0) { newCapacity = MAXIMUM_CAPACITY; } Node[] newTable = (Node[]) new Node[newCapacity];
transfer(newTable);
table = newTable;
threshold = (int) (loadFactor * newCapacity);
}

private void transfer(Node[] newTable) {
int newCapacity = newTable.length;
for (Node e : table) {
while (e != null) {
Node next = e.next;
int hash = e.hash;
int i = (hash & (newCapacity – 1));
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}

private static final int TREEIFY_THRESHOLD = 8;

private static final int UNTREEIFY_THRESHOLD = 6;

private static final int MIN_TREEIFY_CAPACITY = 64;

private final void treeifyBin(Node[] tab, int hash) {
for (Node e = tab[i = (hash & (tab.length – 1))]; e != null; e = e.next) {
Node p = e;
int ph = e.hash;
K pk = e.key;
V pv = e.value;
if ((p.next = e.next) == null) {
newTable[ph & (newTable.length – 1)] = e;
continue;
}
if (p instanceof TreeNode) {
TreeNode tn = (TreeNode) e;
p = tn;
ph = tn.hash;
}
for (Node q ; q != null; q = p.next) {
Node nn = q.next;
int nh = q.hash;
if ((q.next = newTable[nh & (newTable.length – 1)]) == null) {
newTable[nh & (newTable.length – 1)] = q;
}
p = nn;
}
newTable[ph & (newTable.length – 1)] = e;
}
}

private final void untreeify(Node[] tab, int index) {
Node e = tab[index];
int h = e.hash;
for (; e != null; e = f) {
Node nn;
if ((e.next = nn = tab[(h & (tab.length – 1))]) == null) {
tab[index] = e;
continue;
}
for (Node q ; q != null; q = nn) {
nn = q.next;
int nh = q.hash;
if ((q.next = tab[nh & (tab.length – 1)]) == null) {
tab[nh & (tab.length – 1)] = q;
}
}
}
}

private final Node newNode(int hash, K key, V value, Node next) {
return new Node<>(hash, key, value, next);
}

private Node getNode(int hash, Object key) {
Node[] tab; Node first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n – 1) & hash]) != null) {
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k)))) {
return first;
}
if (first instanceof TreeNode) {
return ((TreeNode) first).getTreeNode(hash, key);
}
for (e = first.next; e != null; e = e.next) {
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
return e;
}
}
}
return null;
}

public V remove(Object key) {
Node e;
if ((e = getNode(hash(key), key)) != null) {
Node p = e.prev;
Node n = e.next;
if (p == null)
table[tabIndex(e.hash)] = n;
else
p.next = n;
if (n == null)
last = p;
else
n.prev = p;
removeNode(e);
return value;
}
return null;
}

private void removeNode(Node e) {
if (e.next == null) {
e.prev.next = null;
} else {
e.next.prev = e.prev;
}
e.next = null;
e.prev = null;
}

public void putAll(Map m) {
for (Map.Entry e : m.entrySet())
put(e.getKey(), e.getValue());
}

public void clear() {
for (int i = 0; i < table.length; i++) { table[i] = null; } size = 0; } public Set keySet() {
Set ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}

final class KeySet extends AbstractSet {
public Iterator iterator() {
return new HashMap.KeyIterator();
}

public int size() {
return HashMap.this.size();
}

public boolean contains(Object o) {
return containsKey(o);
}

public boolean remove(Object o) {
return HashMap.this.remove(o) != null;
}

public Spliterator spliterator() {
return new HashMap.KeySpliterator();
}

public void clear() {
HashMap.this.clear();
}
}

final class EntrySet extends AbstractSet> {
public Iterator> iterator() {
return new HashMap.EntryIterator();
}

public int size() {
return HashMap.this.size();
}

public boolean contains(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry e = (Map.Entry) o;
Object k = e.getKey();
Object v = e.getValue();
return HashMap.this.containsKey(k) && HashMap.this.get(k).equals(v);
}

public boolean remove(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry e = (Map.Entry) o;
Object k = e.getKey();
Object v = e.getValue();
return HashMap.this.remove(k, v) != null;
}

public Spliterator> spliterator() {
return new HashMap.EntrySpliterator();
}

public void clear() {
HashMap.this.clear();
}
}

final class Values extends AbstractCollection {
public Iterator iterator() {