I am trying to read in a large block of text and store each unique word and the number of times it came up in the text. To do this I made an array list of a Word class. The Word class simply stores the word and number of times it came up. To avoid duplicates of the same word I use the .contains() function to see if I have already processed a word before, but for some reason, .contains() is not working.
class Main
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("poe.text");
Scanner f = new Scanner(file);
ArrayList<Word> words = new ArrayList<Word>();
int total = 0;
while(f.hasNext())
{
Word temp = new Word(f.next().toLowerCase().trim());
//System.out.println("temp is "+temp.getWord());
total++;
if(words.contains(temp))
{
words.get(words.indexOf(temp)).up();
} else
{
words.add(temp);
}
}
for(Word w:words)
{
System.out.println(w.toString());
}
}
}
The if statement never evaluates to true and every word is added to the words ArrayList even if it is already present.
Map<String, Integer>orMap<Word, Integer>. In your case my guess is that you have not overriddenequalsofWordclass correctly.containsdocs. It will tell you that in absence of the respective custom overrides, it will use the default comparison method, which is reference. A new instance will always have a unique reference, regardless of the value of the instance.