Working with List and Objects in Java

2

I have a java class called Library. with attributes: name, city, number of employees:

public class Biblioteca{
   String nome;
   String cidade;
   int qtdFuncionarios;

   //depois getters e setters e construtor...
}

And a Book class, containing: title, publisher, year.

public class Livro{
   String titulo;
   String editora;
   String ano;

   //depois getters e setters e construtor...
}

What I can not do is the following:

I need to create a library with a list of books for this library. That is, register a library and then register books for that library by saving it in a list. I can have several libraries, each containing their respective books. After saving in the list, a method that lists all books receiving the library name as parameter. Could someone help me with this?

    
asked by anonymous 22.06.2016 / 20:15

1 answer

2

Add the Book class within the library

public class Biblioteca {
   private String nome;
   private String cidade;
   private int qtdFuncionarios;
   private ArrayList<Livro> lstLivro;    
}

Then create a default constructor for the class, so you can decide if there will be a library without libraries, or if there can not be a library without libraries

public Biblioteca (String nome, String cidade, int qtdFuncionarios, ArrayList<Livro> lstLivro) {
   this.nome = nome;
   //-- resto da implementação
}

In your control you can create an ArrayList or a HashMap to control multiple libraries.

...
HashMap<string, Biblioteca> lstBiblioteca = new HashMap<>();
lstBiblioteca.put(Biblioteca.getNome(), Biblioteca);
...

or

ArrayList<Biblioteca> lstBiblioteca = new ArrayList<>()
lstBiblioteca.add(Biblioteca)

Using the ArrayList you have to make a foreach to perform the search (I do not recommend).

With HashMap you can use the .containsKey (Key) to check for existence in the hash table and retrieve the pointer with .get (Key)

I'm assuming you're loading the whole file into memory, because if you're using SQL, you'd better search for CRUD and return the dataSet to your list containing only what's needed or displaying the result if it's unique.

//-- para efetuar busca por parametro q não seja o Key do hashmap
//-- Ex.: Nome Editora
   ArrayList<Biblioteca> tmpLstBiblioteca = new ArrayList<>();
   for(Biblioteca biblioteca : lstBiblioteca.value) {
      for(Livro livro : biblioteca.getLstLivro()) {
         if(livro.getEditora().toUpper().contains(NOME_BUSCADO.toUpper())) {
            tmpLstBiblioteca.add(biblioteca);
         }
      }
   }
   return tmpLstBiblioteca;

I use the .contains (str) so that it is possible to do a partial search and the .toUpper () to have no problem with the case sensitive, it would be nice before adding the name and before searching to make the removal of spaces " .trim () "of the strings.

    
22.06.2016 / 20:28