How do I retrieve particular object from LinkedList?
Category: java.util, viewed: 331 time(s).
The example show you how to retrieve particular object from LinkedList using the indexOf() method.
package org.kodejava.example.util;
import java.util.List;
import java.util.LinkedList;
public class LinkedListIndexOf {
public static void main(String[] args) {
List<String> names = new LinkedList<String>();
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
Can't find what you are looking for? Join our
FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!