Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList<int[]> containing a value

Tags:

java

if i have an ArrayList<int[]> example and I want to check if {2,4} is in it how would I do this?

exaple.contains({2,4}); //doesn't work

and

exaple.contains(2,4); //doesn't work either

what is wrong with the code?

like image 939
user3328784 Avatar asked Dec 20 '22 17:12

user3328784


1 Answers

Arrays don't override the Object.equals() method (that ArrayList.contains() uses to compare objects). So an array is only equal to itself. You'll have to loop through the list and compare each element with your array using Arrays.equals().

What I suspect, though, is that you shouldn't have a List<int[]>, but a List<Coordinate>. The Coordinate class could then override equals() and hashCode(), and you would be able to use

example.contains(new Coordinate(2, 4))

You could also use a List<List<Integer>>, but if what I suspect is true (i.e. you're using arrays to hold two coordinates that should be in class), then go with the custom Coordinate class.

like image 183
JB Nizet Avatar answered Jan 02 '23 22:01

JB Nizet