这个问题是出现开发一个电商平台的订单系统时,遇到了类似的问题。需要将一个订单 ID 数组转换为一个List, 并在后续的业务逻辑中向这个List中添加新的订单 ID。由于个人经验不足,使用了Arrays.asList()方法,部署到线上导致在添加新订单 ID 时抛出了UnsupportedOperationException异常, 整个订单处理流程中断,线上系统出现了严重的故障。
ArrayList(E[] array) { a = Objects.requireNonNull(array); }
@Override publicintsize(){ return a.length; }
@Override public Object[] toArray() { return a.clone(); }
@Override @SuppressWarnings("unchecked") public T[] toArray(T[] a) { int size = size(); if (a.length return Arrays.copyOf(this.a, size, (Class extends T[]>) a.getClass()); System.arraycopy(this.a, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
@Override public E get(int index){ return a[index]; }
@Override public E set(int index, E element){ E oldValue = a[index]; a[index] = element; return oldValue; }
@Override publicintindexOf(Object o){ E[] a = this.a; if (o == null) { for (int i = 0; i if (a[i] == null) return i; } else { for (int i = 0; i if (o.equals(a[i])) return i; } return -1; }
@Override public Spliteratorspliterator(){ return Spliterators.spliterator(a, Spliterator.ORDERED); }
@Override publicvoidforEach(Consumer super E> action){ Objects.requireNonNull(action); for (E e : a) { action.accept(e); } }
@Override publicvoidreplaceAll(UnaryOperator operator){ Objects.requireNonNull(operator); E[] a = this.a; for (int i = 0; i a[i] = operator.apply(a[i]); } }
@Override publicvoidsort(Comparator super E> c){ Arrays.sort(a, c); } }