[fix] java: incompatible types: double cannot be converted to java.lang.Integer Generics


Java incompatible types errors:
java: incompatible types: double cannot be converted to java.lang.Integer
java: incompatible types: double cannot be converted to java.lang.Integer
java: incompatible types: float cannot be converted to java.lang.Double
java: incompatible types: int cannot be converted to java.lang.Boolean
java: incompatible types: byte cannot be converted to java.lang.Character

One of the reasons for the incompatible types is that you are using generics with collections and passing a wrong type to a specific type,

Exmple:
1. public static void main(String[] args) {
2.   List<Integer> list = new ArrayList<>();
3.   list.add(10.0);
4. }

In the above example, we have a list of type Integer, and at line 3 we are trying to add a double to it, so you get a type safety compilation type error,

Required type: Integer
Provided: double

But if this happens at runtime you will get an error,

incompatible types double cannot be converted to java.lang.Integer
Fix:

For this example, if you expect the types for the list to hold doubles as well, change the type from Integer -> Double.

Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.