ArrayList - 如何检查索引是否存在? [英] ArrayList - how can I check if an index exists?

查看:48
本文介绍了ArrayList - 如何检查索引是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ArrayList 并在特定索引处添加数据,如何检查特定索引是否存在?

I'm using ArrayList<String> and I add data at specific indices, how can I check if a specific index exists?

我应该简单地get() 并检查值吗?还是我应该等待异常?还有别的办法吗?

Should I simply get() and check the value? Or should I wait for an exception? Is there another way?

更新:感谢您的回答,但因为我只在特定索引处添加内容,列表的长度不会显示哪些可用.

Update: Thank you for your answers, but because I'm only adding stuff at specific indices, the length of the list will not show me which are available.

推荐答案

方法 arrayList.size() 返回列表中的项目数 - 所以如果索引大于或等于 size(),它不存在.

The method arrayList.size() returns the number of items in the list - so if the index is greater than or equal to the size(), it doesn't exist.

if(index >= myList.size()){
  //index not exists
}else{
 // index exists
}

这篇关于ArrayList - 如何检查索引是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆