"-6ren"> "-我试图找出两个 ArrayList 中有多少个元素的百分比比赛,但我已经走进了死胡同。有人可以帮忙吗? 这是我尝试做的,我不知道它是否正确或适用: int i; int count = 0; Arra-6ren">
gpt4 book ai didi

java - 尝试匹配两个 "ArrayList "

转载 作者:行者123 更新时间:2023-12-01 11:38:50 25 4
gpt4 key购买 nike

我试图找出两个 ArrayList<Point> 中有多少个元素的百分比比赛,但我已经走进了死胡同。有人可以帮忙吗?

这是我尝试做的,我不知道它是否正确或适用:

int i;
int count = 0;

ArrayList<Point> firstInter= array1; // output from other class
ArrayList<Point> secondInter = array2; //output from other class
int size= firstInter.size(); //they have the same size

for (i = 0; i < size; i++) {
if (firstInter.get(i) == secondInter.get(i)) {
count1++;
}
}

double percentage1 = count / size;

最佳答案

您需要找到两个列表的交集。详细说明:第一个列表中也包含在第二个列表中的元素数量:

List<Point> first = ...;
List<Point> second = ...;
int count = 0;

for (Point p : first) {
if (second.contains(p)) count++;
}

// assuming, first and second have equal size
double percentage = (double)count / first.size();

Set 中,收容行动的效率要高得多。比List,所以如果你有很多元素,使用Set进行第二可能会快得多:

Set<Point> second = new HashSet<Point>(secondList);

幸运的是,Set 已经提供了执行交集操作的方法:Set.retainAll(Collection other)Java API Docs :

Retains only the elements in this set that are contained in the specified collection (optional operation).

因此,要获取两个集合的交集,我们可以简单地使用以下方法:

Collection<Point> first = ...; // should be a Set for maximum performance
Set<Point> second = new HashSet<Point>(...);

second.retainAll(first);

// assuming, both point lists have equal size
double percentage = (double)count / first.size();

注意:只有当 Point 类正确覆盖 equalshashcode 时,所有这些代码才有效。请参阅https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java.

关于java - 尝试匹配两个 "ArrayList<Point> ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29722684/

25 4 0