Last active
May 23, 2016 15:34
-
-
Save magostinhojr/308c20161b6091f3ea26eacd5cde14b3 to your computer and use it in GitHub Desktop.
Codigo exemplo para demonstrar comparação de Objeto e problema ao tentar comparar primitivo e null.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* * Class Principal */ | |
public class Test { | |
public void test(){ | |
Usuario usuario = new Usuario(); | |
usuario.setNome("Ian Nagot"); | |
validadeIdadeNull(usuario); | |
} | |
private void validaIdadeNull(Usuario usuario){ | |
if(usuario.getIdade == null){ //Compara usando Wrapper | |
System.out.println("Idade vazia"); | |
} | |
if(usuario.getIdadePrimitivo == null){ //Compara usando Primitivo | |
System.out.print("Idade vazia") //Esse bloco nem compila pois estamos tentando comparar um primitivo com Null | |
} //Não são comparaveis... null pertence ao universo dos Objetos diriamos assim | |
} | |
} | |
/* | |
* Classe que representa um usuario no Sistema. | |
*/ | |
public class Usuario{ | |
private String nome; | |
private Integer idade; | |
public String getNome(){ | |
return nome; | |
} | |
public void setNome(String nome){ | |
this.nome = nome; | |
} | |
public Integer getIdade(){ | |
return idade; | |
} | |
public void setIdade(Integer idade){ | |
this.idade. = idade; | |
} | |
public int getIdadePrimitivo(){ | |
return idade.intValue(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment