Subversion Repositories programming

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
5 irasnyd 1
//import chap09.list03.Map;
2
 
3
import java.io.*;
4
import java.util.*;
5
 
6
public class HashTable implements Map {  // open addressing
7 irasnyd 7
    private Entry[] entries; 
8
 
9
    //size is the total number of elements, including NIL
10
    //used is the total number of elements, NOT INCLUDING NIL
5 irasnyd 11
    private int size, used;
12
    private float loadFactor;
13
    private final Entry NIL = new Entry(null,null);  // dummy
9 irasnyd 14
 
10 irasnyd 15
    private int probeType; //holds the type of probing to use    
16
 
9 irasnyd 17
    //variable to hold total number of collisions this run.
18
    //Definition: collision - the number of times we must jump to
19
    //                        get to the next null space in the table
20
    //                        This includes jumping NIL's
21
    //
22
    //NOTE: will only be counted on inserting values
7 irasnyd 23
    private int collisions; //initialized to 0 by default
5 irasnyd 24
 
7 irasnyd 25
    //create a HashTable with a certain capacity (maximum items)
26
    //and a maximum load factor (if we exceed this we will rehash)
5 irasnyd 27
    public HashTable(int capacity, float loadFactor) {
28
        entries = new Entry[capacity];
29
        this.loadFactor = loadFactor; }
30
 
7 irasnyd 31
    //create a HashTable with a certain capacity (maximum items)
32
    //and a default load factor of 0.75
5 irasnyd 33
    public HashTable(int capacity) {
7 irasnyd 34
        this(capacity,0.75F);} //calls the HashTable( int, float ) constructor
5 irasnyd 35
 
7 irasnyd 36
    //create a default HashTable with default capacity (101 items) and
37
    //default load factor of 0.75
5 irasnyd 38
    public HashTable() {
7 irasnyd 39
        this(101); } //calls the HashTable( int ) constructor
5 irasnyd 40
 
7 irasnyd 41
    //Method to find a certain key in the HashTable
42
    //Precondition: key != null
43
    //Postcondition: return the entry's value if the key is found
44
    //               otherwise return null for not found
5 irasnyd 45
    public Object get(Object key) {
46
        int h=hash(key);
47
        for (int i=0; i<entries.length; i++) {
48
            int j = nextProbe(h,i);
49
            Entry entry=entries[j];
50
            if (entry==null) break;
51
            if (entry==NIL) continue;
52
            if (entry.key.equals(key)) return entry.value;  // success
53
        }
54
        return null;  // failure: key not found
55
    }
6 irasnyd 56
 
7 irasnyd 57
    //Method to add a key/value pair to the HashTable
58
    //Key - the value that gets hash() called on it. Should be unique (hopefully)
59
    //Value - the actual data that is to be stored.
60
    //Precondition: key != null
61
    //Postcondition: return null if the object was inserted sucessfully
62
    //               return the value that was there if we updated a value
63
    //               return null if the table overflows (should never happen,
64
    //               but it is there just in case)
5 irasnyd 65
    public Object put(Object key, Object value) {
66
        if (used>loadFactor*entries.length) rehash();
11 irasnyd 67
 
68
	System.out.print(key); //print out the key
69
 
70
	int h=hash(key); //hash the key
71
 
72
	for (int i=0; i<entries.length; i++) { //run once for each place in the Table
7 irasnyd 73
            int j = nextProbe(h,i); //get the [first, next] place to try putting the value
74
            Entry entry=entries[j]; //get the Entry at j (where we want to put value)
75
 
11 irasnyd 76
	    System.out.print(" -> " + j); //print the location we tried to place the value
77
 
7 irasnyd 78
	    //if entry[j] == null then we have found a good place to put value!
79
	    if (entry==null) {
11 irasnyd 80
 
81
                System.out.println(); //terminate the line
82
 
5 irasnyd 83
                entries[j] = new Entry(key,value);
84
                ++size;
85
                ++used;
86
                return null;  // insertion success
87
            }
7 irasnyd 88
 
89
	    //if entry[j] == NIL then we must continue to probe for a new place,
90
	    //otherwise we will confuse the remove() and get() methods
9 irasnyd 91
            if (entry==NIL) { collisions++; continue; }
7 irasnyd 92
 
93
	    //if entry[j].key == key then we need to update the record
5 irasnyd 94
            if (entry.key.equals(key)) {
95
                Object oldValue=entry.value;
96
                entries[j].value = value;
97
                return oldValue;  // update success
98
            }
9 irasnyd 99
 
100
	    //if we get here, we have had a collision that is not a NIL,
101
	    //and is not an Entry that needs updating, therefore it is something
102
	    //else that hashes to the same value.  Therefore we must increment the
103
	    //collision counter
104
	    collisions++;
105
 
106
	}
5 irasnyd 107
        return null;  // failure: table overflow
108
    }
109
 
7 irasnyd 110
    //Method to remove a key/value pair from the table.  This will leave a NIL behind
111
    //Precondition: key != null
112
    //Postcondition: return the old value if the key was found, then put a NIL in it's place
113
    //               return null if the key was not found in the table.
5 irasnyd 114
    public Object remove(Object key) {
7 irasnyd 115
        int h=hash(key); //hash the key
116
        for (int i=0; i<entries.length; i++) { //run once for every place in the table
117
            int j = nextProbe(h,i); //find the [first, next] place to put the value
5 irasnyd 118
            Entry entry=entries[j];
7 irasnyd 119
 
120
            if (entry==null) break; //break out of the loop, since the key was not found
121
            if (entry==NIL) continue; //keep going, since we found a NIL
122
            if (entry.key.equals(key)) { //we found the key we are looking for...
123
                Object oldValue=entry.value; //save value to return
124
                entries[j] = NIL; //replace the value with a NIL
125
                --size; //decrement size
5 irasnyd 126
                return oldValue;  // success
127
            }
128
        }
129
        return null;  // failure: key not found
130
    }
131
 
7 irasnyd 132
    //Method to access private variable size
133
    //Precondition: none
134
    //Postcondition: return size
5 irasnyd 135
    public int size() {
136
        return size;
137
    }
138
 
9 irasnyd 139
    //Method to access private variable collisions
140
    //Precondition: none
141
    //Postcondition: return collisions
142
    public int collisions() {
143
    	return collisions;
144
    }
145
 
10 irasnyd 146
    //Method to set the probeType variable
147
    //
148
    //0 == Linear Probing (step size 1) DEFAULT
149
    //1 == Prime  Probing (step size 3)
150
    //2 == Prime  Probing (step size 5)
151
    //3 == Prime  Probing (step size 7)
152
    //4 == Prime  Probing (step size 11)
153
    //5 == Quadratic Probing
154
    //6 == Double Hashing
155
    //
156
    //Precondition: 0 <= newValue <= 6
157
    //Postcondition: probeType will be changed
158
    //WARNING: Please do NOT change probeType while in a test run
159
    public void setProbeType( int newValue ) {
160
    	if( newValue < 0 || newValue > 6 ) { newValue = 0; } //put in for safety, just in case
161
	probeType = newValue;
162
    }
163
 
7 irasnyd 164
    //A private class which will hold a key/value pair
5 irasnyd 165
    private class Entry {
166
        Object key, value;
167
        Entry(Object k, Object v) { key=k; value=v; }
168
    }
169
 
7 irasnyd 170
    //our implementation of the hash() function. Takes the Object.hashCode() method
171
    //and chops off the sign bit
172
    //Precondition: None (we check for key == null)
173
    //Postcondition: throw an IllegalArgumentException() if the key == null
174
    //               return an integer hash for the given key
5 irasnyd 175
    private int hash(Object key) {
176
        if (key==null) throw new IllegalArgumentException();
177
        return (key.hashCode() & 0x7FFFFFFF) % entries.length;
178
    }
7 irasnyd 179
 
180
    //Method to implement linear probing
181
    //Precondition: h != null; i != null
182
    //Postcondition: return the next place to try and put the value
5 irasnyd 183
    private int nextProbe(int h, int i) {
10 irasnyd 184
 
185
	int returnVal = 0; //set to zero to stop compiler error
8 irasnyd 186
 
10 irasnyd 187
	switch( probeType ) {
188
		case 0: { //linear probing
189
			returnVal = (h + i)%entries.length;
190
			break;
191
		}
192
 
193
		case 1: { //Prime Probing ( p=3  )
194
			returnVal = (h + (i * 3 ))%entries.length; 
195
			break;
196
		}
197
 
198
		case 2: { //Prime Probing ( p=5  )
199
			returnVal = (h + (i * 5 ))%entries.length;
200
			break;
201
		}
202
 
203
		case 3: {  //Prime Probing ( p=7  )
204
			returnVal = (h + (i * 7 ))%entries.length;
205
			break;
206
		}
207
 
208
		case 4: { //Prime Probing ( p=11 )
209
			returnVal = (h + (i * 11))%entries.length;
210
			break;
211
		}
212
 
213
    		case 5: { //Quadratic Probing
214
			returnVal = (h + (i * i ))%entries.length;
215
			break;
216
		}
8 irasnyd 217
 
10 irasnyd 218
		//I am aware that my implementation of Double Hashing (which follows) is
219
		//wasteful in terms of computation time (we must create the array "step"
220
		//each and every time this code is run.  I did it this way to abstract the
221
		//method used to find the nextProbe() location from the put method.
222
		case 6: { //Double Hashing
223
			int[] step = { 2,3,5,7,11 };
224
			int stepSize = step[h%4];
225
			returnVal = (h + (i * stepSize))%entries.length;
226
			break;
227
		}
228
	}
229
	//return the final value
230
	return returnVal;
8 irasnyd 231
 
5 irasnyd 232
    }
233
 
7 irasnyd 234
    //Method to rehash the entire table.  This will get rid of NIL's
235
    //Precondition: none
236
    //Postcondition: entries will be twice the size plus one (ensures odd size)
237
    //               all NIL will be gone
238
    //               all values will be re-hash()ed
5 irasnyd 239
    private void rehash() {
240
        Entry[] oldEntries = entries;
241
        entries = new Entry[2*oldEntries.length+1];
242
        for (int k=0; k<oldEntries.length; k++) {
243
            Entry entry=oldEntries[k];
244
            if (entry==null || entry==NIL) continue;
245
            int h=hash(entry.key);
246
            for (int i=0; i<entries.length; i++) {
247
                int j = nextProbe(h,i);
248
                if (entries[j]==null) {
249
                    entries[j] = entry;
250
                    break;
251
                }
252
            }
253
        }
254
        used = size;
255
    }
256
}