-- 创造无限可能

java开发问题:获取List<Integer>的元素报错

2023-06-04 09:57:11
510 人浏览 0 人点赞
有用,点赞支持一下

场景

现在需要获取List<Integer>中的某个值

List<String> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);

#报错语句
list.get(10)

报错

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IndexOutOfBoundsException: Index 13 out of bounds for length 1] with root cause

原因分析

尝试使用list.get(10)去获取值
list.get(10)实际获取的是索引为10的值,已经操作了list的长度,所以报错

解决方案

判断List对象是否包含某元素的方法有

  • list.contains(“A”);//不存在返回false
  • list.indexOf(“A”);//不存在则返回-1