这是一种在Java中创建只读List的方法吗?

znl*_*lyj 1 java list

用java思考说:

要从AbstractList创建只读List,必须实现get()和size().

它让我困惑,代码如下:

 public class CountingIntegerList
extends AbstractList<Integer> {
  private int size;
  public CountingIntegerList(int size) {
    this.size = size < 0 ? 0 : size;
  }
  public Integer get(int index) {
    return Integer.valueOf(index);
  }
  public int size() { return size; }
  public static void main(String[] args) {
    List list = new CountingIntegerList(30);
  }
}
Run Code Online (Sandbox Code Playgroud)

列表是只读列表吗?为什么?

好吧,答案是肯定的,因为我延伸AbstractList并抛出UnsupportedOperationExceptionif set或者and被调用.如果我想获得一个不可修改的List,Collections.unmodifiableList()是一个不错的选择.但请记住,它们都不是一成不变的:

      List<StringBuilder> list = new ArrayList<StringBuilder>();
      StringBuilder sb = new StringBuilder();
      sb.append("hello");
      list.add(sb);
      System.out.println(list);
      list = Collections.unmodifiableList(list);
      sb.append("world");
      System.out.println(list);
Run Code Online (Sandbox Code Playgroud)

有一个flyweight patternCountingIntegerList.因为每次都get()被调用,它从Integer获取缓存,源代码为valueOf():

   public static Integer valueOf(int i) {
    final int offset = 128;
    if (i >= -128 && i <= 127) { // must cache 
        return IntegerCache.cache[i + offset];
    }
        return new Integer(i);
    }
Run Code Online (Sandbox Code Playgroud)

是对的吗?

Joh*_*and 5

它的只读(甚至是不可变的),因为add会抛出一个UnsupportedOperationException为意志remove.

AbstractList处理为您创建迭代器,计算哈希码和相等的所有工作.这非常有帮助.包装完全没必要unmodifiableList.

稍后你会问是否AbstractList主要用于创建不可修改的列表.实际上它用于创建任何类型的随机访问列表.在我的数据结构课程中,我们使用诸如此类的抽象类来保存实现列表类的大部分工作.甚至Collection接口也有13个方法,除了其中两个方法都是实现的AbstractCollection.

有一个相关的类AbstractSequentialList可以帮助创建非随机访问的列表(例如链表).