-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashIndex.java
More file actions
85 lines (70 loc) · 2.59 KB
/
Copy pathHashIndex.java
File metadata and controls
85 lines (70 loc) · 2.59 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.*;
import java.io.*;
/**
* Hash Index Implementation
*
* @author Tafita Rakotozandry & Taylor Strong & Khalid Al-Motaery
* @version 11/28/2020
*/
public class HashIndex extends IndexAbstract implements Index {
private static HashMap <String, TreeSet<Integer>> hashMap;
public static ArrayList <String> list;
/**
* Constructor for the HashIndex class
*/
public HashIndex() {
hashMap = new HashMap <String, TreeSet<Integer>> ();
}
/**
* Creates and writes the output file
*/
public void createOutFile() {
try {
//create the output file
File outputFile = new File("HashOutput.txt");
outputFile.createNewFile();
//set the key
Set <String> s = hashMap.keySet();
list = new ArrayList <String> ();//create an arrayList
for (String key: s) {//add all the key in the arrayList
list.add(key);
}
//sort the list
//sort needed to be performed because hasmap is not sorted
Collections.sort(list);
//write output in the line
PrintWriter writeFile = new PrintWriter(outputFile);
Iterator <String> itr = list.iterator();
while (itr.hasNext()) {
String line = itr.next();
writeFile.println(line + " " + hashMap.get(line));
}
writeFile.close();
} catch (Exception e) {
System.out.println("An error has occurred " + e);
}
}
/**
* Adds a word in the HashMap
*
* @param w the word to add to the HashMap
* @param k the line number of the word
* @return true or false depending on if the addition was successful or not
*/
public boolean add(String w, Integer k) {
if (!isEnglish(w)) { //return false if the word is not in english
return false;
}
if (!hashMap.containsKey(w)) { //if the word is not the hash map
hashMap.put(w, new TreeSet <Integer> ()); //put the word in the hashmap
hashMap.get(w).add(k); //add the line corresponding to the word in the hashmap
return true;
} else if (hashMap.containsKey(w)) { //if the word is in the hash map
if (!hashMap.get(w).contains(k)) {//if the word is in the hash map
hashMap.get(w).add(k); //add the line corresponding to the word in the hashmap
return true;
}
}
return false;
}
}