gpt4 book ai didi

java - 查找两个 ArrayList 之间的交集

转载 作者:行者123 更新时间:2023-12-01 22:40:31 25 4
gpt4 key购买 nike

查找两个字符串 ArrayList 的交集。

这是代码:

public ArrayList<String> intersection( ArrayList<String> AL1, ArrayList<String> AL2){   
ArrayList<String> empty = new ArrayList<String>();
ArrayList<String> empty1 = new ArrayList<String>();
if (AL1.isEmpty()){
return AL1;
}
else{
String s = AL1.get(0);
if(AL2.contains(s))
empty.add(s);


empty1.addAll(AL1.subList(1, AL1.size()));
empty.addAll(intersection(empty1, AL2));
return empty;
}
}

我希望输出如下所示:例如,

 [a, b, c] intersect [b, c, d, e] = [b, c]

上面的代码给了我这个输出,但我想知道如何使这个代码更容易理解。

最佳答案

你可以这样写,这样更容易理解:

/**
* Computes the intersection of two Lists of Strings, returning it as a new ArrayList of Strings
*
* @param list1 one of the Lists from which to compute an intersection
* @param list2 one of the Lists from which to compute an intersection
*
* @return a new ArrayList of Strings containing the intersection of list1 and list2
*/
public ArrayList<String> intersection( List<String> list1, List<String> list2) {
ArrayList<String> result = new ArrayList<String>(list1);

result.retainAll(list2);

return result;
}

关于java - 查找两个 ArrayList 之间的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26222864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com