如何在 Java 中檢查列表中是否存在某個元素?


可以使用 indexOf() 或 contains() 方法檢查列表中的元素。

語法 - indexOf() 方法

int indexOf(Object o)

返回此列表中指定元素第一次出現的索引,如果此列表不包含該元素,則返回 -1。更正式地說,返回最小的索引 i,使得 (o==null ? get(i)==null : o.equals(get(i))),如果不存在這樣的索引,則返回 -1。

引數

  • o − 要搜尋的元素。

返回值

此列表中指定元素第一次出現的索引,如果此列表不包含該元素,則返回 -1。

丟擲異常

  • ClassCastException − 如果指定元素的型別與此列表不相容(可選)。

  • NullPointerException − 如果指定元素為 null 且此列表不允許 null 元素(可選)。

語法 - contains() 方法

boolean contains(Object o)

如果此列表包含指定的元素,則返回 true。更正式地說,當且僅當此列表至少包含一個元素 e 使得 (o==null ? e==null : o.equals(e)) 時,返回 true。

引數

  • o − 要測試其在此列表中是否存在元素。

返回值

如果此列表包含指定的元素,則返回 true。

丟擲異常

  • ClassCastException − 如果指定元素的型別與此列表不相容(可選)。

  • NullPointerException − 如果指定元素為 null 且此列表不允許 null 元素(可選)。

示例

以下是使用各種方法從列表中查詢元素的示例:

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>();
      list.add("Zara");
      list.add("Mahnaz");
      list.add("Ayan");
      System.out.println("List: " + list);
      System.out.println("Ayan is present: " + list.contains("Ayan"));
      int index = list.indexOf("Ayan");
      System.out.println("Ayan is present at: " + index);
   }
}

輸出

這將產生以下結果:

List: [Zara, Mahnaz, Ayan]
Ayan is present: true
Ayan is present at: 2

更新於: 2022年5月10日

6K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.