首页 > 解决方案 > 有没有办法将一个 ArrayList 与另一个具有一对多关系的 ArrayList 关联起来?

问题描述

我的问题是,如果我有两个名为PersonBook的类,并且ArrayList每个类中都有一个,那么Person List有一个人员列表,而Book有一个书籍列表。是否有可能使每个都可以拥有不同的书籍列表?

假设我有一个Person类:

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

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

和这样的类:

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

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

我如何能够为每个提供他们自己的书籍列表,其中的字段和方法设置类似于上面的代码?

标签: javaobjectarraylist

解决方案


Person课堂上代替List<Book>使用Map<Person,List<Book>>,这样每个人都会有书单。为此,您需要覆盖 person 类中的equals()andhashCode()方法,以便您可以将唯一的Person对象作为键来维护Map

public class Person   { 

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

    @Override
    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.name.equals(this.name)  && per.age == this.age); 
    } 
    @Override
    public int hashCode() 
    { 
         // generate hashcode based on properties so that same person will have same hashcode
         return this.age; 
     }  
} 

推荐阅读