简体   繁体   中英

How do I write a union method without affecting the other sets?

This is the interface

public interface Set{
    public static final int MAX=10;
    public void add(int e);
    public Set union(Set s);
    public void display();
}

SetImp

public class SetImp implements Set{
    private int[] set;
    private int count;

    public SetImp(){
        set = new int[MAX];
        count = 0;
    }

    public void add(int e){
        if(!contains(e))
            set[count++]=e;
    }

    private boolean contains(int e){
        boolean found=false;
        for(int i=0;i<count;i++){
            if(set[i]==e){
                found=true;
                break;
            }
        }
        return found;
    }

    public void display(){
            for(int i=0;i<count;i++)
                System.out.print(set[i] + " ");
            System.out.println();
    }

Where I had most of my problems. Whenever I try to unite Set s with set, the union takes effect in both s. I tried making a temp variable but it still doesn't work.

    public Set union(Set s){
        for(int i=0; i<count; i++){
            s.add(set[i]);
        }
        return s;
    }
}

Your code starts with 2 sets:

Given set1.union(set2) , there's set1 and set2 of course.

Given: Set set3 = set1.union(set2); there are 3 completely separate sets: set1 and set2 did not change, which means set3 is different.

Therefore, you must have 3 sets. Given that at the start of the union method there are only 2... that means you must invoke new SetImp() someplace, or this is never going to work out.

I'm sure with that hint you can figure this one out:)

Create a new SetImp and add both Set s to it.

public Set union(Set s){
    final Set res = new SetImp();
    for(int i = 0; i < count; i++){
        res.add(set[i]);
    }
    for(int i = 0; i < s.count; i++){
        res.add(s.set[i]);
    }
    return res;
}

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