Firstly I created the ArrayList of Strings:
List<List<String>> array1 = new ArrayList<List<String>>();
Then after populating it with data and doing a print:
[John, Smith, 120]
[Albert, Einstein, 170]
Now I want to loop through the list and do a comparison with say String[] array2 = {"Albert", "Einstein", "170"} and I’ve tried so far:
if (array1.get(i).equals(array2)) { blah }
However this is not working, I basically want traverse the arraylist and find if my array2 gets a match or not. How can I make this work?
A list simply isn’t equal to an array. The simplest fix for this would be to wrap your array in a list first:
That will then use the
equalsimplementation which just performs sequential equality checking on each item.If you just want to find the first matching entry, then using
indexOfas per Louis’s answer will also work.I would also strongly suggest that you don’t call a variable
array1when it’s not an array.Finally, if you’re using
List<String>just as a wrapper to avoid having to create a real data structure with (say) names and ages in, then don’t: create aPersonclass, so you end up with:… implement equality and hashing appropriately, and you’ll be good to go. Your code will be much simpler to read and maintain that way.