gpt4 book ai didi

java - java.util.Arrays 中 equals() 的运行时间是多少?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:05:29 25 4
gpt4 key购买 nike

如标题所述,java.util.Arraysequals() 的运行时间是多少?

例如,如果它比较两个 int[] ,它是否循环遍历数组中的每个元素,所以 O(n)?对于 java 中各个类的 equals() 中的所有 equals(),我们可以假设运行时总是 O(n) 吗?

谢谢。

最佳答案

从源码中抓取(源码值100字:P):

/**
* Returns <tt>true</tt> if the two specified arrays of ints are
* <i>equal</i> to one another. 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. In other words, two arrays
* are equal if they contain the same elements in the same order. Also,
* two array references are considered equal if both are <tt>null</tt>.<p>
*
* @param a one array to be tested for equality
* @param a2 the other array to be tested for equality
* @return <tt>true</tt> if the two arrays are equal
*/
public static boolean equals(int[] a, int[] a2) {
if (a==a2)
return true;
if (a==null || a2==null)
return false;

int length = a.length;
if (a2.length != length)
return false;

for (int i=0; i<length; i++)
if (a[i] != a2[i])
return false;

return true;
}

关于java - java.util.Arrays 中 equals() 的运行时间是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14053347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com