首页 > 解决方案 > 在 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")}
});

预期结果在上面代码的注释中描述。

谢谢!

标签: javaarrayslinked-list

解决方案


您应该使用 instanceof 运算符。如果对象属于该类,则返回 true。

pool.forEach( temp -> {
     if(temp instanceof Agent) {
        System.out.println("Agent");
     }
     else if(temp instanceof Job) {
        System.out.println("Job");
     }
});

推荐阅读