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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With