Java中联合和集合交集的计算不正确

时间:2014-08-05 22:03:22

标签: java set set-intersection set-union

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

A = {0, 1, 3, 4, 5}
B = {1, 1, 2, 3, 4, 5, 6, 7, 8}

我收到以下内容:

Union = {1, 1, 2, 3, 4, 5, 6, 7, 8}
Intersection = {0, 1, 3, 4, 5}

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

Union = {0, 1, 2, 3, 4, 5, 6, 7, 8}
Intersection = {1, 3, 4, 5}

这里是我主要关于交集/联合的代码:

    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类是不可能的。以下是我写的函数:

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;
}

如果有人能够提供任何有关为什么不起作用的见解,我很乐意听到它。提前谢谢!

1 个答案:

答案 0 :(得分:1)

isDuplicated 方法不使用参数 i !实际上我认为它总是返回 True 。用

替换函数的整个代码
return p2Shingles.contains(i)

应该足够了。