Add multiple indexes of a vector as parameter

1

I'm starting in JAVA. I created two classes, the Pessoa class, which receives the following parameters in instantiation of a new object:

public Pessoa(String nome, int idade, char sexo)

And the class Livro :

public Livro(String titulo, String autor, int totPaginas, Pessoa leitor)

And in the main class, I made the following instantiations:

Pessoa[] p = new Pessoa[2];
Livro [] l = new Livro[3];

p[0] = new Pessoa("Pedro" , 22 , 'M');
p[1] = new Pessoa("Maria" , 25 , 'F');

l[0] = new Livro("Aprendendo JAVA" , "José da Silva"    , 400 , p[0]);
l[1] = new Livro("POO em JAVA"     , "Márcio Bezerra"   , 500 , p[1]);
l[2] = new Livro("JAVA avançado"   , "Fernanda Pereira" , 900 , p[0]);

How to add multiple indexes of the Pessoa [] vector as a parameter in instantiation of a new book object, that is, how to do, for example, Pedro E Maria read the book "OOP in JAVA" without having to instantiate another identical book?

    
asked by anonymous 23.01.2017 / 16:58

1 answer

2

The relationship must be Um para Muitos

To have this relationship you need the Livro class internally to have a List of Pessoa . To do this you can create a method in Livro with name adicionarPessoa , for example, and after you instantiate the object Livro , you can add people.

l[0] = new Livro("Aprendendo JAVA" , "José da Silva"    , 400);
l[0].adicionarPessoa(p[0]);
l[0].adicionarPessoa(p[1]);

l[1] = new Livro("POO em JAVA"     , "Márcio Bezerra"   , 500);
l[1].adicionarPessoa(p[0]);

Have a question about Compositing and Aggregation here in SOpt that can help you understand these relationships.

    
23.01.2017 / 17:25