Search code examples
javaarraylistcontains

Why is my contains function not detecting the element?


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.


Solution

  • In the Javadoc for List, the contains method uses the equals() method to evaluate if two objects are the same. have you implemented equals and hashcode in your words class ?

    Javadoc http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains%28java.lang.Object%29