This repository was archived by the owner on Dec 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDictionary.java
More file actions
68 lines (60 loc) · 2 KB
/
Copy pathDictionary.java
File metadata and controls
68 lines (60 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* This class represents a dictionary: a data structure used for storing values associated with a key.
* It stores objects of the class DictionaryPair (which contains two elements, key and value) in a vector.
* One can search based on the key.
* Author: Seppe Lampe
*/
public class Dictionary
{
private Vector data;
private class DictionaryPair implements Comparable
{
private Comparable key;
private Comparable value;
public DictionaryPair (Comparable someKey, Comparable someValue)
{
this.key = someKey;
this.value = someValue;
}
@Override
public int compareTo(Object comp) { //O(1)
return this.getKey().compareTo(((DictionaryPair)comp).getKey());
}
public Comparable getKey() { //O(1)
return key;
}
public Comparable getValue() { //O(1)
return value;
}
public void setKey(Comparable newKey) { //O(1)
key = newKey;
}
public void setValue(Comparable newValue) { //O(1)
value = newValue;
}
}
public Dictionary() {
data = new Vector(5);
}
// Adds a key and value to the Dictionary
public void add(Comparable key,Comparable value) { //O(1)
int index = (findPosition(new DictionaryPair(key, 0)));
if (index == -1) data.addLast(new DictionaryPair(key, value));
else data.set(index, new DictionaryPair(key, value));
}
// Returns the position of the key in the Vector
public int findPosition(Comparable key) { //O(n)
DictionaryPair test = new DictionaryPair(key, 0);
for(int i=0;i<data.size();i++) {
if(((DictionaryPair)data.get(i)).compareTo(test) == 0) {
return i;
}
}
return -1;
}
// Search for a certain key and if it is present in the Dictionary then return the value, otherwise return null
public Comparable find(Comparable key) { //O(n)
int index = (findPosition(new DictionaryPair(key, 0)));
if (index > -1) return ((DictionaryPair)data.get(index)).getValue();
else return null;
}
}