java - Why do I get the following result? -


this question has answer here:

i have done following test see how

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");      (string s1: pq)      {          system.out.print(s1 +" ");      } 

the result is:

 sing sing10 sing11 sing13 sing2 sing3 sing12 sing4 

now how api says should order them in natural order if no comparator specified @ construction time. hoever can see result not ordered @ all.

secondly initial capacity set of 2, why there such option if bound not set? what's point? understand api specify it's unbounded priority queue why making constructor taking initial capacity @ if cannot set bound of it?

so have got 2 questions:

1) why order of result above posted not follow natural order of elements?

2) purpose of having constructor parameter "initial capacity" not set bound. in linkedblockingqueue it's reasonable sets bound not happen in priorityblockingqueue.

thanks in advance.

the order guaranteed when access head poll, remove, peek or take example, not when iterate:

the iterator provided in method iterator() not guaranteed traverse elements of priority queue in particular order.

this yield expected output:

string s; while ((s = pq.poll()) != null) {     system.out.println(s); } 

outputs:

sing sing10 sing11 sing12 sing13 sing2 sing3 sing4 

what purpose of having constructor parameter "initial capacity" not set bound.

the initial capacity not bound. queue backed array - setting initial capacity can avoid unnecessary array resizing (similarly arraylist's constructor).


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -