java: ArrayList - 如何检查索引是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2131802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java: ArrayList - how can i check if an index exists?
提问by ufk
I'm using ArrayList<String>
and I add data at specific indices,
how can I check if a specific index exists?
我正在使用ArrayList<String>
并在特定索引处添加数据,如何检查特定索引是否存在?
Should I simply get()
and check the value? Or should I wait for an exception?
Is there another way?
我应该简单地get()
检查价值吗?还是我应该等待异常?还有其他方法吗?
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.
感谢您的回答,但因为我只在特定索引处添加内容,列表的长度不会显示哪些可用。
采纳答案by Amarghosh
回答by Dmitry
If your index is less than the size of your list then it does exist, possibly with null
value. If index is bigger then you may call ensureCapacity()
to be able to use that index.
如果您的索引小于列表的大小,那么它确实存在,可能有null
值。如果索引更大,那么您可以调用ensureCapacity()
以使用该索引。
If you want to check if a value at your index is null
or not, call get()
如果要检查索引中的值是否null
存在,请调用get()
回答by jwoolard
You can check the size of an ArrayList
using the size()
method. This will return the maximum index +1
您可以ArrayList
使用该size()
方法检查一个的大小。这将返回最大索引 +1
回答by miku
You could check for the size of the array.
您可以检查数组的大小。
package sojava;
import java.util.ArrayList;
public class Main {
public static Object get(ArrayList list, int index) {
if (list.size() > index) { return list.get(index); }
return null;
}
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(""); list.add(""); list.add("");
System.out.println(get(list, 4));
// prints 'null'
}
}
回答by Paul McKenzie
This is what you need ...
这就是你需要的......
public boolean indexExists(final List list, final int index) {
return index >= 0 && index < list.size();
}
Why not use an plain old array? Indexed access to a List is a code smell I think.
为什么不使用普通的旧数组?我认为对列表的索引访问是一种代码气味。
回答by stacker
Regarding your update (which probably should be another question). You should use an array of these objects instead an ArrayList, so you can simply check the value for null:
关于您的更新(这可能应该是另一个问题)。您应该使用这些对象的数组而不是 ArrayList,这样您就可以简单地检查 null 的值:
Object[] array = new Object[MAX_ENTRIES];
..
if ( array[ 8 ] == null ) {
// not available
}
else {
// do something
}
Best-Practice
最佳实践
If you don't have hundred of entries in your array you should consider organizing it as a class to get rid of the magic numbers 3,8 etc.
如果您的数组中没有数百个条目,您应该考虑将其组织为一个类以摆脱幻数 3,8 等。
Control flow using exception is bad practice.
使用异常的控制流是不好的做法。
回答by pli
While you got a dozen suggestions about using the size of your list, which work for lists with linear entries, no one seemed to read your question.
虽然您收到了十二条关于使用列表大小的建议,这些建议适用于具有线性条目的列表,但似乎没有人阅读您的问题。
If you add entries manually at different indexes none of these suggestions will work, as you need to check for a specific index.
如果您在不同的索引处手动添加条目,这些建议都不起作用,因为您需要检查特定索引。
Using if ( list.get(index) == null )will not work either, as get() throws an exception instead of returning null.
使用if ( list.get(index) == null )也不起作用,因为 get() 抛出异常而不是返回 null。
Try this:
尝试这个:
try {
list.get( index );
} catch ( IndexOutOfBoundsException e ) {
list.add( index, new Object() );
}
Here a new entry is added if the index does not exist. You can alter it to do something different.
如果索引不存在,这里会添加一个新条目。你可以改变它来做一些不同的事情。
回答by t3dodson
Quick and dirty test for whether an index exists or not. in your implementation replace list With your list you are testing.
快速而肮脏的测试索引是否存在。在您的实现中替换列表 使用您正在测试的列表。
public boolean hasIndex(int index){
if(index < list.size())
return true;
return false;
}
or for 2Dimensional ArrayLists...
或者对于 2Dimensional ArrayLists...
public boolean hasRow(int row){
if(row < _matrix.size())
return true;
return false;
}
回答by Anton Balaniuc
Since java-9
there is a standard way of checking if an index belongs to the array - Objects#checkIndex():
由于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
回答by AamirR
Usually I just check if the index is less than the array size
通常我只是检查索引是否小于数组大小
if (index < list.size()) {
...
}
If you are also concerned of index being a negative value, use following
如果您还担心索引为负值,请使用以下内容
if (index >= 0 && index < list.size()) {
...
}