01: /**
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */package com.tc.test.collections;
04:
05: import com.tc.util.EqualityComparator;
06: import com.tc.util.Stringifier;
07:
08: import java.util.ArrayList;
09: import java.util.BitSet;
10: import java.util.List;
11:
12: /**
13: * A {@link CollectionComparer}that doesn't require objects to be in the same order. However, if multiple instances of
14: * a single object are present in at least one of the collections, then both collections must have the same number of
15: * instances of that object.
16: */
17: public class UnorderedCollectionComparer extends CollectionComparer {
18:
19: public UnorderedCollectionComparer(EqualityComparator comparator,
20: Stringifier describer) {
21: super (comparator, describer);
22: }
23:
24: protected CollectionMismatch[] doComparison(Object[] collectionOne,
25: Object[] collectionTwo) {
26: List mismatches = new ArrayList();
27:
28: BitSet oneUsed = new BitSet(collectionOne.length);
29: BitSet twoUsed = new BitSet(collectionTwo.length);
30:
31: for (int i = 0; i < collectionOne.length; ++i) {
32: if (!oneUsed.get(i)) {
33: int numberInOne = 1;
34:
35: for (int j = i + 1; j < collectionOne.length; ++j) {
36: if ((!oneUsed.get(j))
37: && isEqual(collectionOne[i], true,
38: collectionOne[j], true, i, j)) {
39: ++numberInOne;
40: oneUsed.set(j);
41: }
42: }
43:
44: int numberInTwo = 0;
45:
46: for (int j = 0; j < collectionTwo.length; ++j) {
47: if ((!twoUsed.get(j))
48: && isEqual(collectionOne[i], true,
49: collectionTwo[j], false, i, j)) {
50: ++numberInTwo;
51: twoUsed.set(j);
52: }
53: }
54:
55: if (numberInOne != numberInTwo) {
56: if (numberInTwo > 0) {
57: mismatchedNumbers(collectionOne, mismatches, i,
58: numberInOne, numberInTwo);
59: } else {
60: missingObject(collectionOne, mismatches, i);
61: }
62: }
63: }
64: }
65:
66: for (int i = 0; i < collectionTwo.length; ++i) {
67: if (!twoUsed.get(i)) {
68: mismatches.add(new MissingObjectCollectionMismatch(
69: collectionTwo[i], false, i, describer()));
70: }
71: }
72:
73: return (CollectionMismatch[]) mismatches
74: .toArray(new CollectionMismatch[mismatches.size()]);
75: }
76:
77: private void missingObject(Object[] collectionOne, List mismatches,
78: int i) {
79: mismatches.add(new MissingObjectCollectionMismatch(
80: collectionOne[i], true, i, describer()));
81: }
82:
83: protected void mismatchedNumbers(Object[] collectionOne,
84: List mismatches, int i, int numberInOne, int numberInTwo) {
85: mismatches.add(new UnequalObjectCountCollectionMismatch(
86: collectionOne[i], i, numberInOne, numberInTwo,
87: describer()));
88: }
89:
90: }
|