Add further unit tests.
[cfb.git] / prod / net / jaekl / cfb / util / Util.java
1 package net.jaekl.cfb.util;
2
3 // Copyright (C) 2015 Christian Jaekl
4
5 import java.io.PrintWriter;
6 import java.io.StringWriter;
7 import java.util.Iterator;
8 import java.util.List;
9
10 public class Util {
11         // Returns true iff. a and b contain equal items in the same order
12         public static boolean listsAreEqual(List<?> a, List<?> b)
13         {
14                 if ((null == a) || (null == b)) {
15                         return (a == b);
16                 }
17                 
18                 if (0 == a.size()) {
19                         return (0 == b.size());
20                 }
21                 
22                 if (a.size() != b.size()) {
23                         return false;
24                 }
25                 
26                 Iterator<?> iterA = a.iterator();
27                 Iterator<?> iterB = b.iterator();
28                 
29                 while (iterA.hasNext()) {
30                         Object elemA = iterA.next();
31                         Object elemB = iterB.next();
32                         
33                         if (! objsAreEqual(elemA, elemB)) {
34                                 return false;
35                         }
36                 }
37                 
38                 return true;
39         }
40         
41         // Test for equality, while taking care to avoid 
42         // dereferencing a null pointer.
43         // Note that two null pointers are considered equal.
44         public static boolean objsAreEqual(Object a, Object b) 
45         {
46                 if ((null == a) || (null == b)) {
47                         return (a == b);
48                 }
49                 
50                 if ((a instanceof Number) && (b instanceof Number)) {
51                         Number aNum = (Number)a;
52                         Number bNum = (Number)b;
53                         
54                         return (   (aNum.longValue()   == bNum.longValue())
55                                         || (aNum.doubleValue() == bNum.doubleValue()) );
56                 }
57                 
58                 return a.equals(b);
59         }
60         
61         // Return 1 if obj is null, or obj.hashCode() otherwise
62         public static int objHashCode(Object obj)
63         {
64                 if (null == obj) {
65                         return 1;
66                 }
67                 return obj.hashCode();
68         }
69         
70         // Convert a Throwable to the string representation 
71         // that is generated by printStackTrace().
72         public static String stringify(Throwable thr) 
73         {
74                 StringWriter sw = new StringWriter();
75                 PrintWriter pw = new PrintWriter(sw);
76                 thr.printStackTrace(pw);
77                 return sw.toString();
78         }       
79 }