I'm writing a program to count how many times each unique word appears in a text file, then return the word that occurred the most times along with how many times it occurred. Because I don't know how many different words there will be I cannot use an array since I can't predict how big it will need to be. Therefore I used two parallel ArrayLists. myWords is a list of strings and myFreqs is a list of ints, such that each index in myFreqs contains the number of occurrences of the word stored in the same index of myWords.
To do this I am trying to write a for loop that identifies the index in myFreqs which contains the highest value. I am struggling to write this loop though because ArrayList has no .length() method so I'm not sure the best way to write the stop condition in the loop. I have tried converting the ArrayList to an Array using
myFreqs.toArray(<Integer> array);
so that I can get the length of the array but this is giving me compile-time errors. I have tried several slightly different versions of the above and I get either "illegal start of expression" errors or “A Non-static method cannot be referenced from a static context” errors. I am getting the feeling that there is a much simpler and more direct way to achieve what I want that I am overlooking.
private ArrayList<String> myWords;
private ArrayList<Integer> myFreqs;
public int findIndexOfMax () {
int[] array = new Array[100];
myFreqs.toArray(<Integer> array);
int maxVal = 0;
int maxIdx = -1;
for (int k = 0; k < array.length; k++) {
if (array[k] > maxVal) {
maxVal = array[k];
maxIdx = k;
}
}
return maxIdx;
}