如何在 Java 中獲取列表中元素的索引?


List 的 indexOf() 方法用於獲取元素在列表中的位置。

int indexOf(Object o)

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

引數

  • o − 要搜尋的元素。

返回值

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

丟擲

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

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

示例

以下是顯示 indexOf() 方法用法的示例 -

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);
      String student = "Ayan";
      String missingStudent = "Aman";
      System.out.println("Ayan is present at: " + list.indexOf(student));
      System.out.println("Aman index: " + list.indexOf(missingStudent));
   }
}

輸出

這將產生以下結果 -

List: [Zara, Mahnaz, Ayan]
Ayan is present at: 2
Aman index: -1

更新於: 2022年5月10日

20K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.