My question is that if I have two classes named Person and Book and with an ArrayList in each class, the Person List having a list of people and the Book having a list of books. Is it possible to make it so that each Person can have a different list of Books?

Say that I have a Person Class as such:

List<Person> person = new ArrayList<>();

Person(int name, int lastName, int age){
   //initialize variables

And a Book Class as such:

List<Book> book = newArrayList<>();

Book(int id, int title, int authorLastName){
   //initialize variables

How would I be able to give each Person their own list of Books with the fields and methods set like the above code?

3 Answers

Community On

You can make the Person class take List<Book> that way each person can have their own list of books.

Person(int name, int lastName, int age, List<Book> books){
   //initialize variables
Deadpool On

In the Person class instead of List<Book> use Map<Person,List<Book>>, so that each person will have list of books. For that you need to override the equals() and hashCode() method in person class so that you can maintain unique Person objects as keys in Map


public class Person   { 

    private String name; 
    private String lastName;
    private int age
    // getters, setters , no arg and all arg constructor   

    public boolean equals(Object obj) 
        if(this == obj) 
            return true; 

        if(obj == null || obj.getClass()!= this.getClass()) 
            return false; 

        // type casting of the argument.  
        Person per = (Person) obj; 
          // check conditions based on requirement 
        return (  && per.age == this.age); 
    public int hashCode() 
         // generate hashcode based on properties so that same person will have same hashcode
         return this.age; 
JJovel On

Try using a Map object instead of 2 ArrayLists. For example, you could have a Map object that associates Strings with integers, which would be initialized as follows: new Map<Integer, String>() Note that the first data type is the key and the second is the the type of the mapped values. You can find more information by consulting the Java API.