在Java中搜索ArrayList的元素

可以使用方法java.util.ArrayList.indexOf()搜索ArrayList中的元素。此方法返回指定元素首次出现的索引。如果该元素在ArrayList中不可用,则此方法返回-1。

演示此的程序如下所示-

示例

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add("A");
      aList.add("B");
      aList.add("C");
      aList.add("D");
      aList.add("E");
      int index1 = aList.indexOf("C");
      int index2 = aList.indexOf("Z");
      if(index1 == -1)
         System.out.println("The element C is not in the ArrayList");
      else
         System.out.println("The element C is in the ArrayList at index " + index1);
      if(index2 == -1)
         System.out.println("The element Z is not in the ArrayList");
      else
         System.out.println("The element Z is in the ArrayList at index " + index2);
   }
}

输出结果

The element C is in the ArrayList at index 2
The element Z is not in the ArrayList

现在让我们了解上面的程序。

创建ArrayList aList。然后,使用ArrayList.add()将元素添加到ArrayList中。演示这的代码片段如下-

List aList = new ArrayList();
aList.add("A");
aList.add("B");
aList.add("C");
aList.add("D");
aList.add("E");

ArrayList.indexOf()返回分别存储在index1和index2中的第一次出现的“ C”和“ Z”的索引。然后使用if语句检查index1是否为-1。如果是这样,则C不在ArrayList中。对index2执行类似的过程,并打印结果。演示这的代码片段如下-

int index1 = aList.indexOf("C");
int index2 = aList.indexOf("Z");
if(index1 == -1)
   System.out.println("The element C is not in the ArrayList");
else
   System.out.println("The element C is in the ArrayList at index " + index1);
if(index2 == -1)
   System.out.println("The element Z is not in the ArrayList");
else
   System.out.println("The element Z is in the ArrayList at index " + index2);