在 Java 中删除数组中重复项的最佳方法是什么?

What is the best way to remove duplicates in an Array in Java?(在 Java 中删除数组中重复项的最佳方法是什么?)
本文介绍了在 Java 中删除数组中重复项的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个需要删除/过滤重复项的对象数组.我打算覆盖 equals &对象元素上的hachCode,然后将它们粘贴在一个集合中......但我认为我至少应该轮询stackoverflow,看看是否有其他方法,也许是其他API的一些聪明方法?

I have an Array of Objects that need the duplicates removed/filtered. I was going to just override equals & hachCode on the Object elements, and then stick them in a Set... but I figured I should at least poll stackoverflow to see if there was another way, perhaps some clever method of some other API?

推荐答案

我同意你的方法来覆盖 hashCode()equals() 并使用实现Set.

I would agree with your approach to override hashCode() and equals() and use something that implements Set.

这样做还可以让任何其他开发人员清楚地知道非重复特征是必需的.

Doing so also makes it absolutely clear to any other developers that the non-duplicate characteristic is required.

另一个原因 - 您现在可以选择最能满足您需求的实现:

Another reason - you get to choose an implementation that meets your needs best now:

  • HashSet
  • TreeSet
  • LinkedHashSet

而且您无需更改代码即可在未来更改实现.

and you don't have to change your code to change the implementation in the future.

这篇关于在 Java 中删除数组中重复项的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)