Source code: Freenet/support/StringKey.java
1 package Freenet.support;
2 import Freenet.*;
3 /*
4 This code is part of the Java Adaptive Network Client by Ian Clarke.
5 It is distributed under the GNU Public Licence (GPL) version 2. See
6 http://www.gnu.org/ for further details of the GPL.
7
8 Explanation of Code Versions:
9 0.0.0 = Initial Description
10 0.0.1 = API Specified
11 0.x (x>0) = Partial Implementation
12 x.0 (x>0) = Operational
13
14 Requires Classes: Class (version)
15 Class (version)
16 ...
17 */
18
19 /**
20 * An implementation of the Key interface for Strings
21 *
22 * @version 1.0
23 * @author <A HREF="mailto:I.Clarke@strs.co.uk">Ian Clarke</A>
24 **/
25
26
27 public class StringKey implements Key
28 {
29 String value;
30 public StringKey (String value)
31 {
32 this.value = value;
33 }
34
35 public int hashCode()
36 {
37 return value.hashCode();
38 }
39
40 public char charAt(int p)
41 {
42 if (p<this.value.length())
43 return this.value.charAt(p);
44 else
45 return (char) 0;
46 }
47
48 public boolean equals(Object t)
49 {
50 if (t != null && t instanceof StringKey)
51 {
52 return ((StringKey) t).value.equals(this.value);
53 }
54 else
55 return false;
56 }
57
58 public boolean lessThan(Key k) throws KeyException {
59 if (k == null || !(k instanceof StringKey))
60 throw new KeyException("Not the same type of key");
61 else
62 return ((StringKey) k).value.compareTo(value) < 0;
63 }
64
65
66 public boolean compare(Key kk1, Key kk2) throws KeyException
67 {
68 if (!(kk1 instanceof StringKey) ||
69 !(kk2 instanceof StringKey))
70 throw new KeyException("Trying to compare non-StringKey to StringKey");
71 StringKey k1 = (StringKey) kk1;
72 StringKey k2 = (StringKey) kk2;
73 for (int x=0; true; x++)
74 {
75 if ((x>this.value.length()) &&
76 (x>k1.value.length()) &&
77 (x>k2.value.length()))
78 return false;
79 int cc = charComp(this.charAt(x), k1.charAt(x),
80 k2.charAt(x));
81 if (cc == 1)
82 return true;
83 else if (cc == -1)
84 return false;
85 }
86 }
87
88 private int charComp(char c, char c1, char c2)
89 {
90 if ((Math.abs(Character.getNumericValue(c) -
91 Character.getNumericValue(c1))) <
92 (Math.abs(Character.getNumericValue(c) -
93 Character.getNumericValue(c2))))
94 // If c1 is closer than c2 return 1
95 return 1;
96 else if ((Math.abs(Character.getNumericValue(c) -
97 Character.getNumericValue(c1))) ==
98 (Math.abs(Character.getNumericValue(c) -
99 Character.getNumericValue(c2))))
100 // If the distance is equal return 0
101 return 0;
102 else
103 // else return -1
104 return -1;
105 }
106
107 public String toString()
108 {
109 return value;
110 }
111 }
112
113
114
115
116
117
118