How to Search Element in List in Java: Simple Guide
To search for an element in a Java
List, use the contains() method to check if the element exists or indexOf() to find its position. Both methods are simple and work directly on the list object.Syntax
Here are the common ways to search for an element in a Java List:
boolean contains(Object o): Returnstrueif the list contains the element.int indexOf(Object o): Returns the index of the first occurrence of the element, or-1if not found.
java
list.contains(element); list.indexOf(element);
Example
This example shows how to check if a list contains a string and how to find its index.
java
import java.util.List; import java.util.ArrayList; public class SearchListExample { public static void main(String[] args) { List<String> fruits = new ArrayList<>(); fruits.add("apple"); fruits.add("banana"); fruits.add("cherry"); String searchFruit = "banana"; boolean found = fruits.contains(searchFruit); int position = fruits.indexOf(searchFruit); System.out.println("Contains '" + searchFruit + "'? " + found); System.out.println("Index of '" + searchFruit + "': " + position); } }
Output
Contains 'banana'? true
Index of 'banana': 1
Common Pitfalls
Common mistakes when searching in a list include:
- Using
==to compare objects instead ofequals(), whichcontains()andindexOf()use internally. - Not handling the case when
indexOf()returns-1, meaning the element was not found. - Assuming
contains()works with different object types without properequals()implementation.
java
import java.util.List; import java.util.ArrayList; public class PitfallExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("cat"); list.add("dog"); String search = new String("cat"); // Wrong: using == (compares references, not content) boolean wrongCheck = false; for (String s : list) { if (s == search) { wrongCheck = true; break; } } // Right: use contains() which uses equals() boolean rightCheck = list.contains(search); System.out.println("Wrong check (==): " + wrongCheck); System.out.println("Right check (contains): " + rightCheck); } }
Output
Wrong check (==): false
Right check (contains): true
Quick Reference
Summary tips for searching elements in a Java list:
- Use
contains()to check presence (returns boolean). - Use
indexOf()to find position (returns index or -1). - Remember
contains()andindexOf()useequals()for comparison. - Handle
-1result fromindexOf()to avoid errors.
Key Takeaways
Use list.contains(element) to check if an element exists in a Java list.
Use list.indexOf(element) to find the position of an element; it returns -1 if not found.
contains() and indexOf() rely on equals() method for comparing elements.
Avoid using == to compare list elements; it checks references, not content.
Always check for -1 from indexOf() before using the index.