Skip to content

Instantly share code, notes, and snippets.

@antoniopassos
Created November 6, 2012 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antoniopassos/4024620 to your computer and use it in GitHub Desktop.
Save antoniopassos/4024620 to your computer and use it in GitHub Desktop.
Código-fonte de aplicativo que ilustra post sobre encapsulamento de coleção
import java.util.ArrayList;
import java.util.List;
public class Grupo {
private String nome;
private List<Pessoa> pessoas;
public Grupo() {
super();
this.pessoas = new ArrayList<Pessoa>();
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<Pessoa> getPessoas() {
return pessoas;
}
public void setPessoas(List<Pessoa> pessoas) {
this.pessoas = pessoas;
}
}
public class Pessoa {
private String nome;
private String sobrenome;
public Pessoa() {
super();
}
public Pessoa(String nome, String sobrenome) {
super();
this.nome = nome;
this.sobrenome = sobrenome;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSobrenome() {
return sobrenome;
}
public void setSobrenome(String sobrenome) {
this.sobrenome = sobrenome;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result
+ ((sobrenome == null) ? 0 : sobrenome.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pessoa other = (Pessoa) obj;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
if (sobrenome == null) {
if (other.sobrenome != null)
return false;
} else if (!sobrenome.equals(other.sobrenome))
return false;
return true;
}
@Override
public String toString() {
return nome + " " + sobrenome;
}
}
import java.util.ArrayList;
import java.util.List;
public class Principal {
public static void main(String[] args) {
Grupo grupo = new Grupo();
grupo.setNome("Escritores brasileiros");
List<Pessoa> lstPessoas = new ArrayList<Pessoa>();
lstPessoas.add(new Pessoa("Álvares", "Azevedo"));
lstPessoas.add(new Pessoa("Casimiro", "Abreu"));
grupo.setPessoas(lstPessoas);
Pessoa p1 = new Pessoa("Junqueira", "Freire");
grupo.getPessoas().add(p1);
grupo.getPessoas().add(new Pessoa("Fagundes", "Varela"));
for (Pessoa pessoa : grupo.getPessoas()) {
System.out.println(pessoa);
}
grupo.getPessoas().remove(p1);
grupo.getPessoas().remove(new Pessoa("Álvares", "Azevedo"));
for (Pessoa pessoa : grupo.getPessoas()) {
System.out.println(pessoa);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment