当前位置:首页 > 科技  > 软件

Java|List.subList 踩坑小记

来源: 责编: 时间:2023-09-22 20:11:39 436观看
导读很久以前在使用 Java 的 List.subList 方法时踩过一个坑,当时记了一条待办,要写一写这事,今天完成它。我们先来看一段代码:// 初始化 list 为 { 1, 2, 3, 4, 5 }List<Integer> list = new ArrayList<>();for (int i = 1;

bJV28资讯网——每日最新资讯28at.com

很久以前在使用 Java 的 List.subList 方法时踩过一个坑,当时记了一条待办,要写一写这事,今天完成它。bJV28资讯网——每日最新资讯28at.com

我们先来看一段代码:bJV28资讯网——每日最新资讯28at.com

// 初始化 list 为 { 1, 2, 3, 4, 5 }List<Integer> list = new ArrayList<>();for (int i = 1; i <= 5; i++) {    list.add(i);}// 取前 3 个元素作为 subList,操作 subListList<Integer> subList = list.subList(0, 3);subList.add(6);System.out.println(list.size());

输出是 5 还是 6?bJV28资讯网——每日最新资讯28at.com

没踩过坑的我,会回答是 5,理由是:往一个 List 里加元素,关其它 List 什么事?bJV28资讯网——每日最新资讯28at.com

而掉过坑的我,口中直呼 666。bJV28资讯网——每日最新资讯28at.com

好了不绕弯子,我们直接看下 List.subList 方法的注释文档:bJV28资讯网——每日最新资讯28at.com

/** * Returns a view of the portion of this list between the specified * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.  (If * <tt>fromIndex</tt> and <tt>toIndex</tt> are equal, the returned list is * empty.)  The returned list is backed by this list, so non-structural * changes in the returned list are reflected in this list, and vice-versa. * The returned list supports all of the optional list operations supported * by this list.<p> * * This method eliminates the need for explicit range operations (of * the sort that commonly exist for arrays).  Any operation that expects * a list can be used as a range operation by passing a subList view * instead of a whole list.  For example, the following idiom * removes a range of elements from a list: * <pre>{@code *      list.subList(from, to).clear(); * }</pre> * Similar idioms may be constructed for <tt>indexOf</tt> and * <tt>lastIndexOf</tt>, and all of the algorithms in the * <tt>Collections</tt> class can be applied to a subList.<p> * * The semantics of the list returned by this method become undefined if * the backing list (i.e., this list) is <i>structurally modified</i> in * any way other than via the returned list.  (Structural modifications are * those that change the size of this list, or otherwise perturb it in such * a fashion that iterations in progress may yield incorrect results.) * * @param fromIndex low endpoint (inclusive) of the subList * @param toIndex high endpoint (exclusive) of the subList * @return a view of the specified range within this list * @throws IndexOutOfBoundsException for an illegal endpoint index value *         (<tt>fromIndex < 0 || toIndex > size || *         fromIndex > toIndex</tt>) */List<E> subList(int fromIndex, int toIndex);

这里面有几个要点:bJV28资讯网——每日最新资讯28at.com

subList 返回的是原 List 的一个 视图,而不是一个新的 List,所以对 subList 的操作会反映到原 List 上,反之亦然;bJV28资讯网——每日最新资讯28at.com

如果原 List 在 subList 操作期间发生了结构修改,那么 subList 的行为就是未定义的(实际表现为抛异常)。bJV28资讯网——每日最新资讯28at.com

第一点好理解,看到「视图」这个词相信大家就都能理解了。我们甚至可以结合 ArrayList 里的 SubList 子类源码进一步看下:bJV28资讯网——每日最新资讯28at.com

private class SubList extends AbstractList<E> implements RandomAccess {    private final AbstractList<E> parent;    // ...    SubList(AbstractList<E> parent,            int offset, int fromIndex, int toIndex) {        this.parent = parent;        // ...        this.modCount = ArrayList.this.modCount;    }    public E set(int index, E e) {        // ...        checkForComodification();        // ...        ArrayList.this.elementData[offset + index] = e;        // ...    }    public E get(int index) {        // ...        checkForComodification();        return ArrayList.this.elementData(offset + index);    }    public void add(int index, E e) {        // ...        checkForComodification();        parent.add(parentOffset + index, e);        this.modCount = parent.modCount;        // ...    }    public E remove(int index) {        // ...        checkForComodification();        E result = parent.remove(parentOffset + index);        this.modCount = parent.modCount;        // ...    }    private void checkForComodification() {        if (ArrayList.this.modCount != this.modCount)            throw new ConcurrentModificationException();    }    // ...}

可以看到几乎所有的读写操作都是映射到 ArrayList.this、或者 parent(即原 List)上的,包括 size、add、remove、set、get、removeRange、addAll 等等。bJV28资讯网——每日最新资讯28at.com

第二点,我们在文首的示例代码里加上两句代码看现象:bJV28资讯网——每日最新资讯28at.com

list.add(0, 0);System.out.println(subList);

System.out.println 会抛出异常 java.util.ConcurrentModificationException。bJV28资讯网——每日最新资讯28at.com

我们还可以试下,在声明 subList 后,如果对原 List 进行元素增删操作,然后再读写 subList,基本都会抛出此异常。bJV28资讯网——每日最新资讯28at.com

因为 subList 里的所有读写操作里都调用了 checkForComodification(),这个方法里检验了 subList 和 List 的 modCount 字段值是否相等,如果不相等则抛出异常。bJV28资讯网——每日最新资讯28at.com

modCount 字段定义在 AbstractList 中,记录所属 List 发生 结构修改 的次数。结构修改 包括修改 List 大小(如 add、remove 等)、或者会使正在进行的迭代器操作出错的修改(如 sort、replaceAll 等)。bJV28资讯网——每日最新资讯28at.com

好了小结一下,这其实不算是坑,只是 不应该仅凭印象和猜测,就开始使用一个方法,至少花一分钟认真读完它的官方注释文档。bJV28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-11204-0.htmlJava|List.subList 踩坑小记

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 基于Python+Flask实现一个简易网页验证码登录系统案例

下一篇: 网络安全:渗透测试工程师必备的十种技能

标签:
  • 热门焦点
  • 石头智能洗地机A10 Plus体验:双向自清洁治好了我的懒癌

    一、前言和介绍专为家庭请假懒人而生的石头科技在近日又带来了自己的全新旗舰新品,石头智能洗地机A10 Plus。从这个产品名上就不难看出,这次石头推出的并不是常见的扫地机器
  • 0糖0卡0脂 旭日森林仙草乌龙茶优惠:15瓶到手29元

    旭日森林无糖仙草乌龙茶510ml*15瓶平时要卖为79.9元,今日下单领取50元优惠券,到手价为29.9元。产品规格:0糖0卡0脂,添加草本仙草汁,清凉爽口,富含茶多酚,保留
  • 十个可以手动编写的 JavaScript 数组 API

    JavaScript 中有很多API,使用得当,会很方便,省力不少。 你知道它的原理吗? 今天这篇文章,我们将对它们进行一次小总结。现在开始吧。1.forEach()forEach()用于遍历数组接收一参
  • 一篇聊聊Go错误封装机制

    %w 是用于错误包装(Error Wrapping)的格式化动词。它是用于 fmt.Errorf 和 fmt.Sprintf 函数中的一个特殊格式化动词,用于将一个错误(或其他可打印的值)包装在一个新的错误中。使
  • WebRTC.Net库开发进阶,教你实现屏幕共享和多路复用!

    WebRTC.Net库:让你的应用更亲民友好,实现视频通话无痛接入! 除了基本用法外,还有一些进阶用法可以更好地利用该库。自定义 STUN/TURN 服务器配置WebRTC.Net 默认使用 Google 的
  • 自律,给不了Keep自由!

    来源 | 互联网品牌官作者 | 李大为编排 | 又耳 审核 | 谷晓辉自律能不能给用户自由暂时不好说,但大概率不能给Keep自由。近日,全球最大的在线健身平台Keep正式登陆港交所,努力
  • 回归OPPO两年,一加赢了销量,输了品牌

    成为OPPO旗下主打性能的先锋品牌后,一加屡创佳绩。今年618期间,一加手机全渠道销量同比增长362%,凭借一加 11、一加 Ace 2、一加 Ace 2V三款爆品,一加
  • 利用职权私自解除被封帐号 Meta开除20多名员工

    11月18日消息,据外媒援引知情人士表示,过去一年时间内,Facebook母公司Meta解雇或处罚了20多名员工以及合同工,指控这些人通过内部系统以不当方式重置用户帐号,其
  • Meta盲目扩张致超万人被裁,重金押注元宇宙而前景未明

    图片来源:图虫创意日前,Meta创始人兼CEO 马克&middot;扎克伯发布公开信,宣布Meta计划裁员超11000人,占其员工总数13%。他公开承认了自己的预判失误:&ldquo;不仅
Top