"indexOf()" 方法如何工作以及可以在哪里使用?

How does "indexOf()" method work and where can it be used?

我是 Java 的新手,正在尝试学习迭代器的概念。我从 Java Tutorial Oracle 看到了下面的代码,但是,我很难理解这个方法的功能以及如何使用它。有人可以向我提供一个示例,说明如何将此方法用作工作代码的一部分并向我解释它是如何工作的吗?

public int indexOf(E e) {
    for (ListIterator<E> it = listIterator(); it.hasNext(); )
        if (e == null ? it.next() == null : e.equals(it.next()))
            return it.previousIndex();
    // Element not found
    return -1;
}

这是一种查找元素 e(通用类型 E)的索引的方法,该元素可能(或可能不)包含在基础 Collection 中。如果存在,它使用 it.previousIndex() 到 return 元素的索引值。否则,它 returns -1.

indexOf() 方法用于查找特定字符的索引,或字符串中特定子字符串的索引。请记住,所有内容都是零索引的(如果您还不知道的话)。这是一个简短的例子:

public class IndexOfExample {

   public static void main(String[] args) {

       String str1 = "Something";
       String str2 = "Something Else";
       String str3 = "Yet Another Something";

       System.out.println("Index of o in " + str1 + ": " + str1.indexOf('o'));
       System.out.println("Index of m in " + str2 + ": " + str2.indexOf('m'));
       System.out.println("Index of g in " + str3 + ": " + str3.indexOf('g'));
       System.out.println("Index of " + str1 + " in " + str3 + ": " + str3.indexOf(str1));
   }
}

输出:

Index of o in Something: 1
Index of m in Something Else: 2
Index of g in Yet Another Something: 20
Index of Something in Yet Another Something: 12