[英]How to check equal Names in String Array in Java?
我有一個名字的數組( temp3
)。
我需要確定是否有任何名稱等於數組中的另一個名稱,而不重復比較。
到目前為止,這就是我所擁有的,謝謝。
for(int m=0; m<3; m++){
for(int n=0; n<3; n++){
if(m!=n){
if(temp3[m]==temp3[n]){
System.out.println("Yes");
}
}
}
}
for(int i=0; i< strings.length;i++){ // Pick a string
for(int j=i+1; j<strings.length;j++){ // Loop on all strings starting from i+1
if(strings[i].equals(strings[j])) // check if the two strings are equal
System.out.println("The two strings are the same"); // SOP
}
}
}
這是一個更快的解決方案。 我們不重復任何比較,我們會自動避免將字符串與自身進行比較。
for (int i=0; i< strings.length;i++) {
for (int j= i + 1; j<strings.length;j++) {
if (strings[i].equals(strings[j]))
System.out.println("The two strings are the same");
}
}
您也可以使用Set
沒有任何顯式循環的情況下執行此操作:
if (temp3.length != new HashSet<String>(Arrays.asList(temp3)).size()) {
System.out.println("Yes");
}
這是通過檢查最終的Set
是否與數組具有相同的條目數來實現的。 如果沒有,那么肯定有重復。 (這實際上是鴿籠原理的一個例子。我發現這種簡單的演繹需要一個特殊的名字,這很有趣!)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.