1 4 package gnu.math; 5 import java.io.*; 6 7 8 9 public class NamedUnit extends Unit implements Externalizable 10 { 11 12 String name; 13 14 17 double scale; 18 19 20 Unit base; 21 22 23 NamedUnit chain; 24 25 public NamedUnit () 26 { 27 } 28 29 public NamedUnit (String name, DQuantity value) 30 { 31 this.name = name.intern(); 32 scale = value.factor; 33 base = value.unt; 34 init(); 35 } 36 37 public NamedUnit (String name, double factor, Unit base) 38 { 39 this.name = name; 40 this.base = base; 41 scale = factor; 42 init(); 43 } 44 45 protected void init () 46 { 47 factor = scale * base.factor; 48 dims = base.dims; 49 name = name.intern(); 50 int hash = name.hashCode(); 51 int index = (hash & 0x7FFFFFFF) % table.length; 52 chain = table[index]; 53 table[index] = this; 54 } 55 56 public String getName() { return name; } 57 58 public static NamedUnit lookup (String name) 59 { 60 name = name.intern(); 61 int hash = name.hashCode(); 62 int index = (hash & 0x7FFFFFFF) % table.length; 63 for (NamedUnit unit = table[index]; unit != null; unit = unit.chain) 64 { 65 if (unit.name == name) 66 return unit; 67 } 68 return null; 69 } 70 71 public static NamedUnit lookup (String name, double scale, Unit base) 72 { 73 name = name.intern(); 74 int hash = name.hashCode(); 75 int index = (hash & 0x7FFFFFFF) % table.length; 76 for (NamedUnit unit = table[index]; unit != null; unit = unit.chain) 77 { 78 if (unit.name == name && unit.scale == scale && unit.base == base) 79 return unit; 80 } 81 return null; 82 } 83 84 public static NamedUnit make (String name, double scale, Unit base) 85 { 86 NamedUnit old = lookup(name, scale, base); 87 return old == null ? new NamedUnit(name, scale, base) : old; 88 } 89 90 public static NamedUnit make (String name, Quantity value) 91 { 92 double scale; 93 if (value instanceof DQuantity) 94 scale = ((DQuantity) value).factor; 95 else if (value.imValue() != 0.0) 96 throw new ArithmeticException ("defining " + name 97 + " using complex value"); 98 else 99 scale = value.re().doubleValue(); 100 Unit base = value.unit(); 101 NamedUnit old = lookup(name, scale, base); 102 return old == null ? new NamedUnit(name, scale, base) : old; 103 } 104 105 109 110 public void writeExternal(ObjectOutput out) throws IOException 111 { 112 out.writeUTF(name); 113 out.writeDouble(scale); 114 out.writeObject(base); 115 } 116 117 public void readExternal(ObjectInput in) 118 throws IOException, ClassNotFoundException 119 { 120 name = in.readUTF(); 121 scale = in.readDouble(); 122 base = (Unit) in.readObject(); 123 } 124 125 public Object readResolve() throws ObjectStreamException 126 { 127 NamedUnit unit = lookup(name, scale, base); 128 if (unit != null) 129 return unit; 130 init(); 131 return this; 132 } 133 } 134 | Popular Tags |