有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

    如果你想要一个连接两个列表的不可变列表视图,试试这个

    public class ConcatenatedList<E> extends AbstractList<E> {
    
        private final List<E> a, b;
    
        public ConcatenatedList(List<E> a, List<E> b) {
            this.a = a;
            this.b = b;
        }
    
        @Override
        public E get(int index) {
            return index < a.size() ? a.get(index) : b.get(index - a.size());
        }
    
        @Override
        public int size() {
            return a.size() + b.size();
        }
    }
    
    public static void main(String[] args) {
        List<Integer> listA = new LinkedList<>(Arrays.asList(0, 1, 2));
        List<Integer> listB = new LinkedList<>(Arrays.asList(3, 4, 5));
        List<Integer> joined = new ConcatenatedList<>(listA, listB);
        System.out.println(joined);
    }
    

    输出:

    [0, 1, 2, 3, 4, 5]
    

    这个串联是O(1)