songyuanyao
songyuanyao

Reputation: 173024

How can I check if an object exists in a List by specialized comparing way?

For example I have a List as List<MyClass>.

List.contains() will use Object.equals() for comparing, so I have to implement the method MyClass.equals() with correct semantic, but I can't modify it.

Is there an API that can use the specialized comparing method/class for checking except for loop & check by myself?

The list is not sorted list so I can't use Collections.binarySearch().

Upvotes: 0

Views: 58

Answers (2)

Harmlezz
Harmlezz

Reputation: 8078

The contract for the method contains() is:

java.util.Collection

Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).

Hence I think it is no good idea to override the method, violating the contract. Due to the fact that your List isn't sorted, finding a matching element is O(n), where n is the number of elements contained in the List.

Iterating over each element as suggested by songyuanyao in the answer above should not hurt and is straight forward.

Another solution would be to use com.google.common.collect.Collections2.filter() which takes a Collection and a predicate and returns another collection containing only elements matching the predicate.

Upvotes: 0

Warlord
Warlord

Reputation: 2826

You can specify a custom contains() method for a single instance of a List, during instantiation such as this:

List<String> list = new ArrayList<String>() {

        @Override
        public boolean contains(Object o) {
            // your own implementation
        }
    };

Upvotes: 1

Related Questions