在 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())});

输出是"class 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");
}
});

最新更新