java:ArrayList - 如何检查索引是否存在?

ufk*_*ufk 97 java arraylist

我正在使用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)

  • 那应该是"大于或等于`size()`",因为它是一个从零开始的索引. (9认同)
  • 请注意,我在正确的情况下标记这个答案是因为所有者(Amarghosh)在对我的问题的评论中回答了我的问题.HashTable将更好地满足我的需求. (3认同)

小智 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)

如果索引不存在,则添加新条目.你可以改变它来做一些不同的事情.

  • 请记住避免使用`try/catch`进行此类工作,它会使您的程序速度降低50%或更多..错误检查会为您的现有代码添加一条带子以减慢其速度..更好地避免它关键领域.在这种情况下检查`length`是你能做的最好的事情,因为`index`总是小于`length`,旧`index`将被转移并成为新的`index`如果你`删除它们,这就是为什么检查`length`的规则总是有效的. (10认同)
  • 谢谢,需要这种技术来进行单元测试是否存在数组索引. (2认同)
  • 使用异常进行流量控制,如本示例所示,这是一种反模式 https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-如果-是-为什么 (2认同)

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随着时间的推移而增长,并且数组无法做到. (3认同)

sta*_*ker 6

关于你的更新(可能应该是另一个问题).您应该使用这些对象的数组而不是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等.

使用异常控制流是不好的做法.

  • 如果 array[8] 不存在,则会遇到 ArrayIndexOutOfBoundException。 (2认同)

Ant*_*iuc 5

由于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)


Aam*_*irR 5

通常我只是检查索引是否小于数组大小

if (index < list.size()) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

如果您还担心索引是负值,请使用以下内容

if (index >= 0 && index < list.size()) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 与几年前的 [已接受答案](/sf/answers/149227781/) 相比,这如何提供任何价值? (2认同)
  • 我想在你看来它没有提供任何价值,但我看到罗伯托·托马斯对接受的答案的评论,假设他不太明白接受的答案.检查出来"有一个新的列表我将从index = 0开始,我的list.size()== 0.所以我第一次检查它是真的"我决定发一个单独的答案来帮助任何未来的困惑. (2认同)