PrioriryQueue<E> and Queue<E> reported as incompatible types

Answered

Using IntelliJ Ultimate 2024.3.5, the following code has red marks:

import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

public class Example {

    public record Foo(String s) {
    }

    public void example1() {
        Queue<Foo> queue = new PriorityQueue<>();
    }

    public void example2() {
        PriorityQueue<Foo> queue = new PriorityQueue<>();
        List<String> list = queue.stream()
                .map(foo -> foo.s())
                .toList();
    }

}

 

example1 reports: no instance(s) of type variable(s) E exist so that PriorityQueue<E> conforms to Queue<Foo>

example2 reports: Cannot resolve method 'stream' in 'PriorityQueue', then fails to determine the type in the map() call because the stream type was not established.

I expect that both of these cases are valid, and I have verified that they compile successfully. PriorityQueue extends AbstractQueue which implements the Queue interface and AbstractQueue extends AbstractCollection which implements Collection which provides the stream() method. Am I missing something, or is there a workaround for this situation?

0
3 comments

Hello,
You've hit upon a known limitation or quirk in some static analysis or type-checking tools, particularly when dealing with generics and inheritance hierarchies. Let's break down why these errors might be occurring and how to address them.
 

 

 

 

 

 

 

0
Looks like https://youtrack.jetbrains.com/issue/IDEA-227525/Wrong-object-type-in-stream-causes-cannot-resolve-method-error but it was fixed long time ago.

Would below action make any differences?

File | Invalidate Caches.. | enable Clear file system cache and Local History option > Invalidate and Restart
0

Bond Han Your suggestion resolved the problem. Thanks!

0

Please sign in to leave a comment.