LinkedListlist = new LinkedList (); list.add("Apple"); list.add("Banana"); list.add("Cherry"); int index = list.indexOf("Banana"); System.out.println("Index of Banana: " + index); // Output: Index of Banana: 1
LinkedListIn this example, we search for an element "Grapes" that does not exist in the LinkedList. The indexOf() method returns -1 indicating that the element is not present in the list. Package Library: java.utillist = new LinkedList (); list.add("Apple"); list.add("Banana"); list.add("Cherry"); int index = list.indexOf("Grapes"); System.out.println("Index of Grapes: " + index); // Output: Index of Grapes: -1