Favolas
Favolas

Reputation: 7243

Java see if arraylist contains string

I have a class called Paragens like this:

public class Paragens {
    static int contadorParagens = 1;

    String nomeParagem;
    int id;

    public Paragens(String nomeParagem) {
        this.nomeParagem = nomeParagem;
        this.id = contadorParagens++;
    }

    // getters and setters for nomeParagem
}

Every Paragens object has a name and an Id.

This class has a main method where I create several Paragens objects and store them inside an ArrayList like this:

public static void main(String[] args) {
    ArrayList<Paragens> paragens = new ArrayList<Paragens>();
    paragens.add(new Paragens("name1");
    // ... add more paragens
}

This is working ok. If I insert a bunch of paragens and print them I can see tat is all ok.

What I am trying to do is to ask the user to input a paragem name and then I want to see if that paragem is already in the ArrayList.

String name;
System.out.println("Insert paragem name: ");
pickName = sc.nextLine();
System.out.println(paragens.contains(pickName));

What am I doing wrong?

Upvotes: 0

Views: 26090

Answers (3)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77485

Objects by default are compared by their memory location. So if you have two Paragem with the same name, they are still not equal.

So either, you check the name of each one:

boolean checkDuplicate(String pickName) {
    for (Paragem p : paragems) {
      if (p.nomeParagem.equals(pickName)) return true;
    }
    return false;
}

or implement (override) the equals method to compare names (you should be calling contains on a new Paragem object then instead of a String, though).

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075655

contains checks to see if the list contains the actual thing you handed it. In this case, you're passing in a String name, but comparing it to Paragem instances. contains can't magically guess that it's supposed to look at a given property on the Paragem instances to compare the string.

You can easily loop the list to find out for yourself:

boolean found = false;
for (Paragem p : paragems) {
    if (p.nomeParagem.equals(pickName)) { // Or use an accessor function for `nomeParagem` if appropriate
        found = true;
        break;
    }
}

...or as a function:

boolean containsParagemWithName(ArrayList<Paragem> paragems, String pickName) {
    for (Paragem p : paragems) {
        if (p.nomeParagem.equals(pickName)) {
            return true;
        }
    }
    return false;
}

Upvotes: 10

Igor Popov
Igor Popov

Reputation: 10101

Well, you need to implement the contains method yourself. Do a for loop over the entire array and check if the name of one of the elements is equal with what you're trying to add. If not, add a new Paragens(pickName).

Upvotes: 1

Related Questions