eclipse-jdt / eclipse-jdt/eclipse.jdt.core
Incorrect unnecessary cast warning from ECJ
- Dominant language
- Java
- Stars
- 237
- Forks
- 195
- Avg merge
- 1d 12h
- Merged PRs (30d)
- 47
Description
This issue comes from https://bugs.eclipse.org/bugs/show_bug.cgi?id=569616
The problem still exists in 2024-12.
When I call a generics method from within a stream I might need a cast. But Eclipse thinks it doesn't and so it suggests to remove the cast. Following this advice will lead to a compile error.
If I have the code
```
public class GenericsCast {
public static void main(String[] args) throws Exception {
Set input = Set.of("1", "2", "3");
Set result = createFoos(input);
System.out.println(result);
}
private static Set createFoos(Set input) {
return input.stream().map(s -> {
return (Foo) createFoo(s); // <== Warning
}).collect(Collectors.toSet());
}
static class Foo {
public final String s;
public Foo(String s) {
this.s = s;
}
}
static E createFoo(String s) {
@SuppressWarnings("unchecked")
E result = (E) new Foo(s);
return result;
}
}
```
then Eclipse will show me a warning "Unnecessary cast from GenericsCast.Foo to GenericsCast.Foo".
The quickfix will then change the method to
```
private static Set createFoos(Set input) {
return input.stream().map(s -> { // <== Error
return createFoo(s);
}).collect(Collectors.toSet());
}
```
which will show an error "Type mismatch: cannot convert from Set to Set".
I'm not entirely sure where the problem is, but note that
```
private static Set createFoos(Set input) {
return input.stream().map(s -> {
Foo foo = createFoo(s);
return foo;
}).collect(Collectors.toSet());
}
```
works fine.
The quickfix suggestion:

After the quickfix:

Contributor guide
Assessment
This issue has not been assessed yet.