Reputation: 824
animals.java
public class animals{
static ArrayList<animals> anV = new ArrayList<animals>();
static ArrayList<animals> anF = new ArrayList<animals>();
......
..
.
}
public void metod1(String tur){
ArrayList<animals> an;
if(tur.equals("V")) an = anV;
else an = anF;
for (animals data : an) {
an.add(blah blah);
..........
}
}
Add work normally but not add when tur == "V" then list to > anV. add to an list, not anV.
i change tur.equals but not work. because program add to an list, i want add to anV.
Upvotes: 0
Views: 104
Reputation: 91379
==
can be used to compare primitive types, such as char
s and int
s; but not a String
, which is an Object
. If you use it to compare String
s, it will compare their references, not their contents.
Thus, to compare String
s, use String#equals()
:
if (tur.equals("V")) {
}
Also, you're adding elements to a Collection
that you are iterating over. Are you sure there isn't a typo here?
for (animals data : an) {
an.add(blah blah);
}
Upvotes: 3
Reputation: 66677
if(tur == "V")
String comparison should use eqauls()
instead of ==
Unless Strings you are comparing are String
literals.
Upvotes: 4