java 在 LinkedList 中查找元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/814082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding element in LinkedList
提问by user69514
If I have an LinkedList of Employee objects...
如果我有一个 Employee 对象的 LinkedList ......
Each employee has a Name, and an ID fields.
每个员工都有一个姓名和一个 ID 字段。
I have linkedList call list....
我有链接列表调用列表....
If I want to see if the list contains an employee I do:
如果我想查看列表中是否包含一名员工,我会这样做:
list.contains(someEmployeeObject)
How about if I want to see if the the list contains an employee based on the imployee ID..
如果我想查看列表中是否包含基于员工 ID 的员工,那如何呢?
let's say I have the following method:
假设我有以下方法:
public boolean containsEmployeeByID(int id)
How can I know if the list contains the employee object with the parameter id?
我如何知道列表是否包含带有参数 id 的员工对象?
回答by Chris Dolan
Just walk the list and look for matches. If you do this often and change the list infreqently, build a Map index first.
只需遍历列表并寻找匹配项。如果您经常这样做并且不经常更改列表,请先构建一个 Map 索引。
List<Employee> list = ...
for (Employee e : list)
if (e.getID() == id)
return true;
return false;
That said, saving employees in a LinkedList?? What a strange example problem...
也就是说,将员工保存在 LinkedList 中?多么奇怪的示例问题...
回答by Joe Phillips
Maybe you should be using a map with the key being an ID and value being the employee name or the employee object?
也许您应该使用键为 ID、值为员工姓名或员工对象的映射?
回答by zmf
You could override your equals() method to compare based on Id, however this typically is not a best practice.
您可以覆盖您的 equals() 方法以根据 Id 进行比较,但这通常不是最佳实践。
Another option is to create a HashMap and then you can retrieve your employees by their Id.
另一种选择是创建一个 HashMap,然后您可以通过他们的 ID 检索您的员工。
for (Employee empl : list) {
map.put(empl.getId(), empl);
}
String idLookup = "1234";
Employee employee = map.get(idLookup);

