如何计算两个数组中相等值的数量? [英] How to count the number of equal values in two arrays?

查看:86
本文介绍了如何计算两个数组中相等值的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

int[] a = [0,1,2,3,4,5];
int[] b = [3,4,5,6,7,8];

count = 3;

数组不必是连续的数字。
如何获得这些数组之间相等的值数量?

The arrays do not have to be consecutive numbers. How would I get the number of values that equal between these arrays?

编辑:因此,我尝试了以下操作:

edit: So I've attempted the following:

List<int[]> w = Arrays.asList(winning);
List<int[]> s = Arrays.asList(F1Select);            
w.retainAll(s);
int equalNums = w.size();

但是我在retainAll行中遇到以下错误:

But I'm getting the following error for the retainAll line:

Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(Unknown Source)
    at java.util.AbstractList$Itr.remove(Unknown Source)
    at java.util.AbstractCollection.retainAll(Unknown Source)


推荐答案

您可以转换为列表,然后使用retainAll查找交点。

You can just convert to lists, and find the intersection using retainAll.

List<Integer> aList =  Arrays.asList(a);
List<Integer> bList =  Arrays.asList(b);
aList.retainAll(bList);
return aList.size();

aList然后将仅包含也在bList中的项目,并且aList的大小可让您知道

aList will then only contain items that are also in bList, and the size of aList lets you know the count.

如果只需要唯一值,则可以将数组转换为 Set 并执行相同的操作。

If you want only unique values you could convert the arrays to a Set and do the same thing.

这篇关于如何计算两个数组中相等值的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆