Reputation: 10058
I'm new to Java and is trying to learn the concept of iterator. I saw the code below from Java Tutorial Oracle, however, I am struggling to understand the function of this method and how it could be used. Could someone provide me with an example of how to use this method as part of an working code and explain it to me how it works?
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;
}
Upvotes: 2
Views: 2100
Reputation: 1387
The indexOf() method is used to find the index of a particular character, or the index of a particular substring in a string. Keep in mind that everything is zero indexed (if you didn't already know). Here is a brief example:
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));
}
}
Output:
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
Upvotes: 1
Reputation: 201447
This is a method for finding the index of an element e
(of generic type E
) that may (or may not) be contained by the underlying Collection
. If present, it uses it.previousIndex()
to return the index value for the element. Otherwise, it returns -1
.
Upvotes: 2