java - 比较两个字符串数组而不通过每个元素进行索引的最佳方法是什么?

标签 java arrays string arraylist string-comparison

是否有任何有效的方法可以用来比较两个字符串数组而不检查每个元素?

我尝试使用数组列表、构建对象,但没有一个没有显示出太大的效果。

最佳答案

最后,要比较两个字符串“序列”(代表字符序列),没有任何提高效率的技巧。

您必须以某种方式遍历两个序列并逐个元素地比较它们。

从这个意义上来说,你唯一可以努力的就是:“高效”的编码风格;换句话说:专注于编写人类可读的代码。

当然,现有的库调用 Arrays.equals() 将是您的第一站。除此之外:您可以非常确定,您自己写下的任何内容都不会比标准内置解决方案执行“更好”。

除此之外:请记住,决定之间存在差异:两个大小相等的数组是否具有相同的元素?或者它们的元素顺序是否完全相同

换句话说; 必须澄清 [A, B] 是否等于 [B, A] - 以确定是否 Array.equals()

Returns true if the two specified arrays of Objects are equal to one another. The two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. Two objects e1 and e2 are considered equal if (e1==null ? e2==null : e1.equals(e2)). In other words, the two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.

这正是您所需要的!

如果顺序对您来说重要,您首先必须对两个数组进行排序 - 因为这会将两个数组内容置于相同的顺序。

最后的想法:从性能角度来看,这里使用数组和 ArrayList 之间应该没有(太大)差异。在我的回答中,我们发现您可以通过输入 listA.equals(listB) (这将为您提供 Arrays.equals() 语义)来更轻松地与列表进行比较。

唯一可能真正影响性能的方面是:当您的用例允许使用集合时......

关于java - 比较两个字符串数组而不通过每个元素进行索引的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44001850/

相关文章:

java - 使用 ResponseBody 并返回 Model 类实例的 Controller 方法上的奇怪 Spring MVC 4.2.x 行为

java - 匿名方法使用泛型值作为参数

java - 万磁王 : Adding configurable product to cart fails : Please specify the product's option(s)

javascript - 将 JavaScript 数组中的项目放在任意索引上

arrays - Go:循环排序数组,sort.Sort用作值

java - 使用 JAXB 的编码对象不正确的标签名称

C# 检查对象数组是否重复

C# Byte[] 字节数组到 Unicode 字符串

json - 是否可以在Go中添加嵌套的json "as is"?

python - 如何在 Maya 中使用 Def Function 字符串