1

I got a problem even my professor couldn't solve after an hour of investigation: I have a map which stores a highscore value for each level, where the levels are saved as strings and the integer represents the highscore. Now, when I try to read the highscore for a level, I get this very weird problem: Upon calling the method to read the highscore, I get an error saying

java.lang.String cannot be cast to java.lang.Integer

The code is the following

public Map<String, Integer> highscores = new HashMap<>();
highscores.put("Level1", 35); //Example, we read it from a file
int highscore = highscores.get("Level1");

The error occurs in the third line. Does anyone have an idea why this happens? Integer.parseInt doesn't work either, as that method says it needs a String instead of an Integer as an argument, meaning the right hand side of the line is in fact an Integer. Any help is greatly appreciated.

Legofan431
  • 153
  • 2
  • 11
  • Possible duplicate of [How to convert Integer to int?](https://stackoverflow.com/questions/3571352/how-to-convert-integer-to-int) – ZeldaZach Jun 23 '17 at 14:18
  • 4
    "Example, we read it from a file" How do you read from the file? Please show that code; this code works just fine. – Andy Turner Jun 23 '17 at 14:18
  • 2
    No repro, I guess this is a simplified version, please post a [mcve]. Likely you're using a raw type somewhere? – Jorn Vernee Jun 23 '17 at 14:25
  • Is this maybe done on a JSF page or something? – Dominik Sandjaja Jun 23 '17 at 14:26
  • 1
    I've got my finger hovering over the dupe hammer for ["What is a raw type and why shouldn't we use it?"](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). – Andy Turner Jun 23 '17 at 14:26
  • When it says u need to cast it, then cast it. I guess when you read from a file, a sequence of chars it returned – Pushan Gupta Jun 23 '17 at 15:15
  • @Vidor Vistrom, that guess has no basis. Besides, you can't cast a `CharSequence` to `String` either. Besides, nothing in the message "says u [_sic_] need to cast it". Besides, "u" is not the way to spell "you" in English. Besides, typing those extra two characters will give your fingers some much-needed exercise. – Lew Bloch Jun 23 '17 at 15:43
  • Please adhere to the Java naming conventions. – Lew Bloch Jun 23 '17 at 15:44
  • [Yeah, no, that code doesn't give an error](http://ideone.com/LK1yRr). – Bernhard Barker Jun 24 '17 at 16:13

5 Answers5

1

Sounds like when you're reading the score from a file, it's reading it as a string and then trying to stick it into the HashMap as a String object instead of an Integer object. That's where this exception comes from:

java.lang.String cannot be cast to java.lang.Integer
sorayadragon
  • 1,087
  • 7
  • 21
1

When you say that you read it from a file, are you sure that it is an Integer and not a String?

The line of code

int highscore = highscores.get("Level1");

does two things and is similar to the following:

Integer highscoreObj = highscores.get("Level1");
int highscore = highscoreObj.intValue();

What happens when you try this one?

Florian S.
  • 386
  • 1
  • 12
  • "What happens when you try this one?" Exactly the same, because that's just manually unboxing instead of letting the compiler do it. The problem is that `highscores.get("Level1")` isn't an `Integer`. – Andy Turner Jun 23 '17 at 14:24
1

I just found the answer in the reading of the file, no idea how I overlooked this one! It said

highscores = gson.fromJson(new BufferedReader(
                                new FileReader("ressources/highscores.json")),
                    new TypeToken<Map<String, String>>() {}.getType()); 

Which obviously made the value of the Map a String. Changing the second argument to Map<String, Integer> solves the problem. Thank you for the very fast responses!

sf_
  • 1,138
  • 2
  • 13
  • 28
Legofan431
  • 153
  • 2
  • 11
  • 1
    But surely that wouldn't be type correct, unless the `highscores` map is raw in that case? Please show your declaration of `highscores`. – Andy Turner Jun 23 '17 at 14:27
  • the decleration of the Map can be seen in the question – Legofan431 Jun 23 '17 at 14:29
  • @AndyTurner Here just a `Type` is passed, the compiler can't infer the return type from that, so it's inferred from the assignee, which would be `Map` – Jorn Vernee Jun 23 '17 at 14:29
0

Seems the code that you have mentioned here is perfectly fine, this problem is most likely occurring when you are reading from a file.

Are you sure you are converting whatever you read from the file into an Integer before doing a put() into the Map?

May be you are trying to do something like this:

public class Test {
    public static Map<String, Integer> highscores = new HashMap<>();

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(Test.class.getResourceAsStream("input.txt")));

        String line = null;
        while ((line = reader.readLine()) != null) {
            String[] tokens = line.split(",");
            highscores.put(tokens[0], Integer.parseInt(tokens[1]));
        }

        System.out.println(highscores.get("Level1"));
        System.out.println(highscores.get("Level2"));
    }
}

Input file

Level1,35
Level2,65

Output

35
65
BhalchandraSW
  • 714
  • 5
  • 13
0

You should determine the element of highscores type.Like following code:

System.out.println(highscores.get("Level1").getClass());

In my guess,the result of above code is not class java.lang.Integer,if the result is Class java.lang.String

you can modify your code to following:

    Map<String, Integer> highscores = new HashMap<>();
    highscores.put("Level1", 35); //Example, we read it from a file
    Object item=highscores.get("Level1");
    if(item.getClass().equals(String.class)) {
        highscore= Integer.parseInt((String) item);
    }else if(item.getClass().equals(Integer.class)){
        highscore=(Integer)item;
    }
dabaicai
  • 999
  • 8
  • 9