ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/PriorityQueue.java
(Generate patch)

Comparing jsr166/src/main/java/util/PriorityQueue.java (file contents):
Revision 1.63 by jsr166, Tue Mar 7 07:11:39 2006 UTC vs.
Revision 1.74 by jsr166, Wed Jul 13 11:27:28 2011 UTC

# Line 1 | Line 1
1   /*
2 < * %W% %E%
2 > * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
3 > * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5 < * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
6 < * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
5 > * This code is free software; you can redistribute it and/or modify it
6 > * under the terms of the GNU General Public License version 2 only, as
7 > * published by the Free Software Foundation.  Sun designates this
8 > * particular file as subject to the "Classpath" exception as provided
9 > * by Sun in the LICENSE file that accompanied this code.
10 > *
11 > * This code is distributed in the hope that it will be useful, but WITHOUT
12 > * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 > * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 > * version 2 for more details (a copy is included in the LICENSE file that
15 > * accompanied this code).
16 > *
17 > * You should have received a copy of the GNU General Public License version
18 > * 2 along with this work; if not, write to the Free Software Foundation,
19 > * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 > *
21 > * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 > * or visit www.oracle.com if you need additional information or have any
23 > * questions.
24   */
25  
26   package java.util;
# Line 52 | Line 70 | package java.util;
70   * ({@code peek}, {@code element}, and {@code size}).
71   *
72   * <p>This class is a member of the
73 < * <a href="{@docRoot}/../guide/collections/index.html">
73 > * <a href="{@docRoot}/../technotes/guides/collections/index.html">
74   * Java Collections Framework</a>.
75   *
76   * @since 1.5
59 * @version %I%, %G%
77   * @author Josh Bloch, Doug Lea
78   * @param <E> the type of elements held in this collection
79   */
# Line 153 | Line 170 | public class PriorityQueue<E> extends Ab
170       * @throws NullPointerException if the specified collection or any
171       *         of its elements are null
172       */
173 +    @SuppressWarnings("unchecked")
174      public PriorityQueue(Collection<? extends E> c) {
175 <        initFromCollection(c);
176 <        if (c instanceof SortedSet)
177 <            comparator = (Comparator<? super E>)
178 <                ((SortedSet<? extends E>)c).comparator();
179 <        else if (c instanceof PriorityQueue)
180 <            comparator = (Comparator<? super E>)
181 <                ((PriorityQueue<? extends E>)c).comparator();
175 >        if (c instanceof SortedSet<?>) {
176 >            SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
177 >            this.comparator = (Comparator<? super E>) ss.comparator();
178 >            initElementsFromCollection(ss);
179 >        }
180 >        else if (c instanceof PriorityQueue<?>) {
181 >            PriorityQueue<? extends E> pq = (PriorityQueue<? extends E>) c;
182 >            this.comparator = (Comparator<? super E>) pq.comparator();
183 >            initFromPriorityQueue(pq);
184 >        }
185          else {
186 <            comparator = null;
187 <            heapify();
186 >            this.comparator = null;
187 >            initFromCollection(c);
188          }
189      }
190  
# Line 181 | Line 202 | public class PriorityQueue<E> extends Ab
202       * @throws NullPointerException if the specified priority queue or any
203       *         of its elements are null
204       */
205 +    @SuppressWarnings("unchecked")
206      public PriorityQueue(PriorityQueue<? extends E> c) {
207 <        comparator = (Comparator<? super E>)c.comparator();
208 <        initFromCollection(c);
207 >        this.comparator = (Comparator<? super E>) c.comparator();
208 >        initFromPriorityQueue(c);
209      }
210  
211      /**
# Line 199 | Line 221 | public class PriorityQueue<E> extends Ab
221       * @throws NullPointerException if the specified sorted set or any
222       *         of its elements are null
223       */
224 +    @SuppressWarnings("unchecked")
225      public PriorityQueue(SortedSet<? extends E> c) {
226 <        comparator = (Comparator<? super E>)c.comparator();
227 <        initFromCollection(c);
226 >        this.comparator = (Comparator<? super E>) c.comparator();
227 >        initElementsFromCollection(c);
228 >    }
229 >
230 >    private void initFromPriorityQueue(PriorityQueue<? extends E> c) {
231 >        if (c.getClass() == PriorityQueue.class) {
232 >            this.queue = c.toArray();
233 >            this.size = c.size();
234 >        } else {
235 >            initFromCollection(c);
236 >        }
237 >    }
238 >
239 >    private void initElementsFromCollection(Collection<? extends E> c) {
240 >        Object[] a = c.toArray();
241 >        // If c.toArray incorrectly doesn't return Object[], copy it.
242 >        if (a.getClass() != Object[].class)
243 >            a = Arrays.copyOf(a, a.length, Object[].class);
244 >        int len = a.length;
245 >        if (len == 1 || this.comparator != null)
246 >            for (int i = 0; i < len; i++)
247 >                if (a[i] == null)
248 >                    throw new NullPointerException();
249 >        this.queue = a;
250 >        this.size = a.length;
251      }
252  
253      /**
# Line 210 | Line 256 | public class PriorityQueue<E> extends Ab
256       * @param c the collection
257       */
258      private void initFromCollection(Collection<? extends E> c) {
259 <        Object[] a = c.toArray();
260 <        // If c.toArray incorrectly doesn't return Object[], copy it.
215 <        if (a.getClass() != Object[].class)
216 <            a = Arrays.copyOf(a, a.length, Object[].class);
217 <        queue = a;
218 <        size = a.length;
259 >        initElementsFromCollection(c);
260 >        heapify();
261      }
262  
263      /**
264 +     * The maximum size of array to allocate.
265 +     * Some VMs reserve some header words in an array.
266 +     * Attempts to allocate larger arrays may result in
267 +     * OutOfMemoryError: Requested array size exceeds VM limit
268 +     */
269 +    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
270 +
271 +    /**
272       * Increases the capacity of the array.
273       *
274       * @param minCapacity the desired minimum capacity
275       */
276      private void grow(int minCapacity) {
277 <        if (minCapacity < 0) // overflow
228 <            throw new OutOfMemoryError();
229 <        int oldCapacity = queue.length;
277 >        int oldCapacity = queue.length;
278          // Double size if small; else grow by 50%
279 <        int newCapacity = ((oldCapacity < 64)?
280 <                           ((oldCapacity + 1) * 2):
281 <                           ((oldCapacity / 2) * 3));
282 <        if (newCapacity < 0) // overflow
283 <            newCapacity = Integer.MAX_VALUE;
284 <        if (newCapacity < minCapacity)
237 <            newCapacity = minCapacity;
279 >        int newCapacity = oldCapacity + ((oldCapacity < 64) ?
280 >                                         (oldCapacity + 2) :
281 >                                         (oldCapacity >> 1));
282 >        // overflow-conscious code
283 >        if (newCapacity - MAX_ARRAY_SIZE > 0)
284 >            newCapacity = hugeCapacity(minCapacity);
285          queue = Arrays.copyOf(queue, newCapacity);
286      }
287  
288 +    private static int hugeCapacity(int minCapacity) {
289 +        if (minCapacity < 0) // overflow
290 +            throw new OutOfMemoryError();
291 +        return (minCapacity > MAX_ARRAY_SIZE) ?
292 +            Integer.MAX_VALUE :
293 +            MAX_ARRAY_SIZE;
294 +    }
295 +
296      /**
297       * Inserts the specified element into this priority queue.
298       *
# Line 276 | Line 331 | public class PriorityQueue<E> extends Ab
331      }
332  
333      public E peek() {
334 <        if (size == 0)
280 <            return null;
281 <        return (E) queue[0];
334 >        return (size == 0) ? null : (E) queue[0];
335      }
336  
337      private int indexOf(Object o) {
338 <        if (o != null) {
338 >        if (o != null) {
339              for (int i = 0; i < size; i++)
340                  if (o.equals(queue[i]))
341                      return i;
# Line 302 | Line 355 | public class PriorityQueue<E> extends Ab
355       * @return {@code true} if this queue changed as a result of the call
356       */
357      public boolean remove(Object o) {
358 <        int i = indexOf(o);
359 <        if (i == -1)
360 <            return false;
361 <        else {
362 <            removeAt(i);
363 <            return true;
364 <        }
358 >        int i = indexOf(o);
359 >        if (i == -1)
360 >            return false;
361 >        else {
362 >            removeAt(i);
363 >            return true;
364 >        }
365      }
366  
367      /**
# Line 319 | Line 372 | public class PriorityQueue<E> extends Ab
372       * @return {@code true} if removed
373       */
374      boolean removeEq(Object o) {
375 <        for (int i = 0; i < size; i++) {
376 <            if (o == queue[i]) {
375 >        for (int i = 0; i < size; i++) {
376 >            if (o == queue[i]) {
377                  removeAt(i);
378                  return true;
379              }
# Line 337 | Line 390 | public class PriorityQueue<E> extends Ab
390       * @return {@code true} if this queue contains the specified element
391       */
392      public boolean contains(Object o) {
393 <        return indexOf(o) != -1;
393 >        return indexOf(o) != -1;
394      }
395  
396      /**
# Line 379 | Line 432 | public class PriorityQueue<E> extends Ab
432       * The following code can be used to dump the queue into a newly
433       * allocated array of <tt>String</tt>:
434       *
435 <     * <pre>
383 <     *     String[] y = x.toArray(new String[0]);</pre>
435 >     *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
436       *
437       * Note that <tt>toArray(new Object[0])</tt> is identical in function to
438       * <tt>toArray()</tt>.
# Line 398 | Line 450 | public class PriorityQueue<E> extends Ab
450          if (a.length < size)
451              // Make a new array of a's runtime type, but my contents:
452              return (T[]) Arrays.copyOf(queue, size, a.getClass());
453 <        System.arraycopy(queue, 0, a, 0, size);
453 >        System.arraycopy(queue, 0, a, 0, size);
454          if (a.length > size)
455              a[size] = null;
456          return a;
# Line 491 | Line 543 | public class PriorityQueue<E> extends Ab
543                  lastRetElt = null;
544              } else {
545                  throw new IllegalStateException();
546 <            }
546 >            }
547              expectedModCount = modCount;
548          }
549      }
# Line 537 | Line 589 | public class PriorityQueue<E> extends Ab
589       * avoid missing traversing elements.
590       */
591      private E removeAt(int i) {
592 <        assert i >= 0 && i < size;
592 >        // assert i >= 0 && i < size;
593          modCount++;
594          int s = --size;
595          if (s == i) // removed last element
# Line 688 | Line 740 | public class PriorityQueue<E> extends Ab
740          // Write out array length, for compatibility with 1.5 version
741          s.writeInt(Math.max(2, size + 1));
742  
743 <        // Write out all elements in the proper order.
743 >        // Write out all elements in the "proper order".
744          for (int i = 0; i < size; i++)
745              s.writeObject(queue[i]);
746      }
# Line 707 | Line 759 | public class PriorityQueue<E> extends Ab
759          // Read in (and discard) array length
760          s.readInt();
761  
762 <        queue = new Object[size];
762 >        queue = new Object[size];
763  
764 <        // Read in all elements in the proper order.
764 >        // Read in all elements.
765          for (int i = 0; i < size; i++)
766              queue[i] = s.readObject();
767 +
768 +        // Elements are guaranteed to be in "proper order", but the
769 +        // spec has never explained what that might be.
770 +        heapify();
771      }
772   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines