1

Im adding a POJO to a linked list and now I want to check if the list contains that object. The code below does not work, any suggestions?

List<Object> data = new LinkedList<Object>();

FooBar obj = new FooBar();

data.add(obj);

if (data.contains(FooBar.class)) {
    // true
}
ericbn
  • 10,163
  • 3
  • 47
  • 55

3 Answers3

1

Have you tried

if (data.contains(obj)) {
    // true
}

?

The method contains() for a List will only return true if, for any element in the list, is true that element.equals(parameter).

EDIT: If you're trying to test is there is any instance of FooBar in your list and you're using Java 8, you can do:

if (strs.stream().anyMatch(e -> e instanceof FooBar)) {
    // true
}
ericbn
  • 10,163
  • 3
  • 47
  • 55
0

Firstly you need to do data.contains(obj) i.e. pass actual object for comparison.

ArrayList implements the List Interface. If you look at the Javadoc for List at the contains method you will see that it uses the equals() method to evaluate if two objects are the same.

Hence to make this work, you need to override equals method like:

@Override
public boolean equals(Object obj) {
 ..
}
  • What if i'm creating the object in another class, and adding the object to a list in said class. The parent class will receive the list and then will need to test that the object is in the list. How would i test that? –  Jan 05 '16 at 18:24
  • @Purpl3Paul In every scenario you will surely have object of FooBar to be used for comparison which can be used. How you are going to compare without object? – Aaditya Gavandalkar Jan 05 '16 at 18:25
  • This was to check if specific object is present. To check if any object of specified class is present refer to: http://stackoverflow.com/questions/6350158/check-arraylist-for-instance-of-object – Aaditya Gavandalkar Jan 05 '16 at 18:28
  • If i create and instantiate a simple object in a sub class and add the object to a list in the sub class and then return the list to the parent class, how can i test if the list returned has an instance of the simple object. Im not creating any simple object in the parent class. –  Jan 05 '16 at 18:30
0

You will have to override the equals method in the POJO object.

The if you just do contains it would always return false, because the object will never be equal. So you will have to override the POJO object.

You can look at this question on how to override an equals method : How to override equals method in java

For more look at : http://crunchify.com/how-to-override-equals-and-hashcode-method-in-java/

Community
  • 1
  • 1
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108