简体   繁体   中英

What is the bug in this code

I was reading on the importance of testing and as an example this code appeared:

public Scheme join(final Scheme other) {
    final HashSet<Attribute> $ = new HashSet<Attribute>();

    for (int i = 0; i < attributes.length; ++i)
        $.add(attributes[i]);

    for (int i = 0; i < attributes.length; ++i)
        $.add(other.attributes[i]);
    return new Scheme(true, $.toArray(new Attribute[$.size()]));
}

and it said it has a bug in Scehme.join() but I can't see one!

The bug is in your second loop:

// Here ------------v
for (int i = 0; i < attributes.length; ++i)
    $.add(other.attributes[i]);

That should be other.attributes , not attributes .


This is a great example of why using the enhanced for loop is a good idea:

public Scheme join(final Scheme other) {
    final HashSet<Attribute> $ = new HashSet<Attribute>();

    for (Attribute attr : attributes) {
        $.add(attr);
    }

    for (Attribute attr : other.attributes) {
        $.add(attr);
    }

    return new Scheme(true, $.toArray(new Attribute[$.size()]));
}

my guess wille be here

final HashSet<attribute> $ = new HashSet<Attribute>();

on left hand side you have attribute and on right hand side Attribute , and as java is case sensitive language, this are two different objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM