-
Notifications
You must be signed in to change notification settings - Fork 108
/
DeepEquals.java
1731 lines (1512 loc) · 67.6 KB
/
DeepEquals.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.cedarsoftware.util;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static com.cedarsoftware.util.Converter.convert2BigDecimal;
import static com.cedarsoftware.util.Converter.convert2boolean;
/**
* Performs a deep comparison of two objects, going beyond simple {@code equals()} checks.
* Handles nested objects, collections, arrays, and maps while detecting circular references.
*
* <p><strong>Key features:</strong></p>
* <ul>
* <li>Compares entire object graphs including nested structures</li>
* <li>Handles circular references safely</li>
* <li>Provides detailed difference descriptions for troubleshooting</li>
* <li>Supports numeric comparisons with configurable precision</li>
* <li>Supports selective ignoring of custom {@code equals()} implementations</li>
* <li>Supports string-to-number equality comparisons</li>
* </ul>
*
* <p><strong>Options:</strong></p>
* <ul>
* <li>
* <code>IGNORE_CUSTOM_EQUALS</code> (a {@code Set<Class<?>>}):
* <ul>
* <li><strong>{@code null}</strong> — Use <em>all</em> custom {@code equals()} methods (ignore none).</li>
* <li><strong>Empty set</strong> — Ignore <em>all</em> custom {@code equals()} methods.</li>
* <li><strong>Non-empty set</strong> — Ignore only those classes’ custom {@code equals()} implementations.</li>
* </ul>
* </li>
* <li>
* <code>ALLOW_STRINGS_TO_MATCH_NUMBERS</code> (a {@code Boolean}):
* If set to {@code true}, allows strings like {@code "10"} to match the numeric value {@code 10}.
* </li>
* </ul>
*
* <p>The options {@code Map} acts as both input and output. When objects differ, the difference
* description is placed in the options {@code Map} under the "diff" key
* (see {@link DeepEquals#deepEquals(Object, Object, Map) deepEquals}).</p>
*
* <p><strong>Example usage:</strong></p>
* <pre><code>
* Map<String, Object> options = new HashMap<>();
* options.put(IGNORE_CUSTOM_EQUALS, Set.of(MyClass.class, OtherClass.class));
* options.put(ALLOW_STRINGS_TO_MATCH_NUMBERS, true);
*
* if (!DeepEquals.deepEquals(obj1, obj2, options)) {
* String diff = (String) options.get(DeepEquals.DIFF); // Get difference description
* // Handle or log 'diff'
* }
* </code></pre>
*
* @see #deepEquals(Object, Object)
* @see #deepEquals(Object, Object, Map)
*
* @author John DeRegnaucourt ([email protected])
* <br>
* Copyright (c) Cedar Software LLC
* <br><br>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <br><br>
* <a href="http://www.apache.org/licenses/LICENSE-2.0">License</a>
* <br><br>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@SuppressWarnings("unchecked")
public class DeepEquals {
// Option keys
public static final String IGNORE_CUSTOM_EQUALS = "ignoreCustomEquals";
public static final String ALLOW_STRINGS_TO_MATCH_NUMBERS = "stringsCanMatchNumbers";
public static final String DIFF = "diff";
private static final String EMPTY = "∅";
private static final String TRIANGLE_ARROW = "▶";
private static final String ARROW = "⇨";
private static final String ANGLE_LEFT = "《";
private static final String ANGLE_RIGHT = "》";
private static final double SCALE_DOUBLE = Math.pow(10, 10); // Scale according to epsilon for double
private static final float SCALE_FLOAT = (float) Math.pow(10, 5); // Scale according to epsilon for float
private static final ThreadLocal<Set<Object>> formattingStack = ThreadLocal.withInitial(() ->
Collections.newSetFromMap(new IdentityHashMap<>()));
// Epsilon values for floating-point comparisons
private static final double doubleEpsilon = 1e-15;
// Class to hold information about items being compared
private final static class ItemsToCompare {
private final Object _key1;
private final Object _key2;
private final ItemsToCompare parent;
private final String fieldName;
private final int[] arrayIndices;
private final Object mapKey;
private final Difference difference; // New field
// Modified constructors to include Difference
// Constructor for root
private ItemsToCompare(Object k1, Object k2) {
this(k1, k2, null, null, null, null, null);
}
// Constructor for differences where the Difference does not need additional information
private ItemsToCompare(Object k1, Object k2, ItemsToCompare parent, Difference difference) {
this(k1, k2, parent, null, null, null, difference);
}
// Constructor for field access with difference
private ItemsToCompare(Object k1, Object k2, String fieldName, ItemsToCompare parent, Difference difference) {
this(k1, k2, parent, fieldName, null, null, difference);
}
// Constructor for array access with difference
private ItemsToCompare(Object k1, Object k2, int[] indices, ItemsToCompare parent, Difference difference) {
this(k1, k2, parent, null, indices, null, difference);
}
// Constructor for map access with difference
private ItemsToCompare(Object k1, Object k2, Object mapKey, ItemsToCompare parent, boolean isMapKey, Difference difference) {
this(k1, k2, parent, null, null, mapKey, difference);
}
// Base constructor
private ItemsToCompare(Object k1, Object k2, ItemsToCompare parent,
String fieldName, int[] arrayIndices, Object mapKey, Difference difference) {
this._key1 = k1;
this._key2 = k2;
this.parent = parent;
this.fieldName = fieldName;
this.arrayIndices = arrayIndices;
this.mapKey = mapKey;
this.difference = difference;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof ItemsToCompare)) {
return false;
}
ItemsToCompare that = (ItemsToCompare) other;
// Only compare the actual objects being compared (by identity)
return _key1 == that._key1 && _key2 == that._key2;
}
@Override
public int hashCode() {
return System.identityHashCode(_key1) * 31 + System.identityHashCode(_key2);
}
}
/**
* Performs a deep comparison between two objects, going beyond a simple {@code equals()} check.
* <p>
* This method is functionally equivalent to calling
* {@link #deepEquals(Object, Object, Map) deepEquals(a, b, new HashMap<>())},
* which means it uses no additional comparison options. In other words:
* <ul>
* <li>{@code IGNORE_CUSTOM_EQUALS} is not set (all custom equals() methods are used)</li>
* <li>{@code ALLOW_STRINGS_TO_MATCH_NUMBERS} defaults to {@code false}</li>
* </ul>
* </p>
*
* @param a the first object to compare, may be {@code null}
* @param b the second object to compare, may be {@code null}
* @return {@code true} if the two objects are deeply equal, {@code false} otherwise
* @see #deepEquals(Object, Object, Map)
*/
public static boolean deepEquals(Object a, Object b) {
return deepEquals(a, b, new HashMap<>());
}
/**
* Performs a deep comparison between two objects with optional comparison settings.
* <p>
* In addition to comparing objects, collections, maps, and arrays for equality of nested
* elements, this method can also:
* <ul>
* <li>Ignore certain classes' custom {@code equals()} methods according to user-defined rules</li>
* <li>Allow string-to-number comparisons (e.g., {@code "10"} equals {@code 10})</li>
* <li>Handle floating-point comparisons with tolerance for precision</li>
* <li>Detect and handle circular references to avoid infinite loops</li>
* </ul>
*
* <p><strong>Options:</strong></p>
* <ul>
* <li>
* {@code DeepEquals.IGNORE_CUSTOM_EQUALS} (a {@code Collection<Class<?>>}):
* <ul>
* <li><strong>{@code null}</strong> — Use <em>all</em> custom {@code equals()} methods (ignore none). Default.</li>
* <li><strong>Empty set</strong> — Ignore <em>all</em> custom {@code equals()} methods.</li>
* <li><strong>Non-empty set</strong> — Ignore only those classes’ custom {@code equals()} implementations.</li>
* </ul>
* </li>
* <li>
* {@code DeepEquals.ALLOW_STRINGS_TO_MATCH_NUMBERS} (a {@code Boolean}):
* If set to {@code true}, allows strings like {@code "10"} to match the numeric value {@code 10}. Default false.
* </li>
* </ul>
*
* <p>If the objects differ, a difference description string is stored in {@code options}
* under the key {@code "diff"}. The key {@code "diff_item"} can provide additional context
* regarding the specific location of the mismatch.</p>
*
* @param a the first object to compare, may be {@code null}
* @param b the second object to compare, may be {@code null}
* @param options a map of comparison options and, on return, possibly difference details
* @return {@code true} if the two objects are deeply equal, {@code false} otherwise
* @see #deepEquals(Object, Object)
*/
public static boolean deepEquals(Object a, Object b, Map<String, ?> options) {
try {
Set<Object> visited = new HashSet<>();
return deepEquals(a, b, options, visited);
} finally {
formattingStack.remove(); // Always remove. When needed next time, initialValue() will be called.
}
}
private static boolean deepEquals(Object a, Object b, Map<String, ?> options, Set<Object> visited) {
Deque<ItemsToCompare> stack = new LinkedList<>();
boolean result = deepEquals(a, b, stack, options, visited);
boolean isRecurive = Objects.equals(true, options.get("recursive_call"));
if (!result && !stack.isEmpty()) {
// Store both the breadcrumb and the difference ItemsToCompare
ItemsToCompare top = stack.peek();
String breadcrumb = generateBreadcrumb(stack);
((Map<String, Object>) options).put(DIFF, breadcrumb);
((Map<String, Object>) options).put("diff_item", top);
// if (!isRecurive) {
// System.out.println(breadcrumb);
// System.out.println("--------------------");
// System.out.flush();
// }
}
return result;
}
// Recursive deepEquals implementation
private static boolean deepEquals(Object a, Object b, Deque<ItemsToCompare> stack,
Map<String, ?> options, Set<Object> visited) {
Collection<Class<?>> ignoreCustomEquals = (Collection<Class<?>>) options.get(IGNORE_CUSTOM_EQUALS);
boolean allowAllCustomEquals = ignoreCustomEquals == null;
boolean hasNonEmptyIgnoreSet = (ignoreCustomEquals != null && !ignoreCustomEquals.isEmpty());
final boolean allowStringsToMatchNumbers = convert2boolean(options.get(ALLOW_STRINGS_TO_MATCH_NUMBERS));
stack.addFirst(new ItemsToCompare(a, b));
while (!stack.isEmpty()) {
ItemsToCompare itemsToCompare = stack.peek();
if (visited.contains(itemsToCompare)) {
stack.removeFirst();
continue;
}
visited.add(itemsToCompare);
final Object key1 = itemsToCompare._key1;
final Object key2 = itemsToCompare._key2;
// Same instance is always equal to itself, null or otherwise.
if (key1 == key2) {
continue;
}
// If either one is null, they are not equal (key1 == key2 already checked)
if (key1 == null || key2 == null) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.VALUE_MISMATCH));
return false;
}
// Handle all numeric comparisons first
if (key1 instanceof Number && key2 instanceof Number) {
if (!compareNumbers((Number) key1, (Number) key2)) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.VALUE_MISMATCH));
return false;
}
continue;
}
// Handle String-to-Number comparison if option is enabled
if (allowStringsToMatchNumbers &&
((key1 instanceof String && key2 instanceof Number) ||
(key1 instanceof Number && key2 instanceof String))) {
try {
if (key1 instanceof String) {
if (compareNumbers(convert2BigDecimal(key1), (Number) key2)) {
continue;
}
} else {
if (compareNumbers((Number) key1, convert2BigDecimal(key2))) {
continue;
}
}
} catch (Exception ignore) { }
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.VALUE_MISMATCH));
return false;
}
if (key1 instanceof AtomicBoolean && key2 instanceof AtomicBoolean) {
if (!compareAtomicBoolean((AtomicBoolean) key1, (AtomicBoolean) key2)) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.VALUE_MISMATCH));
return false;
} else {
continue;
}
}
Class<?> key1Class = key1.getClass();
Class<?> key2Class = key2.getClass();
// Handle primitive wrappers, String, Date, Class, UUID, URL, URI, Temporal classes, etc.
if (Converter.isSimpleTypeConversionSupported(key1Class, key1Class)) {
if (key1 instanceof Comparable && key2 instanceof Comparable) {
try {
if (((Comparable)key1).compareTo(key2) != 0) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.VALUE_MISMATCH));
return false;
}
continue;
} catch (Exception ignored) { } // Fall back to equals() if compareTo() fails
}
if (!key1.equals(key2)) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.VALUE_MISMATCH));
return false;
}
continue;
}
// Ordered collections where order is defined as part of equality
if (key1 instanceof List) { // If Collections, they both must be Collection
if (!(key2 instanceof List)) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.TYPE_MISMATCH));
return false;
}
if (!decomposeOrderedCollection((Collection<?>) key1, (Collection<?>) key2, stack)) {
// Push VALUE_MISMATCH so parent's container-level description (e.g. "collection size mismatch")
// takes precedence over element-level differences
ItemsToCompare prior = stack.peek();
stack.addFirst(new ItemsToCompare(prior._key1, prior._key2, prior, Difference.VALUE_MISMATCH));
return false;
}
continue;
} else if (key2 instanceof List) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.TYPE_MISMATCH));
return false;
}
// Unordered Collection comparison
if (key1 instanceof Collection) {
if (!(key2 instanceof Collection)) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.COLLECTION_TYPE_MISMATCH));
return false;
}
if (!decomposeUnorderedCollection((Collection<?>) key1, (Collection<?>) key2, stack)) {
// Push VALUE_MISMATCH so parent's container-level description (e.g. "collection size mismatch")
// takes precedence over element-level differences
ItemsToCompare prior = stack.peek();
stack.addFirst(new ItemsToCompare(prior._key1, prior._key2, prior, Difference.VALUE_MISMATCH));
return false;
}
continue;
} else if (key2 instanceof Collection) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.COLLECTION_TYPE_MISMATCH));
return false;
}
// Map comparison
if (key1 instanceof Map) {
if (!(key2 instanceof Map)) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.TYPE_MISMATCH));
return false;
}
if (!decomposeMap((Map<?, ?>) key1, (Map<?, ?>) key2, stack, options, visited)) {
// Push VALUE_MISMATCH so parent's container-level description (e.g. "map value mismatch")
// takes precedence over element-level differences
ItemsToCompare prior = stack.peek();
stack.addFirst(new ItemsToCompare(prior._key1, prior._key2, prior, Difference.VALUE_MISMATCH));
return false;
}
continue;
} else if (key2 instanceof Map) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.TYPE_MISMATCH));
return false;
}
// Array comparison
if (key1Class.isArray()) {
if (!key2Class.isArray()) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.TYPE_MISMATCH));
return false;
}
if (!decomposeArray(key1, key2, stack)) {
// Push VALUE_MISMATCH so parent's container-level description (e.g. "array element mismatch")
// takes precedence over element-level differences
ItemsToCompare prior = stack.peek();
stack.addFirst(new ItemsToCompare(prior._key1, prior._key2, prior, Difference.VALUE_MISMATCH));
return false;
}
continue;
} else if (key2Class.isArray()) {
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.TYPE_MISMATCH));
return false;
}
// Must be same class if not a container type
if (!key1Class.equals(key2Class)) { // Must be same class
stack.addFirst(new ItemsToCompare(key1, key2, stack.peek(), Difference.TYPE_MISMATCH));
return false;
}
// If there is a custom equals and not ignored, compare using custom equals
if (hasCustomEquals(key1Class)) {
boolean useCustomEqualsForThisClass = hasNonEmptyIgnoreSet && !ignoreCustomEquals.contains(key1Class);
if (allowAllCustomEquals || useCustomEqualsForThisClass) {
// No Field-by-field break down
if (!key1.equals(key2)) {
// Custom equals failed. Call "deepEquals()" below on failure of custom equals() above.
// This gets us the "detail" on WHY the custom equals failed (first issue).
Map<String, Object> newOptions = new HashMap<>(options);
newOptions.put("recursive_call", true);
// Create new ignore set preserving existing ignored classes
Set<Class<?>> ignoreSet = new HashSet<>();
if (ignoreCustomEquals != null) {
ignoreSet.addAll(ignoreCustomEquals);
}
ignoreSet.add(key1Class);
newOptions.put(IGNORE_CUSTOM_EQUALS, ignoreSet);
// Make recursive call to find the actual difference
deepEquals(key1, key2, newOptions);
// Get the difference and add it to our stack
ItemsToCompare diff = (ItemsToCompare) newOptions.get("diff_item");
if (diff != null) {
stack.addFirst(diff);
}
return false;
}
continue;
}
}
// Decompose object into its fields (not using custom equals)
decomposeObject(key1, key2, stack);
}
return true;
}
/**
* Compares two unordered collections (e.g., Sets) deeply.
*
* @param col1 First collection.
* @param col2 Second collection.
* @return true if collections are equal, false otherwise.
*/
private static boolean decomposeUnorderedCollection(Collection<?> col1, Collection<?> col2, Deque<ItemsToCompare> stack) {
ItemsToCompare currentItem = stack.peek();
// Check sizes first
if (col1.size() != col2.size()) {
stack.addFirst(new ItemsToCompare(col1, col2, currentItem, Difference.COLLECTION_SIZE_MISMATCH));
return false;
}
// Group col2 items by hash for efficient lookup
Map<Integer, List<Object>> hashGroups = new HashMap<>();
for (Object o : col2) {
int hash = deepHashCode(o);
hashGroups.computeIfAbsent(hash, k -> new ArrayList<>()).add(o);
}
// Find first item in col1 not found in col2
for (Object item1 : col1) {
int hash1 = deepHashCode(item1);
List<Object> candidates = hashGroups.get(hash1);
if (candidates == null || candidates.isEmpty()) {
// No hash matches - first difference found
stack.addFirst(new ItemsToCompare(item1, null, currentItem, Difference.COLLECTION_MISSING_ELEMENT));
return false;
}
// Check candidates with matching hash
boolean foundMatch = false;
for (Object item2 : candidates) {
if (deepEquals(item1, item2)) {
foundMatch = true;
candidates.remove(item2);
if (candidates.isEmpty()) {
hashGroups.remove(hash1);
}
break;
}
}
if (!foundMatch) {
// No matching element found - first difference found
stack.addFirst(new ItemsToCompare(item1, null, currentItem, Difference.COLLECTION_MISSING_ELEMENT));
return false;
}
}
return true;
}
private static boolean decomposeOrderedCollection(Collection<?> col1, Collection<?> col2, Deque<ItemsToCompare> stack) {
ItemsToCompare currentItem = stack.peek();
// Check sizes first
if (col1.size() != col2.size()) {
stack.addFirst(new ItemsToCompare(col1, col2, currentItem, Difference.COLLECTION_SIZE_MISMATCH));
return false;
}
// Push elements in order
Iterator<?> i1 = col1.iterator();
Iterator<?> i2 = col2.iterator();
int index = 0;
while (i1.hasNext()) {
Object item1 = i1.next();
Object item2 = i2.next();
stack.addFirst(new ItemsToCompare(item1, item2, new int[]{index++}, currentItem, Difference.COLLECTION_ELEMENT_MISMATCH));
}
return true;
}
private static boolean decomposeMap(Map<?, ?> map1, Map<?, ?> map2, Deque<ItemsToCompare> stack, Map<String, ?> options, Set<Object> visited) {
ItemsToCompare currentItem = stack.peek();
// Check sizes first
if (map1.size() != map2.size()) {
stack.addFirst(new ItemsToCompare(map1, map2, currentItem, Difference.MAP_SIZE_MISMATCH));
return false;
}
// Build lookup of map2 entries for efficient matching
Map<Integer, Collection<Map.Entry<?, ?>>> fastLookup = new HashMap<>();
for (Map.Entry<?, ?> entry : map2.entrySet()) {
int hash = deepHashCode(entry.getKey());
fastLookup.computeIfAbsent(hash, k -> new ArrayList<>())
.add(new AbstractMap.SimpleEntry<>(entry.getKey(), entry.getValue()));
}
// Process map1 entries
for (Map.Entry<?, ?> entry : map1.entrySet()) {
Collection<Map.Entry<?, ?>> otherEntries = fastLookup.get(deepHashCode(entry.getKey()));
// Key not found in map2
if (otherEntries == null || otherEntries.isEmpty()) {
stack.addFirst(new ItemsToCompare(entry.getKey(), null, currentItem, Difference.MAP_MISSING_KEY));
return false;
}
// Find matching key in otherEntries
boolean foundMatch = false;
Iterator<Map.Entry<?, ?>> iterator = otherEntries.iterator();
while (iterator.hasNext()) {
Map.Entry<?, ?> otherEntry = iterator.next();
// Check if keys are equal
if (deepEquals(entry.getKey(), otherEntry.getKey(), options, visited)) {
// Push value comparison only - keys are known to be equal
stack.addFirst(new ItemsToCompare(
entry.getValue(), // map1 value
otherEntry.getValue(), // map2 value
entry.getKey(), // pass the key as 'mapKey'
currentItem, // parent
true, // isMapKey = true
Difference.MAP_VALUE_MISMATCH));
iterator.remove();
if (otherEntries.isEmpty()) {
fastLookup.remove(deepHashCode(entry.getKey()));
}
foundMatch = true;
break;
}
}
if (!foundMatch) {
stack.addFirst(new ItemsToCompare(entry.getKey(), null, currentItem, Difference.MAP_MISSING_KEY));
return false;
}
}
return true;
}
/**
* Breaks an array into comparable pieces.
*
* @param array1 First array.
* @param array2 Second array.
* @param stack Comparison stack.
* @return true if arrays are equal, false otherwise.
*/
private static boolean decomposeArray(Object array1, Object array2, Deque<ItemsToCompare> stack) {
ItemsToCompare currentItem = stack.peek(); // This will be the parent
// 1. Check dimensionality
Class<?> type1 = array1.getClass();
Class<?> type2 = array2.getClass();
int dim1 = 0, dim2 = 0;
while (type1.isArray()) {
dim1++;
type1 = type1.getComponentType();
}
while (type2.isArray()) {
dim2++;
type2 = type2.getComponentType();
}
if (dim1 != dim2) {
stack.addFirst(new ItemsToCompare(array1, array2, currentItem, Difference.ARRAY_DIMENSION_MISMATCH));
return false;
}
// 2. Check component types
if (!array1.getClass().getComponentType().equals(array2.getClass().getComponentType())) {
stack.addFirst(new ItemsToCompare(array1, array2, currentItem, Difference.ARRAY_COMPONENT_TYPE_MISMATCH));
return false;
}
// 3. Check lengths
int len1 = Array.getLength(array1);
int len2 = Array.getLength(array2);
if (len1 != len2) {
stack.addFirst(new ItemsToCompare(array1, array2, currentItem, Difference.ARRAY_LENGTH_MISMATCH));
return false;
}
// 4. Push all elements onto stack (with their full dimensional indices)
for (int i = len1 - 1; i >= 0; i--) {
stack.addFirst(new ItemsToCompare(Array.get(array1, i), Array.get(array2, i),
new int[]{i}, // For multidimensional arrays, this gets built up
currentItem, Difference.ARRAY_ELEMENT_MISMATCH));
}
return true;
}
private static boolean decomposeObject(Object obj1, Object obj2, Deque<ItemsToCompare> stack) {
ItemsToCompare currentItem = stack.peek();
// Get all fields from the object
Collection<Field> fields = ReflectionUtils.getAllDeclaredFields(obj1.getClass());
// Push each field for comparison
for (Field field : fields) {
try {
if (field.getName().startsWith("this$")) {
continue;
}
Object value1 = field.get(obj1);
Object value2 = field.get(obj2);
stack.addFirst(new ItemsToCompare(value1, value2, field.getName(), currentItem, Difference.FIELD_VALUE_MISMATCH));
} catch (Exception ignored) {
}
}
return true;
}
/**
* Compares two numbers deeply, handling floating point precision.
*
* @param a First number.
* @param b Second number.
* @return true if numbers are equal within the defined precision, false otherwise.
*/
private static boolean compareNumbers(Number a, Number b) {
// Handle floating point comparisons
if (a instanceof Float || a instanceof Double ||
b instanceof Float || b instanceof Double) {
// Check for overflow/underflow when comparing with BigDecimal
if (a instanceof BigDecimal || b instanceof BigDecimal) {
try {
BigDecimal bd;
if (a instanceof BigDecimal) {
bd = (BigDecimal) a;
} else {
bd = (BigDecimal) b;
}
// If BigDecimal is outside Double's range, they can't be equal
if (bd.compareTo(BigDecimal.valueOf(Double.MAX_VALUE)) > 0 ||
bd.compareTo(BigDecimal.valueOf(-Double.MAX_VALUE)) < 0) {
return false;
}
} catch (Exception e) {
return false;
}
}
// Normal floating point comparison
double d1 = a.doubleValue();
double d2 = b.doubleValue();
return nearlyEqual(d1, d2, doubleEpsilon);
}
// For non-floating point numbers, use exact comparison
try {
BigDecimal x = convert2BigDecimal(a);
BigDecimal y = convert2BigDecimal(b);
return x.compareTo(y) == 0;
} catch (Exception e) {
return false;
}
}
/**
* Correctly handles floating point comparisons.
*
* @param a First number.
* @param b Second number.
* @param epsilon Tolerance value.
* @return true if numbers are nearly equal within the tolerance, false otherwise.
*/
private static boolean nearlyEqual(double a, double b, double epsilon) {
final double absA = Math.abs(a);
final double absB = Math.abs(b);
final double diff = Math.abs(a - b);
if (a == b) { // shortcut, handles infinities
return true;
} else if (a == 0 || b == 0 || diff < Double.MIN_NORMAL) {
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Double.MIN_NORMAL);
} else { // use relative error
return diff / (absA + absB) < epsilon;
}
}
/**
* Compares two AtomicBoolean instances.
*
* @param a First AtomicBoolean.
* @param b Second AtomicBoolean.
* @return true if both have the same value, false otherwise.
*/
private static boolean compareAtomicBoolean(AtomicBoolean a, AtomicBoolean b) {
return a.get() == b.get();
}
/**
* Determines whether the given class has a custom {@code equals(Object)} method
* distinct from {@code Object.equals(Object)}.
* <p>
* Useful for detecting when a class relies on a specialized equality definition,
* which can be selectively ignored by deep-comparison if desired.
* </p>
*
* @param c the class to inspect, must not be {@code null}
* @return {@code true} if {@code c} declares its own {@code equals(Object)} method,
* {@code false} otherwise
*/
public static boolean hasCustomEquals(Class<?> c) {
Method equals = ReflectionUtils.getMethod(c, "equals", Object.class); // cached
return equals.getDeclaringClass() != Object.class;
}
/**
* Determines whether the given class has a custom {@code hashCode()} method
* distinct from {@code Object.hashCode()}.
* <p>
* This can help identify classes that rely on a specialized hashing algorithm,
* potentially relevant for certain comparison or hashing scenarios.
* </p>
*
* @param c the class to inspect, must not be {@code null}
* @return {@code true} if {@code c} declares its own {@code hashCode()} method,
* {@code false} otherwise
*/
public static boolean hasCustomHashCode(Class<?> c) {
Method hashCode = ReflectionUtils.getMethod(c, "hashCode"); // cached
return hashCode.getDeclaringClass() != Object.class;
}
/**
* Computes a deep hash code for the given object by traversing its entire graph.
* <p>
* This method considers the hash codes of nested objects, arrays, maps, and collections,
* and uses cyclic reference detection to avoid infinite loops.
* </p>
* <p>
* While deepHashCode() enables O(n) comparison performance in DeepEquals() when comparing
* unordered collections and maps, it does not guarantee that objects which are deepEquals()
* will have matching deepHashCode() values. This design choice allows for optimized
* performance while maintaining correctness of equality comparisons.
* </p>
* <p>
* You can use it for generating your own hashCodes() on complex items, but understand that
* it *always* calls an instants hashCode() method if it has one that override's the
* hashCode() method defined on Object.class.
* </p>
* @param obj the object to hash, may be {@code null}
* @return an integer representing the object's deep hash code
*/
public static int deepHashCode(Object obj) {
Set<Object> visited = Collections.newSetFromMap(new IdentityHashMap<>());
return deepHashCode(obj, visited);
}
private static int deepHashCode(Object obj, Set<Object> visited) {
LinkedList<Object> stack = new LinkedList<>();
stack.addFirst(obj);
int hash = 0;
while (!stack.isEmpty()) {
obj = stack.removeFirst();
if (obj == null || visited.contains(obj)) {
continue;
}
visited.add(obj);
// Ensure array order matters to hash
if (obj.getClass().isArray()) {
final int len = Array.getLength(obj);
long result = 1;
for (int i = 0; i < len; i++) {
Object element = Array.get(obj, i);
result = 31 * result + hashElement(visited, element);
}
hash += (int) result;
continue;
}
// Order matters for List - it is defined as part of equality
if (obj instanceof List) {
List<?> col = (List<?>) obj;
long result = 1;
for (Object element : col) {
result = 31 * result + hashElement(visited, element);
}
hash += (int) result;
continue;
}
// Ignore order for non-List Collections (not part of definition of equality)
if (obj instanceof Collection) {
stack.addAll(0, (Collection<?>) obj);
continue;
}
if (obj instanceof Map) {
stack.addAll(0, ((Map<?, ?>) obj).keySet());
stack.addAll(0, ((Map<?, ?>) obj).values());
continue;
}
if (obj instanceof Float) {
hash += hashFloat((Float) obj);
continue;
} else if (obj instanceof Double) {
hash += hashDouble((Double) obj);
continue;
}
if (hasCustomHashCode(obj.getClass())) { // A real hashCode() method exists, call it.
hash += obj.hashCode();
continue;
}
Collection<Field> fields = ReflectionUtils.getAllDeclaredFields(obj.getClass());
for (Field field : fields) {
try {
if (field.getName().contains("this$")) {
continue;
}
stack.addFirst(field.get(obj));
} catch (Exception ignored) {
}
}
}
return hash;
}
private static int hashElement(Set<Object> visited, Object element) {
if (element == null) {
return 0;
} else if (element instanceof Double) {
return hashDouble((Double) element);
} else if (element instanceof Float) {
return hashFloat((Float) element);
} else if (Converter.isSimpleTypeConversionSupported(element.getClass(), element.getClass())) {
return element.hashCode();
} else {
return deepHashCode(element, visited);
}
}
private static int hashDouble(double value) {
double normalizedValue = Math.round(value * SCALE_DOUBLE) / SCALE_DOUBLE;
long bits = Double.doubleToLongBits(normalizedValue);
return (int) (bits ^ (bits >>> 32));
}
private static int hashFloat(float value) {
float normalizedValue = Math.round(value * SCALE_FLOAT) / SCALE_FLOAT;
return Float.floatToIntBits(normalizedValue);
}
private enum DiffCategory {
VALUE,
TYPE,
SIZE,
LENGTH,
DIMENSION
}
private enum Difference {
// Basic value difference (includes numbers, atomic values, field values)
VALUE_MISMATCH("value mismatch", DiffCategory.VALUE),
FIELD_VALUE_MISMATCH("field value mismatch", DiffCategory.VALUE),
// Collection-specific
COLLECTION_SIZE_MISMATCH("collection size mismatch", DiffCategory.SIZE),
COLLECTION_MISSING_ELEMENT("missing collection element", DiffCategory.VALUE),
COLLECTION_TYPE_MISMATCH("collection type mismatch", DiffCategory.TYPE),
COLLECTION_ELEMENT_MISMATCH("collection element mismatch", DiffCategory.VALUE),
// Map-specific
MAP_SIZE_MISMATCH("map size mismatch", DiffCategory.SIZE),
MAP_MISSING_KEY("missing map key", DiffCategory.VALUE),
MAP_VALUE_MISMATCH("map value mismatch", DiffCategory.VALUE),
// Array-specific
ARRAY_DIMENSION_MISMATCH("array dimensionality mismatch", DiffCategory.DIMENSION),
ARRAY_COMPONENT_TYPE_MISMATCH("array component type mismatch", DiffCategory.TYPE),
ARRAY_LENGTH_MISMATCH("array length mismatch", DiffCategory.LENGTH),
ARRAY_ELEMENT_MISMATCH("array element mismatch", DiffCategory.VALUE),
// General type mismatch (when classes don't match)
TYPE_MISMATCH("type mismatch", DiffCategory.TYPE);
private final String description;
private final DiffCategory category;
Difference(String description, DiffCategory category) {
this.description = description;
this.category = category;
}
String getDescription() { return description; }
DiffCategory getCategory() { return category; }
}
private static String generateBreadcrumb(Deque<ItemsToCompare> stack) {
ItemsToCompare diffItem = stack.peek();
StringBuilder result = new StringBuilder();