Explain Codes LogoExplain Codes Logo

Check if a value exists in ArrayList

java
equals-hashcode
object-comparison
collections
Anton ShumikhinbyAnton Shumikhin·Dec 1, 2024
TLDR

To determine if an element is present in an ArrayList, utilize the contains() method:

ArrayList<String> fruits = new ArrayList<>(Arrays.asList("Apple", "Banana")); boolean hasApple = fruits.contains("Apple"); // true because "Apple" exists in the list

The contains() function will return true if the queried item is found and false otherwise.

To ensure object equality while checking for presence using contains(), it is critical to override the equals() method in your object's class.

Mastering equals() and hashCode()

When dealing with object instances in a collection, such as ArrayList, it is critical to understand equals() and hashCode(). These two methods form the backbone of object comparisons and hashing.

class CurrentAccount { private String accountId; // Constructors, getters, setters… @Override public boolean equals(Object obj) { // First check! Are you literally me? if (this == obj) return true; // Second check! Are you even of my kind? if (obj == null || getClass() != obj.getClass()) return false; // If passed above, go ahead with field comparison CurrentAccount that = (CurrentAccount) obj; return accountId != null ? accountId.equals(that.accountId) : that.accountId == null; } @Override public int hashCode() { return accountId != null ? accountId.hashCode() : 0; } }

Leverage the power of IDEs like Eclipse to generate the equals() and hashCode() methods, ensuring reliable object-to-object comparison.

Performance trade-offs: List vs. Set

For larger datasets where unique elements are desired, and quick existence checks are crucial, consider using a HashSet. It offers constant time performance for insert operations and searches, unlike ArrayList's linear time complexity.

HashSet<CurrentAccount> accountSet = new HashSet<>(accountList); // Convert ArrayList to HashSet boolean exists = accountSet.contains(desiredAccount); // A quicker search than list.contains()

Supercharging with Java 8 streams

Java 8 streams infuse collections operations with functional programming goodness.

boolean accountExists = accountList.stream() .anyMatch(account -> desiredAccountId.equals(account.getAccountId())); // Office-style search for Michael Scott

Streams shine when you need to filter collections based on properties, but remember, performance may degrade with large data sets.

Graceful exception handling

The contains() method is robust, but "expect the unexpected". Always ensure to handle potential runtime exceptions, especially when object comparisons involve nullable fields or complex logic.

Validating type consistency

Inside the equals() method, use getClass() to check against the exact type of the object. This is stricter than instanceof and keeps those bratty subclasses from slipping through!

Object presence and user feedback

Add your objects to an ArrayList and use contains() to verify their presence. Upgrade this operation by implementing user-friendly notifications based on the check outcome.

ArrayList<CurrentAccount> accounts = new ArrayList<>(); accounts.add(new CurrentAccount("12345")); // An account number as unique as "password123" CurrentAccount queryAccount = new CurrentAccount("12345"); // Notify user about the account existence if (accounts.contains(queryAccount)) { System.out.println("Account exists!"); // Yay! You exist. } else { System.out.println("Account does not exist."); // Oops! Existential crisis. }

Extra tips and tricks

While ArrayList offers features like order preservation and random access, HashSet provides quick lookups. Analyze your use case and choose the best tool for the job.

Also, proper implementation and consistency between equals() and hashCode() cannot be overemphasized; it helps ensure ArrayList.contains() gives accurate results.

Lastly, beyond this answer, take time to explore the Java documentation and books like "Effective Java" by Joshua Bloch to further deepen your understanding of Java collections.