我们在分析Lifecycle源码之前先看下FastSafeIterableMap的源码,因为Lifecycle组件的关键类LifecycleRegistry使用到,而且是关键的属性。
首先,他继承自SafeIterableMap
,而SafeIterableMap
继承自Iterable<Map.Entry<K, V>>
。我们就先分析SafeIterableMap
的源码
SafeIterableMap
他是一个不同于HashMap的键值对,他是由Key组成的链表,每个Key里面存储了Value,具有头部和尾部,我们先看他的声明
1 | public class SafeIterableMap<K, V> implements Iterable<Map.Entry<K, V>> { |
然后是他的属性
1 | private Entry<K, V> mStart //头部指针 |
其中Entry是继承自Map.Entry的,他的声明是
1 | static class Entry<K, V> implements Map.Entry<K, V> { |
然后我们分析他的put
方法
1 | protected Entry<K, V> put(@NonNull K key, @NonNull V v) { |
然后是他的get
方法
1 | protected Entry<K, V> get(K k) { |
然后是迭代器,SafeIterableMap具有两个迭代器,分别通过iterator()
(forEatch循环使用的)得到的AscendingIterator
以及descendingIterator
得到的DescendingIterator
。分别是正序和反序遍历,他们都继承自内部类ListIterator
Iterator
我们先说下ListIterator
,直接看源码
1 | private abstract static class ListIterator<K, V> implements Iterator<Map.Entry<K, V>>, |
其中AscendingIterator和DescendingIterator的实现是类似的,源码如下
1 | static class AscendingIterator<K, V> extends ListIterator<K, V> { |
然后是移除remove
方法
1 | public V remove(@NonNull K key) { |
它还提供了一个iteratorWithAdditions()
获取自定义非基础自ListIterator的额外迭代器,具体实现和解析如下
1 | private class IteratorWithAdditions implements Iterator<Map.Entry<K, V>>, SupportRemove<K, V> { |
我们在一开始的时候有提到SafeIterableMap有一个mIterators
,他是用于存储生成的所有的Iterator,每次获取任意一种迭代器新生成一个迭代器对象的时候就往mIterators
里面放。他会在SafeIterableMap元素被移除的时候调用,去矫正存储的迭代器的当前位置。这就是SafeIterableMap的源码了
FastSafeIterableMap
他是继承了SafeIterableMap,但是他重写了他的get
,putIfAbsent
,remove
方法。而且它使用的是HashMap去存储元素,类型是HashMap<K, Entry<K, V>>
。他存储的与SafeIterableMap不一样,他是通过父类存储<K,V>
,而自己存储的是<K,<K,V>>
,是包裹了一层的。而且LifecycleRegistry也没有直接调用FastSafeIterableMap的put
方法,而是调用的putIfAbsent
,我们具体他的源码。
首先是putIfAbsent
方法
1 | @Override |
然后是get
方法以及自己增加的ceil
方法
1 | @Override |
最后是他的remove
方法
1 | @Override |
这就是FastSafeIterableMap的源码,比较的简单,他其实是相当于把SafeIterableMap再封装了一层,SafeIterableMap存储的是<K,V>
,那么他则是存储的<K,<K,V>
。