集合-ArrayList
我有一个数组列表,它包含一个 100 个员工对象,每个对象包含“姓名”和“薪水”。我们需要从对象中找到最高薪水的员工。请让我知道方法是什么。
我想到了实现compareTo和equals方法是否正确,并且还使用Collections.sort这是正确的方法还是有其他方法
I have a arraylist and it contains a 100 employee object and each object contains "Name" and "Salary". We need to find the Max salaried employeee from the Object .Please let me know what is the way .
I thought of implementing compareTo and equals Method is it right , and also using Collections.sort Is it the right way or is there any other way
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果语言是 Java,则实现 Comparable接口(只需
compareTo
——不需要equals
)并调用Collections.sort(arraylist)
,或者编写一个 Comparator 并调用Collections.sort(数组列表,比较器)
。后者更灵活,因为它不需要您的对象始终按工资排序。If the language is Java, then either implement the Comparable interface (just
compareTo
--no need forequals
) for the objects in the array list and callCollections.sort(arraylist)
, or else write a Comparator and callCollections.sort(arraylist, comparator)
. The latter is more flexible, as it doesn't require your objects to always be sorted by salary.您无需自己进行排序。您的情况非常适合优先队列。按照@Ted的建议编写一个比较器并将数据添加到 PriorityQueue - 它会根据您想要的最小/最大工资数据为您提供最小值或最大值 - 在您的情况下。这篇文章的详细信息:
如何使用 PriorityQueue?
You need not do the sorting yourself. Your case is perfect for priority queues. Write a comparator as @Ted suggested and add the data to PriorityQueue - it'll give you the min or max based on the data you want the min/max of - salary in your case. Details in this post:
How do I use a PriorityQueue?