2013-03-31 23 views
0
s1={"phone","smartphone","dumpphone"} (all string elements in s1 are unique) 
s2={"phone","phone","smartphone"} 

(S2中字符串元素可以被複制,但在s2中必須將每個元素屬於S1,即S2不能包含不s1中存在的字符串。例如,S2不能包含「手持式」,因爲S1確實不包含「」手持式「」)如何結合2字符串數組,但在Java中保持重複?

s2 union s1={"phone","phone", "smartphone","dumpphone"} 

設置&的HashSet不允許重複

我試圖名單,但它並沒有幫助。

你知道如何解決?

+2

有什麼錯一個List實現?似乎很好,只要你有條件地根據你的邏輯將項目插入聯合列表。 – jedwards

回答

1

列表實現應該工作正常。下面是使用一個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 
+1

海事組織他希望's2'追加's1',這些不是's2'。這就是他預期的產出告訴我:) – dantuch

+1

@dantuch,我想你可能是正確的 - 更新我的答案 – jedwards

+0

很酷,很抱歉,這是糾正解決方案 – Tom

相關問題