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>
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.
There are 3 types of Errors: Syntax Error. Runtime Error. Logical Error.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With