meiryo
meiryo

Reputation: 11697

Having trouble comparing an ArrayList of Strings with a String array

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?

Upvotes: 1

Views: 220

Answers (3)

Chakradhar K
Chakradhar K

Reputation: 509

As per your given example both are lists. So try if you can work out with list1.containsAll(list2) i.e, conatinsAll method. Hope it helps

There is also an example here Have I found a bug in java.util.ArrayList.containsAll?

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503290

A list simply isn't equal to an array. The simplest fix for this would be to wrap your array in a list first:

if (array1.get(i).equals(Arrays.asList(array2))

That will then use the equals implementation which just performs sequential equality checking on each item.

If you just want to find the first matching entry, then using indexOf as per Louis's answer will also work.

I would also strongly suggest that you don't call a variable array1 when 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 a Person class, so you end up with:

List<Person> people = new ArrayList<Person>();
Person testPerson = new Person("Albert", "Einstein", 170);

... implement equality and hashing appropriately, and you'll be good to go. Your code will be much simpler to read and maintain that way.

Upvotes: 8

Louis Wasserman
Louis Wasserman

Reputation: 198471

return listOfListsOfStrings.indexOf(Arrays.asList(arrayOfStrings));

would find out if there are any matches for that array in the list. It returns i, if the ith list matches the array, and -1 if no matches are found. You don't even need a for loop.

Upvotes: 2

Related Questions