2017-03-08 100 views
-7

我有2個數組列表。我想返回兩者之間的唯一值。這是如何完成的?遍歷並比較2個數組列表並找到匹配項

String[] s1 = {10, 1}; 
String[] s2 = {10, 1, 13}; 

//loop through and compare element of s1 to s2  
//switch varialbe used to indicate whether a match was found 
boolean matchFound = false; 

//outer loop for all the elements in s2 
for (int i = 0; i < s2.lenght; i++) { 
    //inner loop for all the elements in s1 
    for (int i = 0; i < s1.lenght; i++) { 
    matchFound = true; 
    System.out.println("This " + s2[i] + "was found"); 
    } 
} 
if(matchFound == false) { 
    System.out.println("This " + s2[i] + "was not found"); 
} 
//set matchFound bool back to false 
matchFound = false; 
} 
+2

像'10'和'1'這樣的文字是**不** **字符串文字 – QBrute

+4

您的代碼不能編譯。如果你把整數改成字符串('「10」'vs'10'),這工作得很好。 – tnw

+0

對不起,我沒有包括整個代碼。這些字符串是從我的servlet傳遞過來的,我將它傳遞給DAO。我更新我的代碼。 – Gee

回答

0

我用正確的答案更新了我的問題。

0

如果你的數組沒有重複的值,或者你只對沒有出現的元素感興趣,那麼你可以使用Set。

轉換陣列兩組:

Set<T> one = new HashSet<T>(Arrays.asList(s1));

Set<T> two = = new HashSet<T>(Arrays.asList(s2));

one.removeAll(secondSet);

two.removeAll(firstSet);

如果兩個集都是空的,那麼兩個集都是相等的,否則每個集都有唯一的元素。

相關問題