0
s1={"phone","smartphone","dumpphone"} (all string elements in s1 are unique)
s2={"phone","phone","smartphone"}

(s2中的字符串元素可以重复,但s2中的每个元素都必须属于s1,即s2不能包含s1中不存在的字符串。例如s2不能包含“handheld”,因为s1中不包含“”handheld "")

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

Set & HashSet 不允许重复

我尝试了 List 但它没有帮助。

你知道怎么解决吗?

4

1 回答 1

1

A List implementation should work fine. Here's your code using an 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); } }

Results:

for(String s : union){ System.out.println(s); }

Prints

phone
smartphone
dumpphone
phone
phone
smartphone

Note: You say that you're expecting only two occurances of "phone". Why? From your problem statement it's not clear.

EDIT:

As per @dantuch's comment below, you may be looking for something like this instead:

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); } }

Which would print:

phone
phone
smartphone
dumpphone
于 2013-03-31T08:47:18.613 回答