【问题标题】:Incorrect Calculation of Union and Intersection of Sets in JavaJava中集合的并集和交集计算不正确
【发布时间】:2014-08-05 22:03:21
【问题描述】:

我一直在编写在 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;
}

如果有人能提供任何关于为什么这不起作用的见解,我很想听听。提前致谢!

【问题讨论】:

    标签: java set set-intersection set-union


    【解决方案1】:

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

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

    应该够了。

    【讨论】:

    • 这是一个很好的观点!该功能是错误的,我将其替换。不幸的是,这导致我的示例输入集被处理如下:
    • 联合 = {1, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 3, 4, 5},交集 = {empty}
    • 感谢您的帮助!你还有其他建议吗?我真的不明白这是怎么回事。
    • 根据上述建议,我已经编辑了原始问题替换了 isDuplicated 函数。
    • 小心使用 contains。当且仅当存在相同的对象时,它才返回 true。请注意,在将它们添加到向量中时,您正在创建不同的对象(new Inty(0) 等等......)。我建议。当您执行两次 new Inty(0) 时,您将创建两个不同的对象,即使对象的内容在两种情况下都存储为零。如果您在引用相同的数字时尝试添加相同的对象,它将正常工作。
    猜你喜欢
    • 2011-11-26
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多