當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.util.LinkedList.indexOf()用法及代碼示例


描述

這個java.util.LinkedList.indexOf(Object o)方法返回此列表中指定元素第一次出現的索引,如果此列表不包含該元素,則返回 -1。

聲明

以下是聲明java.util.LinkedList.indexOf()方法

public int indexOf(Object o)

參數

o─ 要搜索的元素

返回值

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

異常

NA

示例

下麵的例子展示了 java.util.LinkedList.indexOf() 方法的用法。

package com.tutorialspoint;

import java.util.*;

public class LinkedListDemo {
   public static void main(String[] args) {

      // create a LinkedList
      LinkedList list = new LinkedList();

      // add some elements
      list.add("Hello");
      list.add(2);
      list.add("Chocolate");
      list.add("10");

      // print the list
      System.out.println("LinkedList:" + list);

      // get the index for "Chocolate"
      System.out.println("Index for Chocolate:" + list.indexOf("Chocolate"));

      // get the index for "Coffee"
      System.out.println("Index for Coffee:" + list.indexOf("Coffee"));
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果——

LinkedList:[Hello, 2, Chocolate, 10]
Index for Chocolate:2
Index for Coffee:-1

相關用法


注:本文由純淨天空篩選整理自 Java.util.LinkedList.indexOf() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。