【问题标题】:Is there a way to associate an ArrayList with another ArrayList with a one to many relationship?有没有办法将一个 ArrayList 与另一个具有一对多关系的 ArrayList 关联起来?
【发布时间】:2019-09-29 11:07:07
【问题描述】:

我的问题是,如果我有两个名为 PersonBook 的班级,并且每个班级都有一个 ArrayList,那么 Person @ 987654322@ 有一个人员列表,Book 有一个书籍列表。是否可以让每个Person拥有不同的Books列表?

假设我有一个 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
}

我怎样才能给每个Person他们自己的Books列表,其中的字段和方法设置与上面的代码类似?

【问题讨论】:

  • 为什么 Person 类会保存一个 Person 对象列表(Book 类也是如此)?

标签: java object arraylist


【解决方案1】:

Person 类中而不是List&lt;Book&gt; 使用Map&lt;Person,List&lt;Book&gt;&gt;,这样每个人都会有书籍列表。为此,您需要覆盖 person 类中的 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; 
     }  
} 

【讨论】:

    【解决方案2】:

    您可以让 Person 类采用 List&lt;Book&gt;,这样每个人都可以拥有自己的书籍列表。

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

    【讨论】:

      【解决方案3】:

      尝试使用 Map 对象而不是 2 个 ArrayList。例如,您可以有一个 Map 对象,它将字符串与整数相关联,其初始化如下: new Map&lt;Integer, String&gt;() 请注意,第一个数据类型是键,第二个是映射值的类型。您可以通过查阅 Java API 找到更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-07
        • 2021-01-27
        • 2011-07-25
        • 2013-10-22
        • 1970-01-01
        • 1970-01-01
        • 2012-03-28
        相关资源
        最近更新 更多