1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
/* Search elements of LinkedList Java example This java example shows how to search element of Java LinkedList using indexOf and lastIndexOf methods. */ import java.util.LinkedList; public class SearchElementLinkedListExample { public static void main(String[] args) { //create LinkedList object LinkedList lList = new LinkedList(); //add elements to LinkedList lList.add("1"); lList.add("2"); lList.add("3"); lList.add("4"); lList.add("5"); lList.add("2"); /* * To search first occurrence of an element of LinkedList, use * int indexOf(Object element) method. * * This method returns index of first occurrence of element if found in * the LinkedList. It returns -1 if element not found. */ int index = lList.indexOf("2"); if(index != -1) { System.out.println("First occurrence of 2 in LinkedList is at index : " + index); } else { System.out.println("LinkedList does not contain 2"); } /* * To search last occurrence of an element of LinkedList, use * int lastIndexOf(Object element) method. * * This method returns index of last occurrence of element if found in * the LinkedList. It returns -1 if element not found. */ index = lList.lastIndexOf("2"); if(index != -1) { System.out.println("Last occurrence of 2 in LinkedList is at index : " + index); } else { System.out.println("LinkedList does not contain 2"); } } } |
what if we have multiple object elements, suppose we are searching for Book details, which consist of Title, Author, Price etc…this case how we are going to search for a perticular Book?
I’m assuming we use if-else statement, I’m I right? Can anybody answer?
—Thank You.