I have an arraylist of integer arrayslists and an arraylist of names. I’d like to add a certain number to one of those integer arraylists when it corresponds with a particular name and add a 0 to every other arraylist. I think that what I have should work, but it simply adds a 0 to everything and ignores the special case when the name is right. “Rating” is an integer, and “user” is a string. “Names” is an arraylist of strings. The language is Java.
for(int i = 0; i<names.size(); i++)
{
if (names.get(i)==user)
allratings.get(i).add(rating);
if (names.get(i)!=user)
allratings.get(i).add(0);
}
Is there something wrong with my syntax? When I insert a print line, I find that my names arraylist and my allratings arraylist are perfectly matched up. Where am I going wrong?
Use
.equals()when comparing Strings in Java:Comparing Strings in Java with
==will compare references, which might not be what you want. It seems that the references are different, even though they hold the same string. This is why your condition is always returning false. You want to compare the actual value of the string. This is done with.equals().