[英]What is the runtime of equals() in java.util.Arrays?
正如標題所述, java.util.Arrays
中equals()
的運行時是什么?
例如,如果它比較兩個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.util.Arrays中默認的運行時是什么等於()?
默認等於可能意味着Object.equals。 Arrays.equals()通常是你真正想要的。
例如,如果它比較兩個int [],它是否循環遍歷數組中的每個元素,那么O(n)?
是的,這就是消息來源所暗示的。
對於java中的所有默認equals(),我們可以假設運行時總是O(n)嗎?
對於某些集合,這是正確的,但對於Tree集合,它可以是O(n log n)。 HashMap的最壞情況是O(N ^ 2)對於非集合, n
沒有意義。
它首先檢查長度,如果相等,則遍歷所有元素並且調用等於它們。
所以,如果你想忽略個人等於的成本,是的,那就是O(n)。 但是,如果條目是字符串,例如,隨着字符串變長,它也會變長,而不僅僅是因為它們得到更多(因為比較本身也是O(m))。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.