What wrong with this Groovy method?

def setSymmetricDifferenceTheWrongWay(s1, s2) {
def sd = s1;
sd.addAll(s2);
def tmp = s1;
tmp.retainAll(s2);
sd.removeAll(tmp);
return sd;
}

Remember Lists are still just objects in Groovy as the are in Java, not primitives. Assigning a new reference to an object does not copy the object. You need to clone them.
def setSymmetricDifferenceTheRightWay(s1,s2){
def sd= s1.clone();//remember these are objects, assignment without clone is not copying
sd.addAll(s2);
def tmp=s1.clone();
tmp.retainAll(s2);
sd.removeAll(tmp);
return sd;
}

Comments

Popular Posts