Frage

So here's my code:

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.event.ListSelectionEvent;

public enum SetOperation {

    AND(){
        public Set operate(Set one, Set two){
            one.retainAll(two);
            return one;
        }
    },

    OR(){
        public Set operate(Set one, Set two){
            one.addAll(two);
            return one;
        }
    };


    public abstract Set operate(Set one, Set two);

    public static void main(String[] args){

        Set<Integer> inta = new HashSet<Integer>();
        inta.add(1);
        inta.add(2);
        inta.add(3);

        Set<Integer> intb = new HashSet<Integer>();
        intb.add(3);
        intb.add(4);
        intb.add(5);


        System.out.println("A:" + inta);
        System.out.println("B:" + intb);
        System.out.println("\n Or Operation");
        System.out.println(SetOperation.OR.operate(inta, intb));
        System.out.println("A:" + inta);
        System.out.println("B:" + intb);
        System.out.println("\n AND Operation");
        System.out.println(SetOperation.AND.operate(inta, intb));
        System.out.println("A:" + inta);
        System.out.println("B:" + intb);
    }

}

What I'm trying to do is be able to get the intersection and union of two sets, but my problem is that while doing the operation, the first set is altered and I do not want that.

Here's what I mean:

The regular output of set A and set B is

[1, 2, 3]
[3, 4, 5]

but after doing the OR operation, I get is

[1, 2, 3, 4, 5]
A:[1, 2, 3, 4, 5]
B:[3, 4, 5]

and yes, it unions the two sets, but set A is altered to be the result of the union and I want it to remain the same so set A should stay as [1,2,3] and not change.

The same thing occurs with the AND operation, where my result is

 AND Operation
[3, 4, 5]
A:[3, 4, 5]
B:[3, 4, 5]

which returns an unwanted result because its taking the set A from the OR operation, which is also not what I want.

Is there any way to make my sets where they will not alter after an operation?

War es hilfreich?

Lösung

Try creating a new temporary Set off of one and running operations off of that.

AND(){
    public Set operate(Set one, Set two){
        Set temp = new HashSet<Integer>(one);
        temp.retainAll(two);
        return temp;
    }
},

OR(){
    public Set operate(Set one, Set two){
        Set temp = new HashSet<Integer>(one);
        temp.addAll(two);
        return one;
    }
};
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top