1

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?

0

3 Answers 3

8

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.

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

3 Comments

Thanks for the advice on some good practices, as a beginner I appreciate this kind of help!
If I can just squeeze in a little question here: I want to traverse the list and look for people with > 130 IQ (so the third element) however I'm stuck as numerical values are stored as characters. Any way around this? Also how do I reference the third element array1.get(i)[2] (a wild guess)?
@meiryo: As I said at the end: don't deal with strings, create a class representing the data. That will solve both of your problems, as you'll have the age as an integer, and you won't need to remember the magic number of an index.
2
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.

Comments

1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.