从列表中删除唯一记录
我有一个员工列表。我的员工类别如下
public class Employee{
int empid;
String name;
...
}
,现在我想从列表中删除 empid 为 5 的员工。一种方法是迭代列表并检查 empid == 5。是否还有其他方法我能做到吗?
还希望我的列表包含具有唯一 empid 的员工。任何添加具有重复 empid 的员工的尝试都应该抛出异常。如何做到这一点?
i have a list of employees.My employee class is as follows
public class Employee{
int empid;
String name;
...
}
now i want to remove a employee from list whose empid is 5.One way to do is to iterate the list and check if empid == 5.Is there any other way by which i can do it?
Also is want my list to contain employees with unique empid.Any attempt made to add employees with duplicate empid should throw an exception.How to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
而不是
List< Employee>
,使用Set<员工>
。不要忘记重写 Employee 类的
hashCode()
和equals()
方法。Instead of
List< Employee>
, useSet< Employee>
.Don't forget to override
hashCode()
andequals()
methods of your Employee class.如果员工的顺序相关(或者如果您需要能够让一名员工多次出现),则需要将它们存储在列表中。 (否则 Set 就足够了。)
我会让
Employee
重写equals
方法并使用List.remove(Object o)
。来自 List 的 API 文档:
具体来说,你可以这样做
If the order of the employees is of relevance (or if you need to be able to let one employee be represented multiple times) you need to store them in a list. (Otherwise a Set would suffice.)
I would let
Employee
override theequals
method and useList.remove(Object o)
.From the API docs of List:
Concretely, you could do something like
对于问题的第一部分,您可以调用remove(),传入一个 Employee 对象,该对象的 equals() 方法对于 id 5 的 Employee 返回 true。
对于第二部分,而不是
List
,Set
保证没有任何重复项。你的收藏有必要是一个列表吗?For the first part to your question, you can call remove() passing in an Employee object whose equals() method returns true for an Employee of id 5.
For your second part, instead of a
List
, aSet
guarantees not to have any duplicates. Is it necessary for your collection to be a list?