ConcurrentLinkedDeque contains() method in Java with Examples


The ConcurrentLinkedDeque class in Java is a thread-safe implementation of the Deque interface. It provides methods to add, remove, and access elements from both ends of the deque. The contains() method is used to check if a particular element is present in the deque or not.

The syntax of the contains() method is as follows:

public boolean contains(Object o)

Here, o is the object to be checked for presence in the deque. The method returns true if the deque contains the specified element, otherwise it returns false.

Example 1: Using contains() method on a ConcurrentLinkedDeque

ConcurrentLinkedDeque<String> deque = new ConcurrentLinkedDeque<>();

deque.add("apple");
deque.add("banana");
deque.add("orange");

System.out.println(deque.contains("banana")); // true
System.out.println(deque.contains("grape")); // false

In this example, we create a ConcurrentLinkedDeque object and add three elements to it. We then use the contains() method to check if the deque contains the elements "banana" and "grape". The method returns true for "banana" and false for "grape".

Example 2: Using contains() method with custom objects

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

ConcurrentLinkedDeque<Person> deque = new ConcurrentLinkedDeque<>();

deque.add(new Person("Alice", 25));
deque.add(new Person("Bob", 30));
deque.add(new Person("Charlie", 35));

Person person = new Person("Bob", 30);
System.out.println(deque.contains(person)); // true

In this example, we create a custom Person class with name and age fields. We override the equals() and hashCode() methods to compare two Person objects based on their name and age fields. We then create a ConcurrentLinkedDeque object and add three Person objects to it. We create a new Person object with the same name and age as the second Person object in the deque. We use the contains() method to check if the deque contains this Person object. The method returns true because the equals() method of the Person class is used to compare the objects.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.