- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Search a particular element in a LinkedList in Java
A particular element can be searched in a LinkedList using the method java.util.LinkedList.indexOf(). This method returns the index of the first occurance of the element that is searched. If the element is not available in the LinkedList, then this method returns -1.
A program that demonstrates this is given as follows −
Example
import java.util.LinkedList; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("A"); l.add("B"); l.add("C"); l.add("D"); l.add("E"); System.out.println("The index of element B in LinkedList is: " + l.indexOf("B")); System.out.println("The index of element Z in LinkedList is: " + l.indexOf("Z")); } }
Output
The index of element B in LinkedList is: 1 The index of element Z in LinkedList is: -1
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. LinkedList.indexOf() returns the index of the first occurrence of “B” and “Z” and that is displayed. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>(); l.add("A"); l.add("B"); l.add("C"); l.add("D"); l.add("E"); System.out.println("The index of element B in LinkedList is: " + l.indexOf("B")); System.out.println("The index of element Z in LinkedList is: " + l.indexOf("Z"));
Advertisements
To Continue Learning Please Login
Login with Google