首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java中集合的并与交的错误计算

Java中集合的并与交的错误计算
EN

Stack Overflow用户
提问于 2014-08-05 22:03:21
回答 1查看 79关注 0票数 0

我一直在编写函数,这些函数可以在Java中找到两个集合的联合和交集,但是我的算法在某个地方似乎有问题。例如,当我输入以下两个数字向量时:

代码语言:javascript
复制
A = {0, 1, 3, 4, 5}
B = {1, 1, 2, 3, 4, 5, 6, 7, 8}

我收到以下消息:

代码语言:javascript
复制
Union = {1, 1, 2, 3, 4, 5, 6, 7, 8}
Intersection = {0, 1, 3, 4, 5}

这显然是不正确的。我应该收到:

代码语言:javascript
复制
Union = {0, 1, 2, 3, 4, 5, 6, 7, 8}
Intersection = {1, 3, 4, 5}

下面是我的主代码中关于交叉口/联合的代码:

代码语言:javascript
复制
    Vector<Inty> p1Shingles = new Vector<Inty>();
    p1Shingles.add(new Inty(0));
    p1Shingles.add(new Inty(1));
    p1Shingles.add(new Inty(3));
    p1Shingles.add(new Inty(4));
    p1Shingles.add(new Inty(5));

    Vector<Inty> p2Shingles = new Vector<Inty>();
    p2Shingles.add(new Inty(1));
    p2Shingles.add(new Inty(1));
    p2Shingles.add(new Inty(2));
    p2Shingles.add(new Inty(3));
    p2Shingles.add(new Inty(4));
    p2Shingles.add(new Inty(5));
    p2Shingles.add(new Inty(6));
    p2Shingles.add(new Inty(7));
    p2Shingles.add(new Inty(8));        

    Vector<Inty> shinglesUnion = vectorUnion(p1Shingles, p2Shingles);
    Vector<Inty> shinglesIntersection = vectorIntersection(p1Shingles, p2Shingles);

这里,Inty是我创建的一个类,这样我就可以更改我需要存储在向量中的整数的值,这在Integer类中是不可能的。下面是我编写的函数:

代码语言:javascript
复制
private static <T> Vector<T> vectorIntersection(Vector<T> p1Shingles, Vector<T> p2Shingles)
{
    Vector<T> intersection = new Vector<T>();

    for(T i : p1Shingles)
    {
        if(p2Shingles.contains(i))
        {
            intersection.add(i);
        }
    }

    return intersection;
}

private static <T> Vector<T> vectorUnion(Vector<T> p1Shingles, Vector<T> p2Shingles) {
    Vector<T> union = new Vector<T>();

    union.addAll(p2Shingles);

    for(T i : p1Shingles)
    {
        if(!p2Shingles.contains(i))
        {
            union.add(i);
        }
    }

    return union;
}

如果有人能深入了解为什么这不起作用的话,我很想听听。提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-05 22:20:30

方法isDuplicated不使用参数i!实际上,我认为它总是返回True。将函数的整个代码替换为

代码语言:javascript
复制
return p2Shingles.contains(i)

应该就够了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25149087

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档