Home ClassCastException
Post
Cancel

ClassCastException

ClassCastException

Occurrence: When solving a Valid Anagram problem in Leetcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
    public boolean isAnagram(String s, String t) {
        HashMap<Character, Integer> sMap = new HashMap<Character, Integer>();
        HashMap<Character, Integer> tMap = new HashMap<Character, Integer>();
        if(s.length() != t.length()) return false;
        
        char c = ' ';
        Object val;
        
        for(int i = 0; i < s.length(); i++){
            c = s.charAt(i);
            val = sMap.get(c);
            
            if(val == null) sMap.put(c, 1);
            else sMap.put(c, (int)val + 1);  // ERROR
            
            c = t.charAt(i);
            val = tMap.get(c);
            
            if(val == null) tMap.put(c, 1);
            else tMap.put(c, (int)val + 1);
            
        }
        
        for(int i = 0; i < s.length(); i++){ // ERROR
            if(sMap.get(s.charAt(i)) != tMap.get(t.charAt(i))){
                return false;
            } 
        }
        return true;
    }
}

When the get method of a HashCode returns an Object and attempts to cast it to an INT,
a RuntimeError occurs and the count is not updated, resulting in incorrect results.
So the result is also incorrect.

Additionally, for the last part of the comparison, the != operator brings an incorrect value, so it is better to use the equals method



Reference:
https://docs.oracle.com/javase/8/docs/api/java/lang/ClassCastException.html
https://leetcode.com/problems/valid-anagram/

This post is licensed under CC BY 4.0 by the author.