这个 indexOf() 方法 ArrayList 返回 第一次发生 此列表中指定元素的,或 -1 如果此列表不包含该元素。
null
语法:
public int IndexOf(Object o) obj : The element to search for.
// Java code to demonstrate the working of // indexOf in ArrayList // for ArrayList functions import java.util.ArrayList; public class IndexOfEx { public static void main(String[] args) { // creating an Empty Integer ArrayList ArrayList<Integer> arr = new ArrayList<Integer>( 5 ); // using add() to initialize values arr.add( 1 ); arr.add( 2 ); arr.add( 3 ); arr.add( 4 ); // printing initial value System.out.print( "The initial values in ArrayList are : " ); for (Integer value : arr) { System.out.print(value); System.out.print( " " ); } // using indexOf() to find index of 3 int pos =arr.indexOf( 3 ); // prints 2 System.out.println( "The element 3 is at index : " + pos); } } |
输出:
The initial values in ArrayList are : 1 2 3 4 The element 3 is at index : 2
实际应用: 索引函数对于 确定事件的最后或第一次发生 例如,掷骰子时最后一次出现6,或名字中第一次出现任何字母等。
还有一个例子:
// Java code to demonstrate the application of // index functions in ArrayList // for ArrayList functions import java.util.ArrayList; public class AppliIndex { public static void main(String[] args) { // creating an Empty Integer ArrayList ArrayList<Integer> arr = new ArrayList<Integer>( 10 ); // using add() to initialize dice values arr.add( 1 ); arr.add( 2 ); arr.add( 4 ); arr.add( 6 ); arr.add( 5 ); arr.add( 2 ); arr.add( 6 ); arr.add( 1 ); arr.add( 6 ); arr.add( 4 ); // using IndexOf() to find first index of 6 int pos1 =arr.indexOf( 6 ); // using lastIndexOf() to find last index of 6 int pos2 =arr.lastIndexOf( 6 ); // to balance 0 based indexing pos1 = pos1+ 1 ; pos2 = pos2+ 1 ; // printing first index of 6 System.out.println( "The first occurrence of 6 is : " + pos1); // printing last index of 6 System.out.println( "The last occurrence of 6 is : " + pos2); } } |
输出:
The first occurrence of 6 is : 4 The last occurrence of 6 is : 9
本文由 沙姆巴维·辛格 .如果你喜欢GeekSforgek并想投稿,你也可以使用“投稿”撰写文章。极客。组织或邮寄你的文章到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END