java有两个数组AB分别存储着字符串,AB中有相同元素,请求出AB数组中除去这部分相同的元素后的结果,请用两种方式实现。
时间: 2024-02-24 07:57:47 浏览: 17
第一种方式:使用List和Set。将数组A和数组B中的元素都添加到一个List中,然后再将List转化为Set去重,最后再转回List即可得到结果。
Java代码如下:
```
String[] A = {"a", "b", "c", "d"};
String[] B = {"c", "d", "e", "f"};
List<String> list = new ArrayList<>(Arrays.asList(A));
list.addAll(Arrays.asList(B));
Set<String> set = new HashSet<>(list);
List<String> result = new ArrayList<>(set);
System.out.println(result);
```
第二种方式:使用双重循环。将数组A中的每个元素与数组B中的每个元素比较,如果相同则将该元素从A中删除,最后将A和B合并即可得到结果。
Java代码如下:
```
String[] A = {"a", "b", "c", "d"};
String[] B = {"c", "d", "e", "f"};
List<String> list = new ArrayList<>(Arrays.asList(A));
for (String s : B) {
if (list.contains(s)) {
list.remove(s);
}
}
list.addAll(Arrays.asList(B));
System.out.println(list);
```
两种方式都可以实现去重,但第一种方式使用了额外的List和Set,相对来说更加高效。