场景
现在需要获取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