Work toward improving solidity. Add a few more unit tests, and some toString()
[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                 return a.equals(b);
51         }
52         
53         // Return 1 if obj is null, or obj.hashCode() otherwise
54         public static int objHashCode(Object obj)
55         {
56                 if (null == obj) {
57                         return 1;
58                 }
59                 return obj.hashCode();
60         }
61         
62         // Convert a Throwable to the string representation 
63         // that is generated by printStackTrace().
64         public static String stringify(Throwable thr) 
65         {
66                 StringWriter sw = new StringWriter();
67                 PrintWriter pw = new PrintWriter(sw);
68                 thr.printStackTrace(pw);
69                 return sw.toString();
70         }       
71 }