有没有一种方法可以将ArrayList与具有一对多关系的另一个ArrayList相关联?

时间:2019-05-12 04:30:38

标签: java object arraylist

我的问题是,如果我有两个名为 Person Book 的班级,并且每个班级中都有一个ArrayList,则 Person > List具有人员列表,而 Book 具有书籍列表。是否可以使每个人员拥有不同的图书列表?

说我有一个这样的 Person 类:

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

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

和一个 Book 类:

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

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

我如何能够给每个人员他们自己的书籍列表,并设置与上述代码类似的字段和方法?

3 个答案:

答案 0 :(得分:2)

Person类而不是List<Book>中使用Map<Person,List<Book>>,以便每个人都有书籍列表。为此,您需要在人员类中覆盖equals()hashCode()方法,以便可以维护唯一的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; 
     }  
} 

答案 1 :(得分:0)

您可以使Person类采用List<Book>,这样每个人都可以拥有自己的书籍清单。

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

答案 2 :(得分:0)

尝试使用Map对象而不是2个ArrayList。例如,您可能有一个Map对象,该对象将Strings与整数相关联,并将其初始化如下: new Map<Integer, String>() 请注意,第一种数据类型是键,第二种是映射值的类型。您可以通过查询Java API找到更多信息。

相关问题