java - 有没有办法将一个 ArrayList 与另一个具有一对多关系的 ArrayList 关联起来?
问题描述
我的问题是,如果我有两个名为Person和Book的类,并且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
}
我如何能够为每个人提供他们自己的书籍列表,其中的字段和方法设置类似于上面的代码?
解决方案
在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;
}
}
推荐阅读
- python - 列表多次升序 - 拆分为单个列表
- php - 使用不同方法将codeigniter变量作为变量
- css - CSS 中 calc() 的最大可用数字是多少?
- python - Python 如何在矩阵中添加标量?
- typescript - 在 TypeScript 中递归地展开对象类型
- r - R 包 OmicsPLS:如何从标准 o2m 模型计算 p1 和 p(corr) 1 值?
- javascript - 升级 ngx-translate 后声明的 Symbol TranslateDirective 中的错误
- docker - 如何创建名称中没有项目名称前缀的 docker 服务?
- node.js - 带有 node.js 服务器的 Vue.js 动态路由器 - 无法为路由提供服务
- firebase - 带有报告的 Firestore 中的成本效率和可扩展性