列表實現應該工作正常。下面是使用一個ArrayList代碼:
String[] s1 = new String[]{"phone","smartphone","dumpphone"};
String[] s2 = new String[]{"phone","phone","smartphone"};
ArrayList<String> union = new ArrayList<>();
// Add elements of s1
for(String s : s1){ union.add(s); }
// Conditionally add elements of s2
for(String s : s2){ if(union.contains(s)){ union.add(s); } }
結果:
for(String s : union){ System.out.println(s); }
打印
phone
smartphone
dumpphone
phone
phone
smartphone
注意:你說你期待的 「電話」 只有兩個occurances。爲什麼?從你的問題陳述中看不清楚。
編輯:
按以下@ dantuch的評論,你可以改爲尋找這樣的事情:
String[] s1 = new String[]{"phone","smartphone","dumpphone"};
String[] s2 = new String[]{"phone","phone","smartphone"};
ArrayList<String> union = new ArrayList<>();
// Add elements of s2
for(String s : s2){ union.add(s); }
// Conditionally add elements of s1 (Only if they're not in s2)
for(String s : s1){ if(!union.contains(s)){ union.add(s); } }
這將打印:
phone
phone
smartphone
dumpphone
有什麼錯一個List實現?似乎很好,只要你有條件地根據你的邏輯將項目插入聯合列表。 – jedwards