Set Relations

A∖B A∩B
B∖A
How to Test
A⊃BA⊂BChange A to match, picking A in A∩B Change A to match, Picking B in A∩B

X
A.isEmpty() && !B.isEmpty()

A⊂Btemp.setTo(B); temp.removeAll(A); A.setTo(temp);
same
X
X
B.containsAll(A) && !B.isEmpty()

A⊂Btemp.setTo(B); temp.retainAll(A); temp.addAll(B); A.setTo(temp);
A.setTo(B);
A.isEmpty() && B.isEmpty()
A⊃BA⊂B
A.clear();
same
X
A.equals(B) && !A.isEmpty()
A⊃BA⊂BA.retainAll(B)
temp.setTo(B); temp.retainAll(A);
A.setTo(temp);
X
!A.isEmpty() && B.isEmpty()
A⊃B
A.removeAll(B);
same
X
X
A.containsAll(B) && !B.isEmpty()
A⊃B

;
temp.setTo(B); temp.retainAll(A); temp.addAll(A); A.setTo(temp);
X
X
!A.containsNone(B)
&& !A.isEmpty() && !B.isEmpty()


A.xorAll(B);
same
X
X
X
!A.overlaps(B)


A.addAll(B);
temp.setTo(B); temp.addAll(A); A.setTo(temp);

The operations containsNone, overlaps; and the relation xorAll don't exist in Java (and the last two don't exist in UnicodeSet). They can be implemented in terms of other operations, but not efficiently. It would be better if they were natively supported, which is a rather small amount of code.

The last two columns describe operations in terms of what you would have to do to change A to match the results of the first three columns. For actions that replace an object by an equal object, it is useful to have 3 choices:
  • Retain the old one (A)
  • Replace the old by new (B)
  • Throw an exception - this is useful when you don't expect to get a new, different object or mapping, such as when building a map from data that is supposed to have unique keys.
Java appears to always have A win, for operations that leave the intersection. To favor the other, you have to use workarounds in the last column.

setTo is a convenience, not for efficiency.
A.setTo(B) := A.clear(); A.addAll(B);

Similar operations can be performed on two Maps. In that case, the choice of whether to have A or B win goes the other way in Java; B normally wins over A, when the keys are equals, as you'd expect from a "put" operation.

Comments