简体   繁体   English

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

[英]ArrayList - how can I check if an index exists?

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?我应该简单地get()并检查值吗? 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.更新:感谢您的回答,但由于我只在特定索引处添加内容,因此列表的长度不会显示哪些可用。

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

if(index >= myList.size() || index < 0){
  //index does not exists
}else{
 // index exists
}

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.你可以改变它来做一些不同的事情。

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.我认为对 List 的索引访问是一种代码味道。

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()) {
    ...
}

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.使用异常的控制流是不好的做法。

This is for Kotlin developers ending up here:这是为Kotlin开发人员准备的:

if (index in myList.indices) {
  // index is valid
}

Other solutions:其他解决方案:

if (index in 0..myArray.lastIndex) {
  // index is valid
}
if (index >= 0 && index <= myList.lastIndex) {
  // index is valid
}
// Note: elements of the list should be non-null
if (myList.getOrNull(index) != null) {
  // index is valid
}
// Note: elements of the list should be non-null
myList.getOrNull(index)?.let { element ->
  // index is valid; use the element
}

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

You can check the size of an ArrayList using the size() method.您可以使用size()方法检查ArrayList的大小。 This will return the maximum index +1这将返回最大索引 +1

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...或者对于二维数组列表...

public boolean hasRow(int row){
    if(row < _matrix.size())
        return true;
    return false;
}

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'
    }
}

a simple way to do this:一个简单的方法来做到这一点:

try {
  list.get( index ); 
} 
catch ( IndexOutOfBoundsException e ) {
  if(list.isEmpty() || index >= list.size()){
    // Adding new item to list.
  }
}

If your index is less than the size of your list then it does exist, possibly with null value.如果您的索引小于列表的大小,则它确实存在,可能具有null值。 If index is bigger then you may call ensureCapacity() to be able to use that index.如果索引更大,那么您可以调用ensureCapacity()来使用该索引。

If you want to check if a value at your index is null or not, call get()如果要检查索引处的值是否为null ,请调用get()

Scanner input = new Scanner(System.in);
    System.out.println("Enter the index to check");
    int i  = input.nextInt();
    if (i > tasksList.size() || i < 0 ){
        System.out.println("invalid input");
    }else {
            //your code
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM