Search code examples
javacasting

Why do I have to cast in "First Unique Character in a String" Problem?


This solution doesn't work.

 public int firstUniqChar(String s) {
    HashMap map = new HashMap<Character, Integer>();
    
    for(int i = 0; i < s.length(); i++){
        if(map.containsKey(s.charAt(i))){
            map.put(s.charAt(i), 2);
        }
        else{
            map.put(s.charAt(i), 1);
        }
    }
    
    for(int i = 0; i < s.length(); i++){
        
        if(map.get(s.charAt(i)) == 1){
            return i;
        }
    }
    
    return -1;
}

But it works now when I cast the value of the Hashmap to int

(int)map.get(s.charAt(i)) == 1

public int firstUniqChar(String s) {
    HashMap map = new HashMap<Character, Integer>();
    
    for(int i = 0; i < s.length(); i++){
        if(map.containsKey(s.charAt(i))){
            map.put(s.charAt(i), 2);
        }
        else{
            map.put(s.charAt(i), 1);
        }
    }
    
    for(int i = 0; i < s.length(); i++){
        
        if((int)map.get(s.charAt(i)) == 1){
            return i;
        }
    }
    
    return -1;
}

I used:

System.out.print(map.get(s.charAt(i)).getClass().getName());

to confirm that the value of the map should already be an integer so I don't understand why I am getting this error when I try to submit to leetcode without casting.


Solution

  • HashMap map = new HashMap<Character, Integer>();

    HashMap is a raw type, essentially equivalent to HashMap<Object, Object>. Hence the compiler cannot detect the type of the value being Integer unless you cast.

    Always specify the generic type at declaration, and you can use the diamond operator at the initialization side:

    HashMap<Character, Integer> map = new HashMap<>();
    

    You can also use the var keyword if you keep the type information at the right-hand side:

    var map = new HashMap<Character, Integer>();