kibar
kibar

Reputation: 824

Java arraylist questionn

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

Answers (2)

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91379

== can be used to compare primitive types, such as chars and ints; but not a String, which is an Object. If you use it to compare Strings, it will compare their references, not their contents.

Thus, to compare Strings, 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

kosa
kosa

Reputation: 66677

if(tur == "V")

String comparison should use eqauls() instead of ==

Unless Strings you are comparing are String literals.

Upvotes: 4

Related Questions