Java字典方法getTextDefinition实现中出现NullPointerException的原因及问题排查
getTextDefinition Method Problem Overview
You're trying to implement the getTextDefinition method that checks if a word exists in a MasterDictionary (a subclass of TreeMap<String, Word>) and returns its definition, or a "No definition found" message if it doesn't exist. However, you're hitting a NullPointerException when searching for a word that isn't in the dictionary, and your logic isn't working as expected.
Let's break down the issues in your code and fix them step by step.
Key Issues Causing the Error
1. Incorrect Use of containsValue()
Your code uses this.containsValue(text) where text is a String, but your TreeMap stores Word objects as values. Since containsValue() checks for equality between the argument and the map's values, and your Word class doesn't override equals() to compare against strings, this check will always return false—even for words that exist in the map.
This means your code always falls into the second if block:
if(this.containsValue(text) == false){ definition = get(text).toString(); }
When the word doesn't exist (like "half taste"), get(text) returns null, and calling toString() on null throws the NullPointerException.
2. Wrong Key Type for get()
In the first if block, you use this.get(word) where word is a Word object. But your TreeMap uses strings (word text) as keys (from super.put(word.getText(), word)), not Word objects. So get(word) will never find a match, even if the word exists.
3. Unused Code & Logical Flaws
- The line
word.getText();does nothing—you call the method but don't store or use its return value. - Even if the first
ifblock ran correctly, you don't assign the result ofget()to yourwordvariable, sodefinition = word.toString()would use the originalWordinstance you created (with "No definition found") instead of the one from the dictionary.
4. Broken compareTo() Method
Your Word class's compareTo() method has a mistake:
@Override public int compareTo(Object o) { int r; r = getText().compareTo(getText()); return r; }
This compares the word's text to itself, always returning 0. This will cause issues with TreeMap sorting and equality checks. It should compare the current word's text to the other object's text instead.
Fixed Code
Corrected getTextDefinition Method
Here's the revised method that addresses all the issues:
public String getTextDefinition(String text){ // Create a Word instance to get the lowercase text (matches how keys are stored) Word inputWord = new Word(text); String wordKey = inputWord.getText(); String definition; if(this.containsKey(wordKey)){ // Get the existing Word from the dictionary and use its toString() Word dictionaryWord = this.get(wordKey); definition = dictionaryWord.toString(); } else { // Use the inputWord's toString() which has "No definition found" definition = inputWord.toString(); } return definition; }
Fixed compareTo() Method in Word Class
Update the compareTo() method to properly compare words:
@Override public int compareTo(Object o) { if (!(o instanceof Word)) { throw new ClassCastException("Cannot compare Word with non-Word object"); } Word otherWord = (Word) o; return this.getText().compareTo(otherWord.getText()); }
Explanation of Fixes
- Use
containsKey()instead ofcontainsValue(): We check if the lowercase word text exists as a key in the map (since that's how we stored entries withsuper.put(word.getText(), word)). - Correct Key for
get(): We use the lowercasewordKeystring to fetch theWordobject from the map, which matches the key type. - Properly Assign Dictionary Word: When the word exists, we retrieve the actual
Wordfrom the map and use itstoString()instead of the original input instance. - Fixed
compareTo(): Now it correctly compares the text of twoWordobjects, ensuringTreeMapworks as expected for sorting and ordering.
Testing the Fixed Code
When you run the main method now, you'll get your expected output:
half: Word Definition: In an equal part or degree; half nelson: Word Definition: A hold in which one arm is thrust under the corresponding armof the opponent. half seas over: Word Definition: Half drunk. [Slang: used only predicatively.] Spectator. half taste: Word Definition: No definition found.
内容的提问来源于stack exchange,提问作者Nadia

