Java Error 8 Incompatible Types

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

MyEntity is a marker interface.

The above code works fine in java-7 (java version "1.7.0_91", to be precise), but not in

In Java8, I get the following exception:

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

+7
java java-7 java-8
source share
2 answers

Your code should not run in either Java 7 or Java 8 because you are trying to pass an ArrayList<Object> (the type returned by the constructor) to List<? extends MyEntity> List<? extends MyEntity> , and it doesn't make sense even at compile time (see this question ). This is why the compiler complains.

The following code compiles:

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

However, the compiler generates a warning because you are performing an unsafe conversion.

EDIT: As @Tom points out:

"Your code should not work in java 7" It should not, but it worked because the compiler checks were still a bit erroneous in this version. This has been fixed in Java 8, so it now fails.

+11
source share

Java 8 has changed a lot regarding type inference and related items. Thus, it is not surprising that some edge cases (for example, shadow casts) suddenly become invalid.

Whatever the reason, you can still use your list, but it's a little more ugly than before:

(List<? extends MyEntity>) (List) new ArrayList<>(removedObjs);

As stated in a comment by Peter Lowry, this can be written even shorter because

(List) new ArrayList<>(removedObjs);

+8
source share

All Articles