Java - String - Comparison [duplicate]

1

I'm not understanding a simple comparison I'm making, but it's not running as I think it should.

Situation

I ask the user to enter the name of the person, and capture with String nome = scan.next();

And sending to this function:

// FIND PESSOA
private boolean findPessoaInList(String nome){
    Boolean _return = false;
    for(Pessoa p : this.pessoas){
        if(p.getNome() == nome){
            _return = true;
            // return true;
        }
    }
    return _return;
}

To check if the person is already registered.
However, it never falls within if even if the name already exists in the list.

Code getNome in Pessoa

public String getNome() {
    return nome;
} 

If someone can explain to me what's happening, thank you.

    
asked by anonymous 28.06.2015 / 00:30

1 answer

3

If you use == it will compare with memory addresses, if you want to compare only the values use .equals() . Another attention is in case sensetive , if you type some lower case letter and use equals , the other one will give false , to avoid it use equalsIgnoreCase()

String nomeMinusculo = "maicon";
String nome = "Maicon";

System.out.println(nomeMinusculo == nome); // false
System.out.println(nomeMinusculo.toUpperCase() == nome.toUpperCase()); // false
System.out.println(nomeMinusculo.equals(nome)); // false
System.out.println(nomeMinusculo.toUpperCase().equals(nome.toUpperCase())); // true

/* Sugerido pelo Filipe Gonzaga */
System.out.println(nomeMinusculo.equalsIgnoreCase(nome)); // true

Ideone Example

In your case

// FIND PESSOA
private boolean findPessoaInList(String nome){

    // remover espaços a direita e esquerda
    nome = (nome == null) ? "" : nome.trim();

    Boolean _return = false;
    for(Pessoa p : this.pessoas){
        if(p.getNome().equalsIgnoreCase(nome)){
            _return = true;
            // return true;
        }
    }
    return _return;
}
    
28.06.2015 / 00:36