The example show you how to retrieve particular object from LinkedList
using the indexOf()
method.
package org.kodejava.util;
import java.util.List;
import java.util.LinkedList;
public class LinkedListIndexOf {
public static void main(String[] args) {
List<String> names = new LinkedList<>();
names.add("Alice");
names.add("Bob");
names.add("Carol");
names.add("Mallory");
// Search for Carol using the indexOf method. This method
// returns the index of the object when found. If not found
// -1 will be returned.
int index = names.indexOf("Carol");
System.out.println("Index = " + index);
// We can check to see if the index returned is in the range
// of the LinkedList element size.
if (index > 0 && index < names.size()) {
String name = names.get(index);
System.out.println("Name = " + name);
}
}
}
The program prints the following output:
Index = 2
Name = Carol
Latest posts by Wayan (see all)
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023