java - 在 Java 中识别链表中的数据条目类别
问题描述
我有一个填充的链接列表,其中包含 2 种类型的对象;工作和代理。
如何遍历链接列表并识别条目的类?
链接列表看起来像这样
LinkedList pool =
[[Agent{id='100', name='John'}],
[Job{id='1', type='rewards', urgent='false'}],
[Agent{id='101', name='Smith'}],
[Job{id='2', type='bills', urgent='false'}],
[Job{id='3', type='bills', urgent='true'}]]
我当前使用的方法返回一个简单的答案 - 该类是 LinkedList
pool.forEach( temp -> {System.out.println(temp.getClass())});
输出是“类 java.util.LinkedList”
Agent agent1 = new Agent();
Job job1 = new Job();
...
LinkedList pool = new LinkedList();
pool.add(agent1);
pool.add(job1);
pool.add(agent2);
pool.add(job2);
pool.add(job3);
pool.forEach( temp -> {
// Pseudo Code for the desired result should be as such
// if (temp.getClass = Agent) {System.out.println("Agent")}
// else if (temp.getClass = Job) {System.out.println("Job")}
});
预期结果在上面代码的注释中描述。
谢谢!
解决方案
您应该使用 instanceof 运算符。如果对象属于该类,则返回 true。
pool.forEach( temp -> {
if(temp instanceof Agent) {
System.out.println("Agent");
}
else if(temp instanceof Job) {
System.out.println("Job");
}
});
推荐阅读
- pandas - 新列中的组计数
- excel - How can I convert a number in a cell to time format when sending this cell via email?
- php - PHP 打印 - 调用未定义的函数 printer_list()
- electron - 为什么 Electron-Angular 项目在构建时会出现 GL ERROR
- node.js - 使用 nodejs 包装时,Cypress.io 找不到规范
- javascript - 如何在数组中对数组的第二个值进行排序?
- c# - 语音识别语义解释 UWP
- javascript - 将 2D SDF 函数转换为 JavaScript
- php - 如何将 Varnish ESI 与模块化 PHP 模板系统一起使用
- ios - 经常重新计算路线的问题