我正在使用ArrayList<String>并在特定索引处添加数据,如何检查特定索引是否存在?
我应该简单地get()检查价值吗?或者我应该等待例外?还有另外一种方法吗?
谢谢你的答案,但因为我只是在特定索引处添加内容,列表的长度不会显示哪些是可用的.
Ama*_*osh 141
该方法arrayList.size() 返回列表中的项数 - 因此,如果索引大于或等于size(),则它不存在.
if(index >= myList.size()){
//index not exists
}else{
// index exists
}
Run Code Online (Sandbox Code Playgroud)
小智 66
虽然你有十几条关于使用列表大小的建议,这些建议适用于带有线性条目的列表,但似乎没有人能够阅读你的问题.
如果您在不同的索引处手动添加条目,则这些建议都不起作用,因为您需要检查特定索引.
使用if(list.get(index)== null)也不起作用,因为get()抛出异常而不是返回null.
试试这个:
try {
list.get( index );
} catch ( IndexOutOfBoundsException e ) {
list.add( index, new Object() );
}
Run Code Online (Sandbox Code Playgroud)
如果索引不存在,则添加新条目.你可以改变它来做一些不同的事情.
Mah*_*zad 14
这是给Kotlin开发者的:
if (index in myList.indices) {
// index is valid
}
Run Code Online (Sandbox Code Playgroud)
其他解决方案:
// The rangeUntil operator (..<) is still exprimental in Kotlin 1.7.20
if (index in 0..<myList.size) {
// index is valid
}
Run Code Online (Sandbox Code Playgroud)
if (index in 0 until myList.size) {
// index is valid
}
Run Code Online (Sandbox Code Playgroud)
if (index in 0..myList.lastIndex) {
// index is valid
}
Run Code Online (Sandbox Code Playgroud)
if (index >= 0 && index <= myList.lastIndex) {
// index is valid
}
Run Code Online (Sandbox Code Playgroud)
// Note: elements of the list should be non-null
if (myList.getOrNull(index) != null) {
// index is valid
}
Run Code Online (Sandbox Code Playgroud)
// Note: elements of the list should be non-null
myList.getOrNull(index)?.let { element ->
// index is valid; use the element
}
Run Code Online (Sandbox Code Playgroud)
Pau*_*zie 12
这就是你需要的......
public boolean indexExists(final List list, final int index) {
return index >= 0 && index < list.size();
}
Run Code Online (Sandbox Code Playgroud)
为什么不使用普通的旧阵列?对List的索引访问是我认为的代码味道.
关于你的更新(可能应该是另一个问题).您应该使用这些对象的数组而不是ArrayList,因此您只需检查null的值:
Object[] array = new Object[MAX_ENTRIES];
..
if ( array[ 8 ] == null ) {
// not available
}
else {
// do something
}
Run Code Online (Sandbox Code Playgroud)
最佳实践
如果你的阵列中没有数百个条目,你应该考虑将它组织成一个类来摆脱神奇的数字3,8等.
使用异常控制流是不好的做法.
由于java-9有一种标准的方法来检查索引是否属于数组 - Objects#checkIndex():
List<Integer> ints = List.of(1,2,3);
System.out.println(Objects.checkIndex(1,ints.size())); // 1
System.out.println(Objects.checkIndex(10,ints.size())); //IndexOutOfBoundsException
Run Code Online (Sandbox Code Playgroud)
通常我只是检查索引是否小于数组大小
if (index < list.size()) {
...
}
Run Code Online (Sandbox Code Playgroud)
如果您还担心索引是负值,请使用以下内容
if (index >= 0 && index < list.size()) {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
199852 次 |
| 最近记录: |