Subversion Repositories programming

Rev

Go to most recent revision | 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();
7 irasnyd 67
        int h=hash(key); //hash the key
68
        for (int i=0; i<entries.length; i++) { //run once for each place in the Table
69
            int j = nextProbe(h,i); //get the [first, next] place to try putting the value
70
            Entry entry=entries[j]; //get the Entry at j (where we want to put value)
71
 
72
	    //if entry[j] == null then we have found a good place to put value!
73
	    if (entry==null) {
5 irasnyd 74
                entries[j] = new Entry(key,value);
75
                ++size;
76
                ++used;
77
                return null;  // insertion success
78
            }
7 irasnyd 79
 
80
	    //if entry[j] == NIL then we must continue to probe for a new place,
81
	    //otherwise we will confuse the remove() and get() methods
9 irasnyd 82
            if (entry==NIL) { collisions++; continue; }
7 irasnyd 83
 
84
	    //if entry[j].key == key then we need to update the record
5 irasnyd 85
            if (entry.key.equals(key)) {
86
                Object oldValue=entry.value;
87
                entries[j].value = value;
88
                return oldValue;  // update success
89
            }
9 irasnyd 90
 
91
	    //if we get here, we have had a collision that is not a NIL,
92
	    //and is not an Entry that needs updating, therefore it is something
93
	    //else that hashes to the same value.  Therefore we must increment the
94
	    //collision counter
95
	    collisions++;
96
 
97
	}
5 irasnyd 98
        return null;  // failure: table overflow
99
    }
100
 
7 irasnyd 101
    //Method to remove a key/value pair from the table.  This will leave a NIL behind
102
    //Precondition: key != null
103
    //Postcondition: return the old value if the key was found, then put a NIL in it's place
104
    //               return null if the key was not found in the table.
5 irasnyd 105
    public Object remove(Object key) {
7 irasnyd 106
        int h=hash(key); //hash the key
107
        for (int i=0; i<entries.length; i++) { //run once for every place in the table
108
            int j = nextProbe(h,i); //find the [first, next] place to put the value
5 irasnyd 109
            Entry entry=entries[j];
7 irasnyd 110
 
111
            if (entry==null) break; //break out of the loop, since the key was not found
112
            if (entry==NIL) continue; //keep going, since we found a NIL
113
            if (entry.key.equals(key)) { //we found the key we are looking for...
114
                Object oldValue=entry.value; //save value to return
115
                entries[j] = NIL; //replace the value with a NIL
116
                --size; //decrement size
5 irasnyd 117
                return oldValue;  // success
118
            }
119
        }
120
        return null;  // failure: key not found
121
    }
122
 
7 irasnyd 123
    //Method to access private variable size
124
    //Precondition: none
125
    //Postcondition: return size
5 irasnyd 126
    public int size() {
127
        return size;
128
    }
129
 
9 irasnyd 130
    //Method to access private variable collisions
131
    //Precondition: none
132
    //Postcondition: return collisions
133
    public int collisions() {
134
    	return collisions;
135
    }
136
 
10 irasnyd 137
    //Method to set the probeType variable
138
    //
139
    //0 == Linear Probing (step size 1) DEFAULT
140
    //1 == Prime  Probing (step size 3)
141
    //2 == Prime  Probing (step size 5)
142
    //3 == Prime  Probing (step size 7)
143
    //4 == Prime  Probing (step size 11)
144
    //5 == Quadratic Probing
145
    //6 == Double Hashing
146
    //
147
    //Precondition: 0 <= newValue <= 6
148
    //Postcondition: probeType will be changed
149
    //WARNING: Please do NOT change probeType while in a test run
150
    public void setProbeType( int newValue ) {
151
    	if( newValue < 0 || newValue > 6 ) { newValue = 0; } //put in for safety, just in case
152
	probeType = newValue;
153
    }
154
 
7 irasnyd 155
    //A private class which will hold a key/value pair
5 irasnyd 156
    private class Entry {
157
        Object key, value;
158
        Entry(Object k, Object v) { key=k; value=v; }
159
    }
160
 
7 irasnyd 161
    //our implementation of the hash() function. Takes the Object.hashCode() method
162
    //and chops off the sign bit
163
    //Precondition: None (we check for key == null)
164
    //Postcondition: throw an IllegalArgumentException() if the key == null
165
    //               return an integer hash for the given key
5 irasnyd 166
    private int hash(Object key) {
167
        if (key==null) throw new IllegalArgumentException();
168
        return (key.hashCode() & 0x7FFFFFFF) % entries.length;
169
    }
7 irasnyd 170
 
171
    //Method to implement linear probing
172
    //Precondition: h != null; i != null
173
    //Postcondition: return the next place to try and put the value
5 irasnyd 174
    private int nextProbe(int h, int i) {
10 irasnyd 175
 
176
	int returnVal = 0; //set to zero to stop compiler error
8 irasnyd 177
 
10 irasnyd 178
	switch( probeType ) {
179
		case 0: { //linear probing
180
			returnVal = (h + i)%entries.length;
181
			break;
182
		}
183
 
184
		case 1: { //Prime Probing ( p=3  )
185
			returnVal = (h + (i * 3 ))%entries.length; 
186
			break;
187
		}
188
 
189
		case 2: { //Prime Probing ( p=5  )
190
			returnVal = (h + (i * 5 ))%entries.length;
191
			break;
192
		}
193
 
194
		case 3: {  //Prime Probing ( p=7  )
195
			returnVal = (h + (i * 7 ))%entries.length;
196
			break;
197
		}
198
 
199
		case 4: { //Prime Probing ( p=11 )
200
			returnVal = (h + (i * 11))%entries.length;
201
			break;
202
		}
203
 
204
    		case 5: { //Quadratic Probing
205
			returnVal = (h + (i * i ))%entries.length;
206
			break;
207
		}
8 irasnyd 208
 
10 irasnyd 209
		//I am aware that my implementation of Double Hashing (which follows) is
210
		//wasteful in terms of computation time (we must create the array "step"
211
		//each and every time this code is run.  I did it this way to abstract the
212
		//method used to find the nextProbe() location from the put method.
213
		case 6: { //Double Hashing
214
			int[] step = { 2,3,5,7,11 };
215
			int stepSize = step[h%4];
216
			returnVal = (h + (i * stepSize))%entries.length;
217
			break;
218
		}
219
	}
220
	//return the final value
221
	return returnVal;
8 irasnyd 222
 
5 irasnyd 223
    }
224
 
7 irasnyd 225
    //Method to rehash the entire table.  This will get rid of NIL's
226
    //Precondition: none
227
    //Postcondition: entries will be twice the size plus one (ensures odd size)
228
    //               all NIL will be gone
229
    //               all values will be re-hash()ed
5 irasnyd 230
    private void rehash() {
231
        Entry[] oldEntries = entries;
232
        entries = new Entry[2*oldEntries.length+1];
233
        for (int k=0; k<oldEntries.length; k++) {
234
            Entry entry=oldEntries[k];
235
            if (entry==null || entry==NIL) continue;
236
            int h=hash(entry.key);
237
            for (int i=0; i<entries.length; i++) {
238
                int j = nextProbe(h,i);
239
                if (entries[j]==null) {
240
                    entries[j] = entry;
241
                    break;
242
                }
243
            }
244
        }
245
        used = size;
246
    }
247
}