[Solved] Java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double

When from map < String,Object> The above exception occurs when the key value is taken out of

public static void main(String[] args) {
		Map<String, Object> map = new HashMap<>();
		map.put("a", 1);
		map.put("b", 2);
		double value = (double) map.get("a");
		System.out.println(value);
}

Map< String, Object> map = new HashMap<>() In order to avoid the above problems, we can judge by instanceof

public static void main(String[] args) {
		Map<String, Object> map = new HashMap<>();
		map.put("a", 1);
		map.put("b", 2);
		Object object = map.get("a");
		if (object instanceof Integer) {
			System.out.println("true");
		}
}

according to the console output, the return type of map.get (“a”) is known as integer

solution: use tostring()/string. Valueof() to convert it to string first and then to the required data type

public static void main(String[] args) {
		Map<String, Object> map = new HashMap<>();
		map.put("a", 1);
		map.put("b", 2);
		Double a = Double.valueOf(map.get("a").toString());
		Double b = Double.valueOf(map.get("b").toString());
		System.out.println("a:" + a);
		System.out.println("b:" + b);
}

 

Similar Posts: