[英]Identifying the class of data entries in a Linked List in 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");
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.