为什么会得到以下结果? [英] Why do I get the following result?

查看:124
本文介绍了为什么会得到以下结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了以下测试,看看如何

I have done the following test to see how a

PriorityBlockingQueue<String> pq = new PriorityBlockingQueue<>(2);
     pq.put("Sing");
     pq.put("Sing2");
     pq.put("Sing3");
     pq.put("Sing4");
     pq.put("Sing10");
     pq.put("Sing11");
     pq.put("Sing12");
     pq.put("Sing13");
     for (String s1: pq)
     {
         System.out.print(s1 +" ");
     }

我得到的结果是:

 Sing Sing10 Sing11 Sing13 Sing2 Sing3 Sing12 Sing4

现在, API如果在施工时没有指定比较器,它应该按照自然顺序排序。

Now how the API says it should order them in their natural order if no comparator specified at construction time. Hoever as you can see the result is not ordered at all.

其次,我设置的初始容量是2,为什么有这样的选项,如果绑定实际上不是组?重点是什么?我知道api指定它是一个无界的优先级队列,但为什么要一个构造函数采取一个初始容量,如果它不能设置任何边界?

Secondly the initial capacity I set was of 2, why there is such an option if the bound is actually not set? What's the point? I understand that the api specify that it's an unbounded priority queue however why making a constructor taking an initial capacity at all if it cannot set any bound of it?

有2个问题:

1)为什么上述结果的顺序不遵循元素的自然顺序?

1) Why the order of the result above posted does not follow the natural order of the elements?

2)使用具有参数初始容量的构造函数的目的不是实际设置绑定。在 LinkedBlockingQueue 中,它是合理的

2) What is the purpose of having a constructor with a parameter "initial capacity" which does not actually set the bound. In the LinkedBlockingQueue it's reasonable as it sets the bound however it does not happen in the PriorityBlockingQueue.

提前感谢。

推荐答案

当你以poll,remove,peek或take作为例子访问头部时,但不是当你迭代时,这个顺序是有保证的:

The order is guaranteed when you access the head with poll, remove, peek or take for example, but not when you iterate:


方法iterator()中提供的迭代器不能保证以任何特定顺序遍历优先级队列的元素。

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.

这将产生预期的输出:

String s;
while ((s = pq.poll()) != null) {
    System.out.println(s);
}

输出:

Sing
Sing10
Sing11
Sing12
Sing13
Sing2
Sing3
Sing4








具有实际上不设置绑定的参数初始容量的构造函数。

What is the purpose of having a constructor with a parameter "initial capacity" which does not actually set the bound.

初始容量不是绑定。队列由阵列支持 - 通过设置初始容量可以避免不必要的数组调整大小(类似于ArrayList的构造函数)。

The initial capacity is not a bound. The queue is backed by an array - by setting the initial capacity you can avoid unnecessary array resizing (similarly to ArrayList's constructor).

这篇关于为什么会得到以下结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆