0

I have a list of object array in this structure:

List<Object[]> numbers = new ArrayList<>();
numbers.add(new Object[]{1, 2, 3, 4});

I want to check whether an array of objects exist in that list. The contains method always returns false. I use contains in this way:

if(numbers.contains(new Object[]{1,2,3,4}))

This condition always returns false. What's the problem?

9
  • can you have array of Integers instead of objects? Commented Dec 21, 2015 at 6:17
  • 1
    new Something() create a new instance so both your new Object[]{1, 2, 3, 4} are differents (not the same hashcode) Commented Dec 21, 2015 at 6:17
  • @RC. but the contains method uses equals method to find the matching object Commented Dec 21, 2015 at 6:19
  • 1
    @sidgate - Yes, but for arrays, equals() sin't overriden and hence you will only be checking references Commented Dec 21, 2015 at 6:20
  • in that case instead of using List<Object[]> you should use List<List<Object>> Commented Dec 21, 2015 at 6:21

1 Answer 1

0

You can try this:

List<Object[]> numbers = new ArrayList<>();
numbers .add(new Object[]{1, 2, 3, 4});
boolean b = list.stream().anyMatch(o -> Arrays.deepEquals(o, new Object[]{1, 2, 3, 4}));

System.out.println("b = " + b);

And the result is:

b = true
Sign up to request clarification or add additional context in comments.

4 Comments

I get the feeling that this question would benefit more from that answer, as a Java 8 option.
I have checked in my PC, it works well, you can try.
You should try this, don't use new Operator List<Object[]> numbers = new ArrayList<>(); Object[] obj = new Object[]{1, 2, 3, 4}; numbers.add(obj); if(numbers.contains(obj)) System.out.println("True"); else System.out.println("False");
Yes, I know it works. That's probably why I haven't downvoted it. The main point here is that the duplicate question which I've linked to in a response (and subsequently voted to close this question as) would benefit far more from this answer, since first - this is a duplicate question and second - a Java 8 option is indeed missing from the linked dupe.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.