Check If Element Exists in Java Vector Example

This example shows how to check if the element exists in Vector in Java. This example also shows how to check if the custom class object element exists in vector using the contains method.

How to check if the element exists in Vector in Java?

The Vector contains method returns true if the specified element exists in this vector object.

It returns false if the vector does not contain the specified element.

Output

How to check if the custom class object element exists in the Vector?

Let’s see what happens when we check for the element that is an object of a custom class using the contains method.

Output

So even if the specified object was present in the vector object, the contains method returned false.

That is because the contains method relies on the equals method of the element object. Since the Student class has not overridden the equals method, the equals method inherited from the Object class was used that compares the object references, not the actual objects.

We need to override the equals method (and hashCode method too) for the contains method to search and compare the specified object in the vector. Let’s override these methods in the Student class and try again.

Output

As we can see from the output, the contains method worked for the custom class object as expected this time.

This example is a part of the Vector in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Vector Documentation

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping