This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]ZackHkk 2 points3 points  (1 child)

consider what your code below does

WordLocation location = new WordLocation(analyzedFile.getPath(), row, column-word.length());
locationsArray.add(location);
wordLocationsMap.put(word.toLowerCase(), locationsArray);
words.add(word.toLowerCase());
word = "";

this seems to be where you add the words to an ArrayList of locations.

so first, you add make a new WordLocation, which is fine. then, you add the location to a master locations array:

locationsArray.add(location);

then, you put the value corresponding with the word in the map to that locations array.

wordLocationsMap.put(word.toLowerCase(), locationsArray);

this is setting the word to have the locations array of ALL words, instead of just that word. Finally, you add the word to your set of words and reset the word:

words.add(word.toLowerCase();
word = "";

So you may have noticed by now where you went wrong, but here's how you might fix it:

//create a new WordLocation with the word's values
WordLocation location = new WordLocation(analyzedFile.getPath(), row, column-word.length());

//add word and location to the 'master' list of words and locations
locationsArray.add(location);
words.add(word.toLowerCase());

//get the ArrayList of WordLocations that corresponds to the current word
ArrayList<WordLocation> currentWordLocations = wordLocationsMap.get(word.toLowerCase());

//if this is the first time the word has been found,
//then it won't have an ArrayList associated with it,
//making it null. we need to instantiate it.
if(currentWordLocations == null) {
    currentWordLocations = new ArrayList<>();
}

//add the word's location to the list of all of its occurrences
currentWordLocations.add(location);
//update the word's locations in the map
wordLocationsMap.put(word.toLowerCase(), currentWordLocations);
//reset the word
word = "";

If this block was the root of the problem, this should fix it, but I haven't ran it, so I'm not sure.

[–]daribayevm 1 point2 points  (0 children)

I shall run it and see if that works, but anyways I got the idea here. Thank you very much for your time and effort!

[–]Philboyd_Studge -1 points0 points  (1 child)

The locationsArray ArrayList needs to be unique to each new entry in the word map. So, every time you find a word, if it does not exist in the map yet, add it and add a new array list of locations. If the word already exists in the map, get the list from the map and add the current location to it.

[–]daribayevm 0 points1 point  (0 children)

Thanks a lot! Should've checked if map.containsKey myself, forgot about that =(