Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Incompatible Types Error

Set<Object> removedObjs = new HashSet<>();
List<? extends MyEntity> delObjs = (List<? extends MyEntity>) new ArrayList<>(removedObjs);

MyEntity is marker interface.

Above code is working fine in java-7(java version "1.7.0_91", to be precise) but not in java-8(java version "1.8.0_77")

In Java8, I am getting the following exception:

incompatible types: ArrayList<Object> cannot be converted to List< ? extends MyEntity>

like image 775
LAXMIKANT MAHAJAN Avatar asked May 16 '16 08:05

LAXMIKANT MAHAJAN


People also ask

What solution is provided by Java for non compatible data types?

Narrowing or Explicit Conversion If we want to assign a value of a larger data type to a smaller data type we perform explicit type casting or narrowing. This is useful for incompatible data types where automatic conversion cannot be done.

What is type error in Java?

There are 3 types of Errors: Syntax Error. Runtime Error. Logical Error.


1 Answers

Your code should neither work in Java 7 nor in Java 8, because you are trying to cast an ArrayList<Object> (type returned from the constructor) to a List<? extends MyEntity> and it has no sense even at compile time (see this question). That's why the compiler is complaining.

The following code will compile:

Set<Object> removedObjs = new HashSet<>();
List<? extends Integer> delObjs = (List) new ArrayList<>(removedObjs);

However, the compiler will throw a warning since you are performing an unsafe conversion.

EDIT: As @Tom points out:

"Your code should not work in java 7" It shouldn't, but it worked, because the compiler checks were still a bit faulty in that version. This has been fixed in Java 8, that is why it now fails.

like image 140
zequihg50 Avatar answered Nov 17 '22 04:11

zequihg50