logo

JavaリストのindexOf()メソッド

List インターフェイスのindexOf() メソッドは、このリスト内で最初に出現する指定された要素のインデックスを返します。指定された要素がこのリストに存在しない場合は、-1 を返します。

構文

 public int indexOf(Object o) 

パラメーター

パラメータ「o」は検索対象の要素を表します。

投げる:

クラスキャスト例外 - 指定された要素のタイプがこのリストと互換性がない場合。

NullPointerException - 指定された要素が null であり、このリストが null 要素を許可しない場合。

例外スローJava

戻る

IndexOf() メソッドは、指定された要素がこのリストに存在する場合はその要素の最初のインデックスを返し、存在しない場合は -1 を返します。

例1

 import java.util.LinkedList; import java.util.List; public class JavaListIndexOfExample1 { public static void main(String[] args) { List list= new LinkedList(); for (int i=0;i<6;i++){ list.add(i); returns the element at specified position in this list int value="list.indexOf(i);" system.out.println('element stored index '+i+' : '+value); } < pre> <span> Test it Now </span> <p> <strong>Output:</strong> </p> <pre> Element stored at index 0 : 0 Element stored at index 1 : 1 Element stored at index 2 : 2 Element stored at index 3 : 3 Element stored at index 4 : 4 Element stored at index 5 : 5 </pre> <h2>Example 2</h2> <pre> import java.util.LinkedList; import java.util.List; public class JavaListIndexOfExample2 { public static void main(String[] args) { List list= new LinkedList(); list.add(null); list.add(null); list.add(null); // returns -1 if the no value is present in the specified index int value =list.indexOf(90); System.out.println(&apos;Element stored at Index &apos;+90+&apos; : &apos;+value); } } </pre> <span> Test it Now </span> <p> <strong>Output:</strong> </p> <pre> Element stored at Index 90 : -1 </pre> <h2>Example 3</h2> <pre> import java.util.LinkedList; import java.util.List; public class JavaListIndexOfExample3 { public static void main(String[] args) { List list= new LinkedList(); list.add(67); list.add(89); // returns -1 if the no value is present in the specified index int value =list.indexOf(null); System.out.println(&apos;Element stored at &apos;+null+&apos; : &apos;+value); } } </pre> <span> Test it Now </span> <p> <strong>Output:</strong> </p> <pre> Element stored at null : -1 </pre></6;i++){>

例 2

 import java.util.LinkedList; import java.util.List; public class JavaListIndexOfExample2 { public static void main(String[] args) { List list= new LinkedList(); list.add(null); list.add(null); list.add(null); // returns -1 if the no value is present in the specified index int value =list.indexOf(90); System.out.println(&apos;Element stored at Index &apos;+90+&apos; : &apos;+value); } } 
今すぐテストしてください

出力:

 Element stored at Index 90 : -1 

例 3

 import java.util.LinkedList; import java.util.List; public class JavaListIndexOfExample3 { public static void main(String[] args) { List list= new LinkedList(); list.add(67); list.add(89); // returns -1 if the no value is present in the specified index int value =list.indexOf(null); System.out.println(&apos;Element stored at &apos;+null+&apos; : &apos;+value); } } 
今すぐテストしてください

出力:

 Element stored at null : -1