Hey I wanted to ask how I can add elements in a new set that either are in my set a or set b or both sets. This is what I have until now. Would be nice of you could help me.
public static Set<String> vereinigung(Set<String> a, Set<String> b) {
Set<String> setForAB = new HashSet<String>();
//add elements from a
setForAB.add(String.valueOf(a));
//add elements from a
setForAB.add(String.valueOf(b));
//elements from both sets
setForAB.addAll(a);
setForAB.addAll(b);
return setForAB;
}
CodePudding user response:
You are on right track, removed unncessary code from your solution. This should suffice.
public static Set<String> vereinigung(Set<String> a, Set<String> b) {
Set<String> setForAB = new HashSet<String>();
//add elements from both sets
setForAB.addAll(a);
setForAB.addAll(b);
return setForAB;
}
CodePudding user response:
In Java, Sets can not contain duplicates, so if you want a set C to contain all values from set A and set B, then you simply need to add all elements of A and B. When a duplicate is found, it will simply ignore it and move on. I'm not sure why you are casting your sets to a string, but you can simply add the sets themselves to the new set:
Set<Integer> a = new HashSet<Integer>();
Set<Integer> b = new HashSet<Integer>();
Set<Integer> c = new HashSet<Integer>(a);
c.addAll(b);