4

Why does the Java code return false?

List list = new ArrayList();
int[][] arr = {{-1, -1, 2}, {-1, 0, 1}};
list.add(arr[0]);
list.add(arr[1]);
int[] temp = {-1, 0, 1};
return list.contains(temp);

And when the elements in the list are arrays, how do I remove the duplicate then?

Thanks for your reply.

1
  • If you really want contains to work you need to use comparable on your custom array list. And dups you need to create a new list and loop through old or put everything in a hashmap Commented Mar 5, 2017 at 14:39

1 Answer 1

4

Arrays don't override the implementation of Object's equals, so, since list.contains() uses equals to determine if an element appears in the List, it will only return true if you are searching for the exact array object you added to the List. Therefore list.contains(arr[1]) will return true, but list.contains(temp) won't, since temp and arr[1] are different objects (even though they contain the exact same elements).

You can use a List<List<Integer> instead of a List<int[]> in order for list.contains() to function as you expect (since the common implementations of the List interface do override Object's equals).

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.