美文网首页
Guava(5) collect.Immutable

Guava(5) collect.Immutable

作者: 懵逼猴 | 来源:发表于2019-11-22 16:16 被阅读0次

前面

  1. 不可变代表着线程安全,线程调用时完全不用考虑线程安全的问题(不过个人认为意义不大,因为这个不可变是在封锁修改方法的前提下保证的,非不可变类不对其进行修改也完全可以实现同样的效果)

  2. Guava不可变集合不是源数据结构的视图,而是它的副本,使得对原始结构的更改不会影响复制的不可变集合。这一点与JDK提供的Collections.unmodifiableCollection()不一样,JDK提供的类只是将源数据进行了一个的包装,读操作还是调用的源数据结构的读操作,对写操作则直接报错了。

  3. 转成不可变类再输出是一个防御式编程的手段.

其他杂想

其中有一个方法实现的非常巧妙,subListUnchecked()方法,实现并没有构造新的Object[]数组,而是在利用原有的数组,但偏移量有所改变。所有的写操作都已经被屏蔽,所以Object[]数组成为了不可变,截取操作只是变成了对原有Object[]上下界的操作。节省了很多空间

@Override
  public ImmutableList<E> subList(int fromIndex, int toIndex) {
    checkPositionIndexes(fromIndex, toIndex, size());
    int length = toIndex - fromIndex;
    if (length == size()) {
      return this;
    } else if (length == 0) {
      return of();
    } else if (length == 1) {
      return of(get(fromIndex));
    } else {
      return subListUnchecked(fromIndex, toIndex);
    }
  }
ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) {
    return new SubList(fromIndex, toIndex - fromIndex);
  }

  class SubList extends ImmutableList<E> {
    final transient int offset;
    final transient int length;

    SubList(int offset, int length) {
      this.offset = offset;
      this.length = length;
    }

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

    @Override
    public E get(int index) {
      checkElementIndex(index, length);
      return ImmutableList.this.get(index + offset);
    }

    @Override
    public ImmutableList<E> subList(int fromIndex, int toIndex) {
      checkPositionIndexes(fromIndex, toIndex, length);
      return ImmutableList.this.subList(fromIndex + offset, toIndex + offset);
    }

    @Override
    boolean isPartialView() {
      return true;
    }
  }

参考文章

Guava源码阅读计划:collect.Immutable

相关文章

网友评论

      本文标题:Guava(5) collect.Immutable

      本文链接:https://www.haomeiwen.com/subject/kiprvctx.html