开发者

How to create MinMaxPriorityQueue with nested generic parameters?

开发者 https://www.devze.com 2023-02-11 18:17 出处:网络
How do I create a MinMaxPriorityQueue with nested generic parameters like: MinMaxPriorityQueue<AtomicCountHolder<E>> sortedHeap;

How do I create a MinMaxPriorityQueue with nested generic parameters like:

MinMaxPriorityQueue<AtomicCountHolder<E>> sortedHeap;

I've tried all kinds of variations I could think of with the static create() method, and the Builder to no 开发者_Python百科avail. It works with

MinMaxPriorityQueue<Integer> s = MinMaxPriorityQueue. <Integer>create();

But not with nested generics. Any clues would be helpful.


MinMaxPriorityQueue.create() imposes a restriction that the generic type must implement the Comparable interface, i.e. there is a natural ordering of instances of that type.

I assume AtomicCountHolder<E> does not implement Comparable. In this case you must provide a custom Comparator which defines an ordering of your types. For example,

MinMaxPriorityQueue<AtomicCountHolder<E>> sortedHeap = MinMaxPriorityQueue.orderedBy(Ordering.natural().onResultOf(someFunction)).create();

This assumes you have a Function that takes AtomicCountHolder<E> and returns something that is Comparable, like an Integer. Assuming E is comparable, you could write a Function that takes a AtomicCountHolder<E extends Comparable<? super E>> and returns whatever the AtomicCountHolder refers to.

What is AtomicCountHolder btw? Is it like AtomicInteger?


EDIT: @sjr's answer is right, then — your AtomicCountHolder<E> class needs to implement Comparable<AtomicCountHolder<E>>. AtomicInteger doesn't implement Comparable<AtomicInteger>, by the way.


In addition, E needs to be a declared type. You either need to define the priority queue in a class with a parameter type named E:

public class Example<E> {
  MinMaxPriorityQueue<AtomicCountHolder<E>> sortedHeap =
      MinMaxPriorityQueue.create();
}

... or you need to specify an existing type in its place:

MinMaxPriorityQueue<AtomicCountHolder<Integer>> sortedHeap =
    MinMaxPriorityQueue.create();

You can also use wildcards as you normally would elsewhere (assuming there are no constraints on the parameter type of AtomicCountHolder):

MinMaxPriorityQueue<AtomicCountHolder<?>> sortedHeap =
    MinMaxPriorityQueue.create();


Note that MinMaxPriorityQueue assumes that its elements do not change in a way that alters their ordering. If the AtomicCountHolder class is mutable, as its name suggests, you could have incorrect behavior.

0

精彩评论

暂无评论...
验证码 换一张
取 消