从列表中删除项目后,Java ArrayList引发IndexOutOfBoundsException

编程入门 行业动态 更新时间:2024-10-19 14:37:39
本文介绍了从列表中删除项目后,Java ArrayList引发IndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我们创建一个ArrayList并检查其大小时,其值将为0.但是,当我们添加一个元素并删除该元素,然后检查其大小时,它将引发异常.

When we create an ArrayList and check its size, it gives the value as 0. However, when we add an element and remove that element, and then check its size, it throws exception.

remove()方法的内部实现是什么,它可以更改空列表的定义?

What is the internal implementation in remove() method, that it changes the definition of an empty list?

下面的代码将输出设置为0.

Code below gives output as 0.

List<Integer> list2 = new ArrayList<Integer>(); System.out.println(list2.size());

下面的代码引发异常:

List<Integer> list1 = new ArrayList<Integer>(); list1.add(1); System.out.println(list1.size()); list1.remove(1); System.out.println(list1.size());

推荐答案

list1.remove(1)

list1.remove(1)

您正在尝试从索引1中删除一个元素,而不是值1.因此,数组索引超出范围错误.

You are trying to remove an element from index 1, not the value 1. hence the array index out of bounds error.

更多推荐

从列表中删除项目后,Java ArrayList引发IndexOutOfBoundsException

本文发布于:2023-11-22 20:35:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618924.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   列表中   Java   ArrayList   IndexOutOfBoundsException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!