1

I am having trouble with this method of my class. It always returns false. Passenger is a separate class. This is a method in my Train class which creates an array list of Passenger objects. I am making a method that will search the ArrayList passengerList for a Passanger object with the name as the parameter.

public boolean search(String a){
    Passenger temp;
    boolean query = false;
    for (int i =0; i<passengerList.size(); i++)
    {
        temp=passengerList.get(i);
        if (temp.getName() == a)
        {
            query = true;
        }
    }
    return query;
}

3 Answers 3

4
 if (temp.getName() == a)

should be

 if (temp.getName().equals(a))

String comparison should always use equals() method instead of == (except that strings literals).

if temp.getName() and a both not pointing to same object, == condition will fail.

== checks for references equality. equals() checks for content equality.

This tutorial may help you.

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

1 Comment

Thanks for helping the link you gave me explained a lot!
2

if (temp.getName() == a) should be if (temp.getName().equals(a)).

The former compares references for equality. The latter actually checks to see if the string values are equal.

Comments

0

I would suggest writing this code more elegant and cleaner (with checking for null):

public boolean search(String a){  
    boolean query = false;
    for (Passenger temp : passengerList)
    {
        if (temp != null && temp.getName()!=null && temp.getName().equals(a))
        {
            query = true;
        }
    }
    return query;
}

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.