在 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() 返回 “C” 和 “Z” 的第一次出现的索引,分别存储在 index1 和 index2 中。然后使用一个 if 语句检查 index1 是否为 -1。如果是,则 ArrayList 中没有 C。使用 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);
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP