在 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