1 package com.mockobjects; 2 3 import com.mockobjects.util.Null; 4 5 import java.lang.reflect.Array ; 6 import java.util.Map ; 7 8 12 13 public class MapEntry implements Map.Entry { 14 private Object myKey; 15 private Object myValue; 16 17 public MapEntry(Object aKey, Object aValue) { 18 myKey = (aKey == null ? new Null() : aKey); 19 myValue = (aValue == null ? new Null() : aValue); 20 } 21 22 public boolean equals(Object o) { 23 if (!(o instanceof MapEntry)) { 24 return false; 25 } 26 MapEntry other = (MapEntry) o; 27 28 if (myValue.getClass().isArray() && other.getValue().getClass().isArray()) { 29 return arrayEquals(other.getValue()); 30 } else { 31 return myKey.equals(other.getKey()) && myValue.equals(other.getValue()); 32 } 33 } 34 35 private final boolean arrayEquals(Object anArray) { 36 int i = 0; 37 boolean endOfThisArray = false; 38 boolean endOfAnotherArray = false; 39 40 while (true) { 41 Object valueOfThis = null; 42 Object valueOfAnother = null; 43 44 try { 45 valueOfThis = Array.get(myValue, i); 46 } catch (ArrayIndexOutOfBoundsException e) { 47 endOfThisArray = true; 48 } 49 50 try { 51 valueOfAnother = Array.get(anArray, i); 52 } catch (ArrayIndexOutOfBoundsException e) { 53 endOfAnotherArray = true; 54 } 55 56 if (endOfThisArray && endOfAnotherArray) { 57 return true; 58 } 59 60 if (valueOfThis != null || valueOfAnother != null) { 61 if (valueOfThis == null || !valueOfThis.equals(valueOfAnother)) { 62 return false; 63 } 64 } 65 66 i++; 67 } 68 } 69 70 public Object getKey() { 71 return myKey; 72 } 73 74 public Object getValue() { 75 return myValue; 76 } 77 78 public int hashCode() { 79 int hash = myKey.hashCode(); 80 if (myValue.getClass().isArray()) { 81 int i = 0; 82 83 try { 84 while (true) { 85 hash = hash ^ Array.get(myValue, i++).hashCode(); 86 } 87 } catch (ArrayIndexOutOfBoundsException e) { 88 } 89 } else { 90 hash = hash ^ myValue.hashCode(); 91 } 92 return hash; 93 } 94 95 public Object setValue(Object aValue) { 96 Object oldValue = myValue; 97 myValue = (null == aValue ? new Null() : aValue); 98 return oldValue; 99 } 100 101 public String toString() { 102 return myKey.toString() + "=" + myValue.toString(); 103 } 104 } 105 | Popular Tags |