试图匹配两个&#34; ArrayList <point>&#34; </point>

时间:2015-04-18 20:49:31

标签: java arraylist point

我试图找到两个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;

2 个答案:

答案 0 :(得分:1)

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

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 second可能要快得多1}}:

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

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

  

仅保留此集合中包含的元素   指定集合(可选操作)。

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

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.

答案 1 :(得分:0)

您可以使用intersection

中的org.apache.commons.collections.CollectionUtils方法
int intersectionSize = CollectionUtils.intersection(firstInter, secondInter).size();

至于“百分比”,问题是什么的百分比?工会 ?无论哪种方式都应该不难,你可以这样做:

return 100 * intersectionSize / (firstInter.size() + secondInter.size());