Home > Enterprise >  HashMap.get returns true instead of an element
HashMap.get returns true instead of an element

Time:12-11

So I'm trying to make a program that will count the number of times a unique word appears in a small file using HashMap. However, when I try to increase the count on a repeating word by using .get(key) on my HashMap, it returns true instead of the integer value that I want to cast to. How can I get my code to return the value instead of a boolean? Here's my code so far:

public class CountWords
{
public static void main (String[] args) {
    Map<String, Object> words = new HashMap<>();
    ArrayList<FindCommons> list = new ArrayList<>();
    
    read(words, list);
    
    for (int i = 0; i < list.size(); i  ) {
        System.out.println(list.get(i));
    }
}

public static void read (Map<String, Object> words, ArrayList<FindCommons> list) {
    try {
        BufferedReader input = new BufferedReader (new FileReader ("file.txt"));
        String line = "";
        while ((line = input.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(line);

            while (st.hasMoreTokens()) {
                line = st.nextToken();
                
                if (words.containsKey(line)) {
                    System.out.println(words.get(line)); //this returns boolean
                    //int count = (int) words.get(line));
                    words.put(line, list.add(new FindCommons(1, line)));
                }
                else {
                    words.put(line, list.add(new FindCommons(1, line)));
                    
                }
            }
        }

        input.close();
    }
    catch (FileNotFoundException e){
    }
    catch (IOException e){ 
    }
}
}

My FindCommons class:

import java.util.ArrayList; public class FindCommons{

private String word;
private int count;

public FindCommons(int count, String word) {
    this.count = count;
    this.word = word;
}

public int getNumber() {
    return count;
}

public String getWord() {
    return word;
}

public String toString() {
    return String.format("%-20s ]", word, count);
}

}

CodePudding user response:

You have used words.put(line, list.add(new FindCommons(1, line))); to add the items to the HashMap. The problem is, that list.add() returns a boolean value, so it puts the Boolean into the words HashMap.

CodePudding user response:

list.add(new FindCommons(1, line))

  •  Tags:  
  • java
  • Related