Skip to content

Files

Latest commit

Oct 8, 2019
224d55e · Oct 8, 2019

History

History
46 lines (35 loc) · 1.19 KB

File metadata and controls

46 lines (35 loc) · 1.19 KB

Java ArrayList indexOf()方法

原文: https://beginnersbook.com/2013/12/java-arraylist-indexof-method-example/

ArrayList类方法indexOf(Object o)用于查找列表中特定元素的索引。

public int indexOf(Object o)

如果列表中不存在指定的元素,则此方法返回 -1。

package beginnersbook.com;
import java.util.ArrayList;
public class IndexOfExample {
  public static void main(String[] args) {
      ArrayList<String> al = new ArrayList<String>();
      al.add("AB");
      al.add("CD");
      al.add("EF");
      al.add("GH");
      al.add("IJ");
      al.add("KL");
      al.add("MN");

      System.out.println("Index of 'AB': "+al.indexOf("AB"));
      System.out.println("Index of 'KL': "+al.indexOf("KL"));
      System.out.println("Index of 'AA': "+al.indexOf("AA"));
      System.out.println("Index of 'EF': "+al.indexOf("EF"));
  }
}

输出:

Index of 'AB': 0
Index of 'KL': 5
Index of 'AA': -1
Index of 'EF': 2

参考:

ArrayList.indexOf(Object)