0
I’ve tried to come up with a simpler example, so I have a person who has a list of cars. If I have a C1 car, how will I know who it belongs to?
public class Pessoa {
private String nome;
private ListaCarros carros;
public Pessoa(String nome, ListaCarros carros) {
this.nome = nome;
this.carros = carros;
}
}
public class ListaCarros {
private HashMap<String, Carro> listaCarros;
public ListaCarros() {
listaCarros = new HashMap<>();
}
public void adicionar(Carro carro) {
listaCarros.put(carro.getMatricula(), carro);
}
}
public class Carro {
private String matricula;
public Carro(String matricula) {
this.matricula = matricula;
}
public String getMatricula() {
return matricula;
}
}
public class Teste{
public static void main(String[] args){
Carro c1 = new Carro("00-AA-00");
Carro c2 = new Carro("99-AA-99");
ListaCarros l1 = new ListaCarros();
l1.adicionar(c2);
l1.adicionar(c1);
Pessoa p1 = new Pessoa("Afonso", l1);
//Como poderei fazer isto?
//c1.getPessoa().getNome();
}
}
How can I get the owner’s name?
The only solution will be to put one more parameter with the name of the parent?
Somehow you would have to have a reference to the Person inside the Car object, for him to know who the "father" is. There is no built-in mechanism in language to know who holds a reference to an object, and even if there was, there could be more than one "father", there could be a reference in a local variable, etc. I also suggest abolishing the List Car class and incorporating its functionality into the Person class, so that the method itself adds() already assigns Person to the Car.
– epx