1.1 --- a/emul/compact/src/main/java/java/io/InputStreamReader.java Fri Jan 25 16:46:14 2013 +0100
1.2 +++ b/emul/compact/src/main/java/java/io/InputStreamReader.java Mon Jan 28 18:14:00 2013 +0100
1.3 @@ -156,9 +156,39 @@
1.4 * @exception IOException If an I/O error occurs
1.5 */
1.6 public int read() throws IOException {
1.7 - return ((InputStream)lock).read();
1.8 + final InputStream is = (InputStream)lock;
1.9 + int c = is.read();
1.10 + if (c == -1) {
1.11 + return -1;
1.12 + }
1.13 + c = (int) c & 0xff;
1.14 + switch (c >> 4) {
1.15 + case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
1.16 + /* 0xxxxxxx*/
1.17 + return c;
1.18 + case 12: case 13: {
1.19 + /* 110x xxxx 10xx xxxx*/
1.20 + int char2 = (int) is.read();
1.21 + if ((char2 & 0xC0) != 0x80)
1.22 + throw new UTFDataFormatException("malformed input");
1.23 + return (((c & 0x1F) << 6) | (char2 & 0x3F));
1.24 + }
1.25 + case 14: {
1.26 + /* 1110 xxxx 10xx xxxx 10xx xxxx */
1.27 + int char2 = is.read();
1.28 + int char3 = is.read();
1.29 + if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
1.30 + throw new UTFDataFormatException("malformed input");
1.31 + return (((c & 0x0F) << 12) |
1.32 + ((char2 & 0x3F) << 6) |
1.33 + ((char3 & 0x3F) << 0));
1.34 + }
1.35 + default:
1.36 + /* 10xx xxxx, 1111 xxxx */
1.37 + throw new UTFDataFormatException("malformed input");
1.38 + }
1.39 }
1.40 -
1.41 +
1.42 /**
1.43 * Reads characters into a portion of an array.
1.44 *
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/emul/compact/src/main/java/java/util/AbstractQueue.java Mon Jan 28 18:14:00 2013 +0100
2.3 @@ -0,0 +1,192 @@
2.4 +/*
2.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
2.6 + *
2.7 + * This code is free software; you can redistribute it and/or modify it
2.8 + * under the terms of the GNU General Public License version 2 only, as
2.9 + * published by the Free Software Foundation. Oracle designates this
2.10 + * particular file as subject to the "Classpath" exception as provided
2.11 + * by Oracle in the LICENSE file that accompanied this code.
2.12 + *
2.13 + * This code is distributed in the hope that it will be useful, but WITHOUT
2.14 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
2.15 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
2.16 + * version 2 for more details (a copy is included in the LICENSE file that
2.17 + * accompanied this code).
2.18 + *
2.19 + * You should have received a copy of the GNU General Public License version
2.20 + * 2 along with this work; if not, write to the Free Software Foundation,
2.21 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
2.22 + *
2.23 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2.24 + * or visit www.oracle.com if you need additional information or have any
2.25 + * questions.
2.26 + */
2.27 +
2.28 +/*
2.29 + * This file is available under and governed by the GNU General Public
2.30 + * License version 2 only, as published by the Free Software Foundation.
2.31 + * However, the following notice accompanied the original version of this
2.32 + * file:
2.33 + *
2.34 + * Written by Doug Lea with assistance from members of JCP JSR-166
2.35 + * Expert Group and released to the public domain, as explained at
2.36 + * http://creativecommons.org/publicdomain/zero/1.0/
2.37 + */
2.38 +
2.39 +package java.util;
2.40 +
2.41 +/**
2.42 + * This class provides skeletal implementations of some {@link Queue}
2.43 + * operations. The implementations in this class are appropriate when
2.44 + * the base implementation does <em>not</em> allow <tt>null</tt>
2.45 + * elements. Methods {@link #add add}, {@link #remove remove}, and
2.46 + * {@link #element element} are based on {@link #offer offer}, {@link
2.47 + * #poll poll}, and {@link #peek peek}, respectively, but throw
2.48 + * exceptions instead of indicating failure via <tt>false</tt> or
2.49 + * <tt>null</tt> returns.
2.50 + *
2.51 + * <p>A <tt>Queue</tt> implementation that extends this class must
2.52 + * minimally define a method {@link Queue#offer} which does not permit
2.53 + * insertion of <tt>null</tt> elements, along with methods {@link
2.54 + * Queue#peek}, {@link Queue#poll}, {@link Collection#size}, and
2.55 + * {@link Collection#iterator}. Typically, additional methods will be
2.56 + * overridden as well. If these requirements cannot be met, consider
2.57 + * instead subclassing {@link AbstractCollection}.
2.58 + *
2.59 + * <p>This class is a member of the
2.60 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
2.61 + * Java Collections Framework</a>.
2.62 + *
2.63 + * @since 1.5
2.64 + * @author Doug Lea
2.65 + * @param <E> the type of elements held in this collection
2.66 + */
2.67 +public abstract class AbstractQueue<E>
2.68 + extends AbstractCollection<E>
2.69 + implements Queue<E> {
2.70 +
2.71 + /**
2.72 + * Constructor for use by subclasses.
2.73 + */
2.74 + protected AbstractQueue() {
2.75 + }
2.76 +
2.77 + /**
2.78 + * Inserts the specified element into this queue if it is possible to do so
2.79 + * immediately without violating capacity restrictions, returning
2.80 + * <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt>
2.81 + * if no space is currently available.
2.82 + *
2.83 + * <p>This implementation returns <tt>true</tt> if <tt>offer</tt> succeeds,
2.84 + * else throws an <tt>IllegalStateException</tt>.
2.85 + *
2.86 + * @param e the element to add
2.87 + * @return <tt>true</tt> (as specified by {@link Collection#add})
2.88 + * @throws IllegalStateException if the element cannot be added at this
2.89 + * time due to capacity restrictions
2.90 + * @throws ClassCastException if the class of the specified element
2.91 + * prevents it from being added to this queue
2.92 + * @throws NullPointerException if the specified element is null and
2.93 + * this queue does not permit null elements
2.94 + * @throws IllegalArgumentException if some property of this element
2.95 + * prevents it from being added to this queue
2.96 + */
2.97 + public boolean add(E e) {
2.98 + if (offer(e))
2.99 + return true;
2.100 + else
2.101 + throw new IllegalStateException("Queue full");
2.102 + }
2.103 +
2.104 + /**
2.105 + * Retrieves and removes the head of this queue. This method differs
2.106 + * from {@link #poll poll} only in that it throws an exception if this
2.107 + * queue is empty.
2.108 + *
2.109 + * <p>This implementation returns the result of <tt>poll</tt>
2.110 + * unless the queue is empty.
2.111 + *
2.112 + * @return the head of this queue
2.113 + * @throws NoSuchElementException if this queue is empty
2.114 + */
2.115 + public E remove() {
2.116 + E x = poll();
2.117 + if (x != null)
2.118 + return x;
2.119 + else
2.120 + throw new NoSuchElementException();
2.121 + }
2.122 +
2.123 + /**
2.124 + * Retrieves, but does not remove, the head of this queue. This method
2.125 + * differs from {@link #peek peek} only in that it throws an exception if
2.126 + * this queue is empty.
2.127 + *
2.128 + * <p>This implementation returns the result of <tt>peek</tt>
2.129 + * unless the queue is empty.
2.130 + *
2.131 + * @return the head of this queue
2.132 + * @throws NoSuchElementException if this queue is empty
2.133 + */
2.134 + public E element() {
2.135 + E x = peek();
2.136 + if (x != null)
2.137 + return x;
2.138 + else
2.139 + throw new NoSuchElementException();
2.140 + }
2.141 +
2.142 + /**
2.143 + * Removes all of the elements from this queue.
2.144 + * The queue will be empty after this call returns.
2.145 + *
2.146 + * <p>This implementation repeatedly invokes {@link #poll poll} until it
2.147 + * returns <tt>null</tt>.
2.148 + */
2.149 + public void clear() {
2.150 + while (poll() != null)
2.151 + ;
2.152 + }
2.153 +
2.154 + /**
2.155 + * Adds all of the elements in the specified collection to this
2.156 + * queue. Attempts to addAll of a queue to itself result in
2.157 + * <tt>IllegalArgumentException</tt>. Further, the behavior of
2.158 + * this operation is undefined if the specified collection is
2.159 + * modified while the operation is in progress.
2.160 + *
2.161 + * <p>This implementation iterates over the specified collection,
2.162 + * and adds each element returned by the iterator to this
2.163 + * queue, in turn. A runtime exception encountered while
2.164 + * trying to add an element (including, in particular, a
2.165 + * <tt>null</tt> element) may result in only some of the elements
2.166 + * having been successfully added when the associated exception is
2.167 + * thrown.
2.168 + *
2.169 + * @param c collection containing elements to be added to this queue
2.170 + * @return <tt>true</tt> if this queue changed as a result of the call
2.171 + * @throws ClassCastException if the class of an element of the specified
2.172 + * collection prevents it from being added to this queue
2.173 + * @throws NullPointerException if the specified collection contains a
2.174 + * null element and this queue does not permit null elements,
2.175 + * or if the specified collection is null
2.176 + * @throws IllegalArgumentException if some property of an element of the
2.177 + * specified collection prevents it from being added to this
2.178 + * queue, or if the specified collection is this queue
2.179 + * @throws IllegalStateException if not all the elements can be added at
2.180 + * this time due to insertion restrictions
2.181 + * @see #add(Object)
2.182 + */
2.183 + public boolean addAll(Collection<? extends E> c) {
2.184 + if (c == null)
2.185 + throw new NullPointerException();
2.186 + if (c == this)
2.187 + throw new IllegalArgumentException();
2.188 + boolean modified = false;
2.189 + for (E e : c)
2.190 + if (add(e))
2.191 + modified = true;
2.192 + return modified;
2.193 + }
2.194 +
2.195 +}
3.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3.2 +++ b/emul/compact/src/main/java/java/util/AbstractSequentialList.java Mon Jan 28 18:14:00 2013 +0100
3.3 @@ -0,0 +1,253 @@
3.4 +/*
3.5 + * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
3.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3.7 + *
3.8 + * This code is free software; you can redistribute it and/or modify it
3.9 + * under the terms of the GNU General Public License version 2 only, as
3.10 + * published by the Free Software Foundation. Oracle designates this
3.11 + * particular file as subject to the "Classpath" exception as provided
3.12 + * by Oracle in the LICENSE file that accompanied this code.
3.13 + *
3.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
3.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
3.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
3.17 + * version 2 for more details (a copy is included in the LICENSE file that
3.18 + * accompanied this code).
3.19 + *
3.20 + * You should have received a copy of the GNU General Public License version
3.21 + * 2 along with this work; if not, write to the Free Software Foundation,
3.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
3.23 + *
3.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
3.25 + * or visit www.oracle.com if you need additional information or have any
3.26 + * questions.
3.27 + */
3.28 +
3.29 +package java.util;
3.30 +
3.31 +/**
3.32 + * This class provides a skeletal implementation of the <tt>List</tt>
3.33 + * interface to minimize the effort required to implement this interface
3.34 + * backed by a "sequential access" data store (such as a linked list). For
3.35 + * random access data (such as an array), <tt>AbstractList</tt> should be used
3.36 + * in preference to this class.<p>
3.37 + *
3.38 + * This class is the opposite of the <tt>AbstractList</tt> class in the sense
3.39 + * that it implements the "random access" methods (<tt>get(int index)</tt>,
3.40 + * <tt>set(int index, E element)</tt>, <tt>add(int index, E element)</tt> and
3.41 + * <tt>remove(int index)</tt>) on top of the list's list iterator, instead of
3.42 + * the other way around.<p>
3.43 + *
3.44 + * To implement a list the programmer needs only to extend this class and
3.45 + * provide implementations for the <tt>listIterator</tt> and <tt>size</tt>
3.46 + * methods. For an unmodifiable list, the programmer need only implement the
3.47 + * list iterator's <tt>hasNext</tt>, <tt>next</tt>, <tt>hasPrevious</tt>,
3.48 + * <tt>previous</tt> and <tt>index</tt> methods.<p>
3.49 + *
3.50 + * For a modifiable list the programmer should additionally implement the list
3.51 + * iterator's <tt>set</tt> method. For a variable-size list the programmer
3.52 + * should additionally implement the list iterator's <tt>remove</tt> and
3.53 + * <tt>add</tt> methods.<p>
3.54 + *
3.55 + * The programmer should generally provide a void (no argument) and collection
3.56 + * constructor, as per the recommendation in the <tt>Collection</tt> interface
3.57 + * specification.<p>
3.58 + *
3.59 + * This class is a member of the
3.60 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
3.61 + * Java Collections Framework</a>.
3.62 + *
3.63 + * @author Josh Bloch
3.64 + * @author Neal Gafter
3.65 + * @see Collection
3.66 + * @see List
3.67 + * @see AbstractList
3.68 + * @see AbstractCollection
3.69 + * @since 1.2
3.70 + */
3.71 +
3.72 +public abstract class AbstractSequentialList<E> extends AbstractList<E> {
3.73 + /**
3.74 + * Sole constructor. (For invocation by subclass constructors, typically
3.75 + * implicit.)
3.76 + */
3.77 + protected AbstractSequentialList() {
3.78 + }
3.79 +
3.80 + /**
3.81 + * Returns the element at the specified position in this list.
3.82 + *
3.83 + * <p>This implementation first gets a list iterator pointing to the
3.84 + * indexed element (with <tt>listIterator(index)</tt>). Then, it gets
3.85 + * the element using <tt>ListIterator.next</tt> and returns it.
3.86 + *
3.87 + * @throws IndexOutOfBoundsException {@inheritDoc}
3.88 + */
3.89 + public E get(int index) {
3.90 + try {
3.91 + return listIterator(index).next();
3.92 + } catch (NoSuchElementException exc) {
3.93 + throw new IndexOutOfBoundsException("Index: "+index);
3.94 + }
3.95 + }
3.96 +
3.97 + /**
3.98 + * Replaces the element at the specified position in this list with the
3.99 + * specified element (optional operation).
3.100 + *
3.101 + * <p>This implementation first gets a list iterator pointing to the
3.102 + * indexed element (with <tt>listIterator(index)</tt>). Then, it gets
3.103 + * the current element using <tt>ListIterator.next</tt> and replaces it
3.104 + * with <tt>ListIterator.set</tt>.
3.105 + *
3.106 + * <p>Note that this implementation will throw an
3.107 + * <tt>UnsupportedOperationException</tt> if the list iterator does not
3.108 + * implement the <tt>set</tt> operation.
3.109 + *
3.110 + * @throws UnsupportedOperationException {@inheritDoc}
3.111 + * @throws ClassCastException {@inheritDoc}
3.112 + * @throws NullPointerException {@inheritDoc}
3.113 + * @throws IllegalArgumentException {@inheritDoc}
3.114 + * @throws IndexOutOfBoundsException {@inheritDoc}
3.115 + */
3.116 + public E set(int index, E element) {
3.117 + try {
3.118 + ListIterator<E> e = listIterator(index);
3.119 + E oldVal = e.next();
3.120 + e.set(element);
3.121 + return oldVal;
3.122 + } catch (NoSuchElementException exc) {
3.123 + throw new IndexOutOfBoundsException("Index: "+index);
3.124 + }
3.125 + }
3.126 +
3.127 + /**
3.128 + * Inserts the specified element at the specified position in this list
3.129 + * (optional operation). Shifts the element currently at that position
3.130 + * (if any) and any subsequent elements to the right (adds one to their
3.131 + * indices).
3.132 + *
3.133 + * <p>This implementation first gets a list iterator pointing to the
3.134 + * indexed element (with <tt>listIterator(index)</tt>). Then, it
3.135 + * inserts the specified element with <tt>ListIterator.add</tt>.
3.136 + *
3.137 + * <p>Note that this implementation will throw an
3.138 + * <tt>UnsupportedOperationException</tt> if the list iterator does not
3.139 + * implement the <tt>add</tt> operation.
3.140 + *
3.141 + * @throws UnsupportedOperationException {@inheritDoc}
3.142 + * @throws ClassCastException {@inheritDoc}
3.143 + * @throws NullPointerException {@inheritDoc}
3.144 + * @throws IllegalArgumentException {@inheritDoc}
3.145 + * @throws IndexOutOfBoundsException {@inheritDoc}
3.146 + */
3.147 + public void add(int index, E element) {
3.148 + try {
3.149 + listIterator(index).add(element);
3.150 + } catch (NoSuchElementException exc) {
3.151 + throw new IndexOutOfBoundsException("Index: "+index);
3.152 + }
3.153 + }
3.154 +
3.155 + /**
3.156 + * Removes the element at the specified position in this list (optional
3.157 + * operation). Shifts any subsequent elements to the left (subtracts one
3.158 + * from their indices). Returns the element that was removed from the
3.159 + * list.
3.160 + *
3.161 + * <p>This implementation first gets a list iterator pointing to the
3.162 + * indexed element (with <tt>listIterator(index)</tt>). Then, it removes
3.163 + * the element with <tt>ListIterator.remove</tt>.
3.164 + *
3.165 + * <p>Note that this implementation will throw an
3.166 + * <tt>UnsupportedOperationException</tt> if the list iterator does not
3.167 + * implement the <tt>remove</tt> operation.
3.168 + *
3.169 + * @throws UnsupportedOperationException {@inheritDoc}
3.170 + * @throws IndexOutOfBoundsException {@inheritDoc}
3.171 + */
3.172 + public E remove(int index) {
3.173 + try {
3.174 + ListIterator<E> e = listIterator(index);
3.175 + E outCast = e.next();
3.176 + e.remove();
3.177 + return outCast;
3.178 + } catch (NoSuchElementException exc) {
3.179 + throw new IndexOutOfBoundsException("Index: "+index);
3.180 + }
3.181 + }
3.182 +
3.183 +
3.184 + // Bulk Operations
3.185 +
3.186 + /**
3.187 + * Inserts all of the elements in the specified collection into this
3.188 + * list at the specified position (optional operation). Shifts the
3.189 + * element currently at that position (if any) and any subsequent
3.190 + * elements to the right (increases their indices). The new elements
3.191 + * will appear in this list in the order that they are returned by the
3.192 + * specified collection's iterator. The behavior of this operation is
3.193 + * undefined if the specified collection is modified while the
3.194 + * operation is in progress. (Note that this will occur if the specified
3.195 + * collection is this list, and it's nonempty.)
3.196 + *
3.197 + * <p>This implementation gets an iterator over the specified collection and
3.198 + * a list iterator over this list pointing to the indexed element (with
3.199 + * <tt>listIterator(index)</tt>). Then, it iterates over the specified
3.200 + * collection, inserting the elements obtained from the iterator into this
3.201 + * list, one at a time, using <tt>ListIterator.add</tt> followed by
3.202 + * <tt>ListIterator.next</tt> (to skip over the added element).
3.203 + *
3.204 + * <p>Note that this implementation will throw an
3.205 + * <tt>UnsupportedOperationException</tt> if the list iterator returned by
3.206 + * the <tt>listIterator</tt> method does not implement the <tt>add</tt>
3.207 + * operation.
3.208 + *
3.209 + * @throws UnsupportedOperationException {@inheritDoc}
3.210 + * @throws ClassCastException {@inheritDoc}
3.211 + * @throws NullPointerException {@inheritDoc}
3.212 + * @throws IllegalArgumentException {@inheritDoc}
3.213 + * @throws IndexOutOfBoundsException {@inheritDoc}
3.214 + */
3.215 + public boolean addAll(int index, Collection<? extends E> c) {
3.216 + try {
3.217 + boolean modified = false;
3.218 + ListIterator<E> e1 = listIterator(index);
3.219 + Iterator<? extends E> e2 = c.iterator();
3.220 + while (e2.hasNext()) {
3.221 + e1.add(e2.next());
3.222 + modified = true;
3.223 + }
3.224 + return modified;
3.225 + } catch (NoSuchElementException exc) {
3.226 + throw new IndexOutOfBoundsException("Index: "+index);
3.227 + }
3.228 + }
3.229 +
3.230 +
3.231 + // Iterators
3.232 +
3.233 + /**
3.234 + * Returns an iterator over the elements in this list (in proper
3.235 + * sequence).<p>
3.236 + *
3.237 + * This implementation merely returns a list iterator over the list.
3.238 + *
3.239 + * @return an iterator over the elements in this list (in proper sequence)
3.240 + */
3.241 + public Iterator<E> iterator() {
3.242 + return listIterator();
3.243 + }
3.244 +
3.245 + /**
3.246 + * Returns a list iterator over the elements in this list (in proper
3.247 + * sequence).
3.248 + *
3.249 + * @param index index of first element to be returned from the list
3.250 + * iterator (by a call to the <code>next</code> method)
3.251 + * @return a list iterator over the elements in this list (in proper
3.252 + * sequence)
3.253 + * @throws IndexOutOfBoundsException {@inheritDoc}
3.254 + */
3.255 + public abstract ListIterator<E> listIterator(int index);
3.256 +}
4.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
4.2 +++ b/emul/compact/src/main/java/java/util/ArrayDeque.java Mon Jan 28 18:14:00 2013 +0100
4.3 @@ -0,0 +1,831 @@
4.4 +/*
4.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4.6 + *
4.7 + * This code is free software; you can redistribute it and/or modify it
4.8 + * under the terms of the GNU General Public License version 2 only, as
4.9 + * published by the Free Software Foundation. Oracle designates this
4.10 + * particular file as subject to the "Classpath" exception as provided
4.11 + * by Oracle in the LICENSE file that accompanied this code.
4.12 + *
4.13 + * This code is distributed in the hope that it will be useful, but WITHOUT
4.14 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
4.15 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
4.16 + * version 2 for more details (a copy is included in the LICENSE file that
4.17 + * accompanied this code).
4.18 + *
4.19 + * You should have received a copy of the GNU General Public License version
4.20 + * 2 along with this work; if not, write to the Free Software Foundation,
4.21 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
4.22 + *
4.23 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
4.24 + * or visit www.oracle.com if you need additional information or have any
4.25 + * questions.
4.26 + */
4.27 +
4.28 +/*
4.29 + * This file is available under and governed by the GNU General Public
4.30 + * License version 2 only, as published by the Free Software Foundation.
4.31 + * However, the following notice accompanied the original version of this
4.32 + * file:
4.33 + *
4.34 + * Written by Josh Bloch of Google Inc. and released to the public domain,
4.35 + * as explained at http://creativecommons.org/publicdomain/zero/1.0/.
4.36 + */
4.37 +
4.38 +package java.util;
4.39 +import java.io.*;
4.40 +import org.apidesign.bck2brwsr.emul.lang.System;
4.41 +
4.42 +/**
4.43 + * Resizable-array implementation of the {@link Deque} interface. Array
4.44 + * deques have no capacity restrictions; they grow as necessary to support
4.45 + * usage. They are not thread-safe; in the absence of external
4.46 + * synchronization, they do not support concurrent access by multiple threads.
4.47 + * Null elements are prohibited. This class is likely to be faster than
4.48 + * {@link Stack} when used as a stack, and faster than {@link LinkedList}
4.49 + * when used as a queue.
4.50 + *
4.51 + * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
4.52 + * Exceptions include {@link #remove(Object) remove}, {@link
4.53 + * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
4.54 + * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
4.55 + * iterator.remove()}, and the bulk operations, all of which run in linear
4.56 + * time.
4.57 + *
4.58 + * <p>The iterators returned by this class's <tt>iterator</tt> method are
4.59 + * <i>fail-fast</i>: If the deque is modified at any time after the iterator
4.60 + * is created, in any way except through the iterator's own <tt>remove</tt>
4.61 + * method, the iterator will generally throw a {@link
4.62 + * ConcurrentModificationException}. Thus, in the face of concurrent
4.63 + * modification, the iterator fails quickly and cleanly, rather than risking
4.64 + * arbitrary, non-deterministic behavior at an undetermined time in the
4.65 + * future.
4.66 + *
4.67 + * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
4.68 + * as it is, generally speaking, impossible to make any hard guarantees in the
4.69 + * presence of unsynchronized concurrent modification. Fail-fast iterators
4.70 + * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
4.71 + * Therefore, it would be wrong to write a program that depended on this
4.72 + * exception for its correctness: <i>the fail-fast behavior of iterators
4.73 + * should be used only to detect bugs.</i>
4.74 + *
4.75 + * <p>This class and its iterator implement all of the
4.76 + * <em>optional</em> methods of the {@link Collection} and {@link
4.77 + * Iterator} interfaces.
4.78 + *
4.79 + * <p>This class is a member of the
4.80 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
4.81 + * Java Collections Framework</a>.
4.82 + *
4.83 + * @author Josh Bloch and Doug Lea
4.84 + * @since 1.6
4.85 + * @param <E> the type of elements held in this collection
4.86 + */
4.87 +public class ArrayDeque<E> extends AbstractCollection<E>
4.88 + implements Deque<E>, Cloneable, Serializable
4.89 +{
4.90 + /**
4.91 + * The array in which the elements of the deque are stored.
4.92 + * The capacity of the deque is the length of this array, which is
4.93 + * always a power of two. The array is never allowed to become
4.94 + * full, except transiently within an addX method where it is
4.95 + * resized (see doubleCapacity) immediately upon becoming full,
4.96 + * thus avoiding head and tail wrapping around to equal each
4.97 + * other. We also guarantee that all array cells not holding
4.98 + * deque elements are always null.
4.99 + */
4.100 + private transient E[] elements;
4.101 +
4.102 + /**
4.103 + * The index of the element at the head of the deque (which is the
4.104 + * element that would be removed by remove() or pop()); or an
4.105 + * arbitrary number equal to tail if the deque is empty.
4.106 + */
4.107 + private transient int head;
4.108 +
4.109 + /**
4.110 + * The index at which the next element would be added to the tail
4.111 + * of the deque (via addLast(E), add(E), or push(E)).
4.112 + */
4.113 + private transient int tail;
4.114 +
4.115 + /**
4.116 + * The minimum capacity that we'll use for a newly created deque.
4.117 + * Must be a power of 2.
4.118 + */
4.119 + private static final int MIN_INITIAL_CAPACITY = 8;
4.120 +
4.121 + // ****** Array allocation and resizing utilities ******
4.122 +
4.123 + /**
4.124 + * Allocate empty array to hold the given number of elements.
4.125 + *
4.126 + * @param numElements the number of elements to hold
4.127 + */
4.128 + private void allocateElements(int numElements) {
4.129 + int initialCapacity = MIN_INITIAL_CAPACITY;
4.130 + // Find the best power of two to hold elements.
4.131 + // Tests "<=" because arrays aren't kept full.
4.132 + if (numElements >= initialCapacity) {
4.133 + initialCapacity = numElements;
4.134 + initialCapacity |= (initialCapacity >>> 1);
4.135 + initialCapacity |= (initialCapacity >>> 2);
4.136 + initialCapacity |= (initialCapacity >>> 4);
4.137 + initialCapacity |= (initialCapacity >>> 8);
4.138 + initialCapacity |= (initialCapacity >>> 16);
4.139 + initialCapacity++;
4.140 +
4.141 + if (initialCapacity < 0) // Too many elements, must back off
4.142 + initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
4.143 + }
4.144 + elements = (E[]) new Object[initialCapacity];
4.145 + }
4.146 +
4.147 + /**
4.148 + * Double the capacity of this deque. Call only when full, i.e.,
4.149 + * when head and tail have wrapped around to become equal.
4.150 + */
4.151 + private void doubleCapacity() {
4.152 + assert head == tail;
4.153 + int p = head;
4.154 + int n = elements.length;
4.155 + int r = n - p; // number of elements to the right of p
4.156 + int newCapacity = n << 1;
4.157 + if (newCapacity < 0)
4.158 + throw new IllegalStateException("Sorry, deque too big");
4.159 + Object[] a = new Object[newCapacity];
4.160 + System.arraycopy(elements, p, a, 0, r);
4.161 + System.arraycopy(elements, 0, a, r, p);
4.162 + elements = (E[])a;
4.163 + head = 0;
4.164 + tail = n;
4.165 + }
4.166 +
4.167 + /**
4.168 + * Copies the elements from our element array into the specified array,
4.169 + * in order (from first to last element in the deque). It is assumed
4.170 + * that the array is large enough to hold all elements in the deque.
4.171 + *
4.172 + * @return its argument
4.173 + */
4.174 + private <T> T[] copyElements(T[] a) {
4.175 + if (head < tail) {
4.176 + System.arraycopy(elements, head, a, 0, size());
4.177 + } else if (head > tail) {
4.178 + int headPortionLen = elements.length - head;
4.179 + System.arraycopy(elements, head, a, 0, headPortionLen);
4.180 + System.arraycopy(elements, 0, a, headPortionLen, tail);
4.181 + }
4.182 + return a;
4.183 + }
4.184 +
4.185 + /**
4.186 + * Constructs an empty array deque with an initial capacity
4.187 + * sufficient to hold 16 elements.
4.188 + */
4.189 + public ArrayDeque() {
4.190 + elements = (E[]) new Object[16];
4.191 + }
4.192 +
4.193 + /**
4.194 + * Constructs an empty array deque with an initial capacity
4.195 + * sufficient to hold the specified number of elements.
4.196 + *
4.197 + * @param numElements lower bound on initial capacity of the deque
4.198 + */
4.199 + public ArrayDeque(int numElements) {
4.200 + allocateElements(numElements);
4.201 + }
4.202 +
4.203 + /**
4.204 + * Constructs a deque containing the elements of the specified
4.205 + * collection, in the order they are returned by the collection's
4.206 + * iterator. (The first element returned by the collection's
4.207 + * iterator becomes the first element, or <i>front</i> of the
4.208 + * deque.)
4.209 + *
4.210 + * @param c the collection whose elements are to be placed into the deque
4.211 + * @throws NullPointerException if the specified collection is null
4.212 + */
4.213 + public ArrayDeque(Collection<? extends E> c) {
4.214 + allocateElements(c.size());
4.215 + addAll(c);
4.216 + }
4.217 +
4.218 + // The main insertion and extraction methods are addFirst,
4.219 + // addLast, pollFirst, pollLast. The other methods are defined in
4.220 + // terms of these.
4.221 +
4.222 + /**
4.223 + * Inserts the specified element at the front of this deque.
4.224 + *
4.225 + * @param e the element to add
4.226 + * @throws NullPointerException if the specified element is null
4.227 + */
4.228 + public void addFirst(E e) {
4.229 + if (e == null)
4.230 + throw new NullPointerException();
4.231 + elements[head = (head - 1) & (elements.length - 1)] = e;
4.232 + if (head == tail)
4.233 + doubleCapacity();
4.234 + }
4.235 +
4.236 + /**
4.237 + * Inserts the specified element at the end of this deque.
4.238 + *
4.239 + * <p>This method is equivalent to {@link #add}.
4.240 + *
4.241 + * @param e the element to add
4.242 + * @throws NullPointerException if the specified element is null
4.243 + */
4.244 + public void addLast(E e) {
4.245 + if (e == null)
4.246 + throw new NullPointerException();
4.247 + elements[tail] = e;
4.248 + if ( (tail = (tail + 1) & (elements.length - 1)) == head)
4.249 + doubleCapacity();
4.250 + }
4.251 +
4.252 + /**
4.253 + * Inserts the specified element at the front of this deque.
4.254 + *
4.255 + * @param e the element to add
4.256 + * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
4.257 + * @throws NullPointerException if the specified element is null
4.258 + */
4.259 + public boolean offerFirst(E e) {
4.260 + addFirst(e);
4.261 + return true;
4.262 + }
4.263 +
4.264 + /**
4.265 + * Inserts the specified element at the end of this deque.
4.266 + *
4.267 + * @param e the element to add
4.268 + * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
4.269 + * @throws NullPointerException if the specified element is null
4.270 + */
4.271 + public boolean offerLast(E e) {
4.272 + addLast(e);
4.273 + return true;
4.274 + }
4.275 +
4.276 + /**
4.277 + * @throws NoSuchElementException {@inheritDoc}
4.278 + */
4.279 + public E removeFirst() {
4.280 + E x = pollFirst();
4.281 + if (x == null)
4.282 + throw new NoSuchElementException();
4.283 + return x;
4.284 + }
4.285 +
4.286 + /**
4.287 + * @throws NoSuchElementException {@inheritDoc}
4.288 + */
4.289 + public E removeLast() {
4.290 + E x = pollLast();
4.291 + if (x == null)
4.292 + throw new NoSuchElementException();
4.293 + return x;
4.294 + }
4.295 +
4.296 + public E pollFirst() {
4.297 + int h = head;
4.298 + E result = elements[h]; // Element is null if deque empty
4.299 + if (result == null)
4.300 + return null;
4.301 + elements[h] = null; // Must null out slot
4.302 + head = (h + 1) & (elements.length - 1);
4.303 + return result;
4.304 + }
4.305 +
4.306 + public E pollLast() {
4.307 + int t = (tail - 1) & (elements.length - 1);
4.308 + E result = elements[t];
4.309 + if (result == null)
4.310 + return null;
4.311 + elements[t] = null;
4.312 + tail = t;
4.313 + return result;
4.314 + }
4.315 +
4.316 + /**
4.317 + * @throws NoSuchElementException {@inheritDoc}
4.318 + */
4.319 + public E getFirst() {
4.320 + E x = elements[head];
4.321 + if (x == null)
4.322 + throw new NoSuchElementException();
4.323 + return x;
4.324 + }
4.325 +
4.326 + /**
4.327 + * @throws NoSuchElementException {@inheritDoc}
4.328 + */
4.329 + public E getLast() {
4.330 + E x = elements[(tail - 1) & (elements.length - 1)];
4.331 + if (x == null)
4.332 + throw new NoSuchElementException();
4.333 + return x;
4.334 + }
4.335 +
4.336 + public E peekFirst() {
4.337 + return elements[head]; // elements[head] is null if deque empty
4.338 + }
4.339 +
4.340 + public E peekLast() {
4.341 + return elements[(tail - 1) & (elements.length - 1)];
4.342 + }
4.343 +
4.344 + /**
4.345 + * Removes the first occurrence of the specified element in this
4.346 + * deque (when traversing the deque from head to tail).
4.347 + * If the deque does not contain the element, it is unchanged.
4.348 + * More formally, removes the first element <tt>e</tt> such that
4.349 + * <tt>o.equals(e)</tt> (if such an element exists).
4.350 + * Returns <tt>true</tt> if this deque contained the specified element
4.351 + * (or equivalently, if this deque changed as a result of the call).
4.352 + *
4.353 + * @param o element to be removed from this deque, if present
4.354 + * @return <tt>true</tt> if the deque contained the specified element
4.355 + */
4.356 + public boolean removeFirstOccurrence(Object o) {
4.357 + if (o == null)
4.358 + return false;
4.359 + int mask = elements.length - 1;
4.360 + int i = head;
4.361 + E x;
4.362 + while ( (x = elements[i]) != null) {
4.363 + if (o.equals(x)) {
4.364 + delete(i);
4.365 + return true;
4.366 + }
4.367 + i = (i + 1) & mask;
4.368 + }
4.369 + return false;
4.370 + }
4.371 +
4.372 + /**
4.373 + * Removes the last occurrence of the specified element in this
4.374 + * deque (when traversing the deque from head to tail).
4.375 + * If the deque does not contain the element, it is unchanged.
4.376 + * More formally, removes the last element <tt>e</tt> such that
4.377 + * <tt>o.equals(e)</tt> (if such an element exists).
4.378 + * Returns <tt>true</tt> if this deque contained the specified element
4.379 + * (or equivalently, if this deque changed as a result of the call).
4.380 + *
4.381 + * @param o element to be removed from this deque, if present
4.382 + * @return <tt>true</tt> if the deque contained the specified element
4.383 + */
4.384 + public boolean removeLastOccurrence(Object o) {
4.385 + if (o == null)
4.386 + return false;
4.387 + int mask = elements.length - 1;
4.388 + int i = (tail - 1) & mask;
4.389 + E x;
4.390 + while ( (x = elements[i]) != null) {
4.391 + if (o.equals(x)) {
4.392 + delete(i);
4.393 + return true;
4.394 + }
4.395 + i = (i - 1) & mask;
4.396 + }
4.397 + return false;
4.398 + }
4.399 +
4.400 + // *** Queue methods ***
4.401 +
4.402 + /**
4.403 + * Inserts the specified element at the end of this deque.
4.404 + *
4.405 + * <p>This method is equivalent to {@link #addLast}.
4.406 + *
4.407 + * @param e the element to add
4.408 + * @return <tt>true</tt> (as specified by {@link Collection#add})
4.409 + * @throws NullPointerException if the specified element is null
4.410 + */
4.411 + public boolean add(E e) {
4.412 + addLast(e);
4.413 + return true;
4.414 + }
4.415 +
4.416 + /**
4.417 + * Inserts the specified element at the end of this deque.
4.418 + *
4.419 + * <p>This method is equivalent to {@link #offerLast}.
4.420 + *
4.421 + * @param e the element to add
4.422 + * @return <tt>true</tt> (as specified by {@link Queue#offer})
4.423 + * @throws NullPointerException if the specified element is null
4.424 + */
4.425 + public boolean offer(E e) {
4.426 + return offerLast(e);
4.427 + }
4.428 +
4.429 + /**
4.430 + * Retrieves and removes the head of the queue represented by this deque.
4.431 + *
4.432 + * This method differs from {@link #poll poll} only in that it throws an
4.433 + * exception if this deque is empty.
4.434 + *
4.435 + * <p>This method is equivalent to {@link #removeFirst}.
4.436 + *
4.437 + * @return the head of the queue represented by this deque
4.438 + * @throws NoSuchElementException {@inheritDoc}
4.439 + */
4.440 + public E remove() {
4.441 + return removeFirst();
4.442 + }
4.443 +
4.444 + /**
4.445 + * Retrieves and removes the head of the queue represented by this deque
4.446 + * (in other words, the first element of this deque), or returns
4.447 + * <tt>null</tt> if this deque is empty.
4.448 + *
4.449 + * <p>This method is equivalent to {@link #pollFirst}.
4.450 + *
4.451 + * @return the head of the queue represented by this deque, or
4.452 + * <tt>null</tt> if this deque is empty
4.453 + */
4.454 + public E poll() {
4.455 + return pollFirst();
4.456 + }
4.457 +
4.458 + /**
4.459 + * Retrieves, but does not remove, the head of the queue represented by
4.460 + * this deque. This method differs from {@link #peek peek} only in
4.461 + * that it throws an exception if this deque is empty.
4.462 + *
4.463 + * <p>This method is equivalent to {@link #getFirst}.
4.464 + *
4.465 + * @return the head of the queue represented by this deque
4.466 + * @throws NoSuchElementException {@inheritDoc}
4.467 + */
4.468 + public E element() {
4.469 + return getFirst();
4.470 + }
4.471 +
4.472 + /**
4.473 + * Retrieves, but does not remove, the head of the queue represented by
4.474 + * this deque, or returns <tt>null</tt> if this deque is empty.
4.475 + *
4.476 + * <p>This method is equivalent to {@link #peekFirst}.
4.477 + *
4.478 + * @return the head of the queue represented by this deque, or
4.479 + * <tt>null</tt> if this deque is empty
4.480 + */
4.481 + public E peek() {
4.482 + return peekFirst();
4.483 + }
4.484 +
4.485 + // *** Stack methods ***
4.486 +
4.487 + /**
4.488 + * Pushes an element onto the stack represented by this deque. In other
4.489 + * words, inserts the element at the front of this deque.
4.490 + *
4.491 + * <p>This method is equivalent to {@link #addFirst}.
4.492 + *
4.493 + * @param e the element to push
4.494 + * @throws NullPointerException if the specified element is null
4.495 + */
4.496 + public void push(E e) {
4.497 + addFirst(e);
4.498 + }
4.499 +
4.500 + /**
4.501 + * Pops an element from the stack represented by this deque. In other
4.502 + * words, removes and returns the first element of this deque.
4.503 + *
4.504 + * <p>This method is equivalent to {@link #removeFirst()}.
4.505 + *
4.506 + * @return the element at the front of this deque (which is the top
4.507 + * of the stack represented by this deque)
4.508 + * @throws NoSuchElementException {@inheritDoc}
4.509 + */
4.510 + public E pop() {
4.511 + return removeFirst();
4.512 + }
4.513 +
4.514 + private void checkInvariants() {
4.515 + assert elements[tail] == null;
4.516 + assert head == tail ? elements[head] == null :
4.517 + (elements[head] != null &&
4.518 + elements[(tail - 1) & (elements.length - 1)] != null);
4.519 + assert elements[(head - 1) & (elements.length - 1)] == null;
4.520 + }
4.521 +
4.522 + /**
4.523 + * Removes the element at the specified position in the elements array,
4.524 + * adjusting head and tail as necessary. This can result in motion of
4.525 + * elements backwards or forwards in the array.
4.526 + *
4.527 + * <p>This method is called delete rather than remove to emphasize
4.528 + * that its semantics differ from those of {@link List#remove(int)}.
4.529 + *
4.530 + * @return true if elements moved backwards
4.531 + */
4.532 + private boolean delete(int i) {
4.533 + checkInvariants();
4.534 + final E[] elements = this.elements;
4.535 + final int mask = elements.length - 1;
4.536 + final int h = head;
4.537 + final int t = tail;
4.538 + final int front = (i - h) & mask;
4.539 + final int back = (t - i) & mask;
4.540 +
4.541 + // Invariant: head <= i < tail mod circularity
4.542 + if (front >= ((t - h) & mask))
4.543 + throw new ConcurrentModificationException();
4.544 +
4.545 + // Optimize for least element motion
4.546 + if (front < back) {
4.547 + if (h <= i) {
4.548 + System.arraycopy(elements, h, elements, h + 1, front);
4.549 + } else { // Wrap around
4.550 + System.arraycopy(elements, 0, elements, 1, i);
4.551 + elements[0] = elements[mask];
4.552 + System.arraycopy(elements, h, elements, h + 1, mask - h);
4.553 + }
4.554 + elements[h] = null;
4.555 + head = (h + 1) & mask;
4.556 + return false;
4.557 + } else {
4.558 + if (i < t) { // Copy the null tail as well
4.559 + System.arraycopy(elements, i + 1, elements, i, back);
4.560 + tail = t - 1;
4.561 + } else { // Wrap around
4.562 + System.arraycopy(elements, i + 1, elements, i, mask - i);
4.563 + elements[mask] = elements[0];
4.564 + System.arraycopy(elements, 1, elements, 0, t);
4.565 + tail = (t - 1) & mask;
4.566 + }
4.567 + return true;
4.568 + }
4.569 + }
4.570 +
4.571 + // *** Collection Methods ***
4.572 +
4.573 + /**
4.574 + * Returns the number of elements in this deque.
4.575 + *
4.576 + * @return the number of elements in this deque
4.577 + */
4.578 + public int size() {
4.579 + return (tail - head) & (elements.length - 1);
4.580 + }
4.581 +
4.582 + /**
4.583 + * Returns <tt>true</tt> if this deque contains no elements.
4.584 + *
4.585 + * @return <tt>true</tt> if this deque contains no elements
4.586 + */
4.587 + public boolean isEmpty() {
4.588 + return head == tail;
4.589 + }
4.590 +
4.591 + /**
4.592 + * Returns an iterator over the elements in this deque. The elements
4.593 + * will be ordered from first (head) to last (tail). This is the same
4.594 + * order that elements would be dequeued (via successive calls to
4.595 + * {@link #remove} or popped (via successive calls to {@link #pop}).
4.596 + *
4.597 + * @return an iterator over the elements in this deque
4.598 + */
4.599 + public Iterator<E> iterator() {
4.600 + return new DeqIterator();
4.601 + }
4.602 +
4.603 + public Iterator<E> descendingIterator() {
4.604 + return new DescendingIterator();
4.605 + }
4.606 +
4.607 + private class DeqIterator implements Iterator<E> {
4.608 + /**
4.609 + * Index of element to be returned by subsequent call to next.
4.610 + */
4.611 + private int cursor = head;
4.612 +
4.613 + /**
4.614 + * Tail recorded at construction (also in remove), to stop
4.615 + * iterator and also to check for comodification.
4.616 + */
4.617 + private int fence = tail;
4.618 +
4.619 + /**
4.620 + * Index of element returned by most recent call to next.
4.621 + * Reset to -1 if element is deleted by a call to remove.
4.622 + */
4.623 + private int lastRet = -1;
4.624 +
4.625 + public boolean hasNext() {
4.626 + return cursor != fence;
4.627 + }
4.628 +
4.629 + public E next() {
4.630 + if (cursor == fence)
4.631 + throw new NoSuchElementException();
4.632 + E result = elements[cursor];
4.633 + // This check doesn't catch all possible comodifications,
4.634 + // but does catch the ones that corrupt traversal
4.635 + if (tail != fence || result == null)
4.636 + throw new ConcurrentModificationException();
4.637 + lastRet = cursor;
4.638 + cursor = (cursor + 1) & (elements.length - 1);
4.639 + return result;
4.640 + }
4.641 +
4.642 + public void remove() {
4.643 + if (lastRet < 0)
4.644 + throw new IllegalStateException();
4.645 + if (delete(lastRet)) { // if left-shifted, undo increment in next()
4.646 + cursor = (cursor - 1) & (elements.length - 1);
4.647 + fence = tail;
4.648 + }
4.649 + lastRet = -1;
4.650 + }
4.651 + }
4.652 +
4.653 + private class DescendingIterator implements Iterator<E> {
4.654 + /*
4.655 + * This class is nearly a mirror-image of DeqIterator, using
4.656 + * tail instead of head for initial cursor, and head instead of
4.657 + * tail for fence.
4.658 + */
4.659 + private int cursor = tail;
4.660 + private int fence = head;
4.661 + private int lastRet = -1;
4.662 +
4.663 + public boolean hasNext() {
4.664 + return cursor != fence;
4.665 + }
4.666 +
4.667 + public E next() {
4.668 + if (cursor == fence)
4.669 + throw new NoSuchElementException();
4.670 + cursor = (cursor - 1) & (elements.length - 1);
4.671 + E result = elements[cursor];
4.672 + if (head != fence || result == null)
4.673 + throw new ConcurrentModificationException();
4.674 + lastRet = cursor;
4.675 + return result;
4.676 + }
4.677 +
4.678 + public void remove() {
4.679 + if (lastRet < 0)
4.680 + throw new IllegalStateException();
4.681 + if (!delete(lastRet)) {
4.682 + cursor = (cursor + 1) & (elements.length - 1);
4.683 + fence = head;
4.684 + }
4.685 + lastRet = -1;
4.686 + }
4.687 + }
4.688 +
4.689 + /**
4.690 + * Returns <tt>true</tt> if this deque contains the specified element.
4.691 + * More formally, returns <tt>true</tt> if and only if this deque contains
4.692 + * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
4.693 + *
4.694 + * @param o object to be checked for containment in this deque
4.695 + * @return <tt>true</tt> if this deque contains the specified element
4.696 + */
4.697 + public boolean contains(Object o) {
4.698 + if (o == null)
4.699 + return false;
4.700 + int mask = elements.length - 1;
4.701 + int i = head;
4.702 + E x;
4.703 + while ( (x = elements[i]) != null) {
4.704 + if (o.equals(x))
4.705 + return true;
4.706 + i = (i + 1) & mask;
4.707 + }
4.708 + return false;
4.709 + }
4.710 +
4.711 + /**
4.712 + * Removes a single instance of the specified element from this deque.
4.713 + * If the deque does not contain the element, it is unchanged.
4.714 + * More formally, removes the first element <tt>e</tt> such that
4.715 + * <tt>o.equals(e)</tt> (if such an element exists).
4.716 + * Returns <tt>true</tt> if this deque contained the specified element
4.717 + * (or equivalently, if this deque changed as a result of the call).
4.718 + *
4.719 + * <p>This method is equivalent to {@link #removeFirstOccurrence}.
4.720 + *
4.721 + * @param o element to be removed from this deque, if present
4.722 + * @return <tt>true</tt> if this deque contained the specified element
4.723 + */
4.724 + public boolean remove(Object o) {
4.725 + return removeFirstOccurrence(o);
4.726 + }
4.727 +
4.728 + /**
4.729 + * Removes all of the elements from this deque.
4.730 + * The deque will be empty after this call returns.
4.731 + */
4.732 + public void clear() {
4.733 + int h = head;
4.734 + int t = tail;
4.735 + if (h != t) { // clear all cells
4.736 + head = tail = 0;
4.737 + int i = h;
4.738 + int mask = elements.length - 1;
4.739 + do {
4.740 + elements[i] = null;
4.741 + i = (i + 1) & mask;
4.742 + } while (i != t);
4.743 + }
4.744 + }
4.745 +
4.746 + /**
4.747 + * Returns an array containing all of the elements in this deque
4.748 + * in proper sequence (from first to last element).
4.749 + *
4.750 + * <p>The returned array will be "safe" in that no references to it are
4.751 + * maintained by this deque. (In other words, this method must allocate
4.752 + * a new array). The caller is thus free to modify the returned array.
4.753 + *
4.754 + * <p>This method acts as bridge between array-based and collection-based
4.755 + * APIs.
4.756 + *
4.757 + * @return an array containing all of the elements in this deque
4.758 + */
4.759 + public Object[] toArray() {
4.760 + return copyElements(new Object[size()]);
4.761 + }
4.762 +
4.763 + /**
4.764 + * Returns an array containing all of the elements in this deque in
4.765 + * proper sequence (from first to last element); the runtime type of the
4.766 + * returned array is that of the specified array. If the deque fits in
4.767 + * the specified array, it is returned therein. Otherwise, a new array
4.768 + * is allocated with the runtime type of the specified array and the
4.769 + * size of this deque.
4.770 + *
4.771 + * <p>If this deque fits in the specified array with room to spare
4.772 + * (i.e., the array has more elements than this deque), the element in
4.773 + * the array immediately following the end of the deque is set to
4.774 + * <tt>null</tt>.
4.775 + *
4.776 + * <p>Like the {@link #toArray()} method, this method acts as bridge between
4.777 + * array-based and collection-based APIs. Further, this method allows
4.778 + * precise control over the runtime type of the output array, and may,
4.779 + * under certain circumstances, be used to save allocation costs.
4.780 + *
4.781 + * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
4.782 + * The following code can be used to dump the deque into a newly
4.783 + * allocated array of <tt>String</tt>:
4.784 + *
4.785 + * <pre>
4.786 + * String[] y = x.toArray(new String[0]);</pre>
4.787 + *
4.788 + * Note that <tt>toArray(new Object[0])</tt> is identical in function to
4.789 + * <tt>toArray()</tt>.
4.790 + *
4.791 + * @param a the array into which the elements of the deque are to
4.792 + * be stored, if it is big enough; otherwise, a new array of the
4.793 + * same runtime type is allocated for this purpose
4.794 + * @return an array containing all of the elements in this deque
4.795 + * @throws ArrayStoreException if the runtime type of the specified array
4.796 + * is not a supertype of the runtime type of every element in
4.797 + * this deque
4.798 + * @throws NullPointerException if the specified array is null
4.799 + */
4.800 + public <T> T[] toArray(T[] a) {
4.801 + int size = size();
4.802 + if (a.length < size)
4.803 + a = (T[])java.lang.reflect.Array.newInstance(
4.804 + a.getClass().getComponentType(), size);
4.805 + copyElements(a);
4.806 + if (a.length > size)
4.807 + a[size] = null;
4.808 + return a;
4.809 + }
4.810 +
4.811 + // *** Object methods ***
4.812 +
4.813 + /**
4.814 + * Returns a copy of this deque.
4.815 + *
4.816 + * @return a copy of this deque
4.817 + */
4.818 + public ArrayDeque<E> clone() {
4.819 + try {
4.820 + ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
4.821 + result.elements = Arrays.copyOf(elements, elements.length);
4.822 + return result;
4.823 +
4.824 + } catch (CloneNotSupportedException e) {
4.825 + throw new AssertionError();
4.826 + }
4.827 + }
4.828 +
4.829 + /**
4.830 + * Appease the serialization gods.
4.831 + */
4.832 + private static final long serialVersionUID = 2340985798034038923L;
4.833 +
4.834 +}
5.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
5.2 +++ b/emul/compact/src/main/java/java/util/Collections.java Mon Jan 28 18:14:00 2013 +0100
5.3 @@ -0,0 +1,3954 @@
5.4 +/*
5.5 + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
5.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5.7 + *
5.8 + * This code is free software; you can redistribute it and/or modify it
5.9 + * under the terms of the GNU General Public License version 2 only, as
5.10 + * published by the Free Software Foundation. Oracle designates this
5.11 + * particular file as subject to the "Classpath" exception as provided
5.12 + * by Oracle in the LICENSE file that accompanied this code.
5.13 + *
5.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
5.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
5.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
5.17 + * version 2 for more details (a copy is included in the LICENSE file that
5.18 + * accompanied this code).
5.19 + *
5.20 + * You should have received a copy of the GNU General Public License version
5.21 + * 2 along with this work; if not, write to the Free Software Foundation,
5.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
5.23 + *
5.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
5.25 + * or visit www.oracle.com if you need additional information or have any
5.26 + * questions.
5.27 + */
5.28 +
5.29 +package java.util;
5.30 +import java.io.Serializable;
5.31 +import java.io.IOException;
5.32 +import java.lang.reflect.Array;
5.33 +import org.apidesign.bck2brwsr.emul.lang.System;
5.34 +
5.35 +/**
5.36 + * This class consists exclusively of static methods that operate on or return
5.37 + * collections. It contains polymorphic algorithms that operate on
5.38 + * collections, "wrappers", which return a new collection backed by a
5.39 + * specified collection, and a few other odds and ends.
5.40 + *
5.41 + * <p>The methods of this class all throw a <tt>NullPointerException</tt>
5.42 + * if the collections or class objects provided to them are null.
5.43 + *
5.44 + * <p>The documentation for the polymorphic algorithms contained in this class
5.45 + * generally includes a brief description of the <i>implementation</i>. Such
5.46 + * descriptions should be regarded as <i>implementation notes</i>, rather than
5.47 + * parts of the <i>specification</i>. Implementors should feel free to
5.48 + * substitute other algorithms, so long as the specification itself is adhered
5.49 + * to. (For example, the algorithm used by <tt>sort</tt> does not have to be
5.50 + * a mergesort, but it does have to be <i>stable</i>.)
5.51 + *
5.52 + * <p>The "destructive" algorithms contained in this class, that is, the
5.53 + * algorithms that modify the collection on which they operate, are specified
5.54 + * to throw <tt>UnsupportedOperationException</tt> if the collection does not
5.55 + * support the appropriate mutation primitive(s), such as the <tt>set</tt>
5.56 + * method. These algorithms may, but are not required to, throw this
5.57 + * exception if an invocation would have no effect on the collection. For
5.58 + * example, invoking the <tt>sort</tt> method on an unmodifiable list that is
5.59 + * already sorted may or may not throw <tt>UnsupportedOperationException</tt>.
5.60 + *
5.61 + * <p>This class is a member of the
5.62 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
5.63 + * Java Collections Framework</a>.
5.64 + *
5.65 + * @author Josh Bloch
5.66 + * @author Neal Gafter
5.67 + * @see Collection
5.68 + * @see Set
5.69 + * @see List
5.70 + * @see Map
5.71 + * @since 1.2
5.72 + */
5.73 +
5.74 +public class Collections {
5.75 + // Suppresses default constructor, ensuring non-instantiability.
5.76 + private Collections() {
5.77 + }
5.78 +
5.79 + // Algorithms
5.80 +
5.81 + /*
5.82 + * Tuning parameters for algorithms - Many of the List algorithms have
5.83 + * two implementations, one of which is appropriate for RandomAccess
5.84 + * lists, the other for "sequential." Often, the random access variant
5.85 + * yields better performance on small sequential access lists. The
5.86 + * tuning parameters below determine the cutoff point for what constitutes
5.87 + * a "small" sequential access list for each algorithm. The values below
5.88 + * were empirically determined to work well for LinkedList. Hopefully
5.89 + * they should be reasonable for other sequential access List
5.90 + * implementations. Those doing performance work on this code would
5.91 + * do well to validate the values of these parameters from time to time.
5.92 + * (The first word of each tuning parameter name is the algorithm to which
5.93 + * it applies.)
5.94 + */
5.95 + private static final int BINARYSEARCH_THRESHOLD = 5000;
5.96 + private static final int REVERSE_THRESHOLD = 18;
5.97 + private static final int SHUFFLE_THRESHOLD = 5;
5.98 + private static final int FILL_THRESHOLD = 25;
5.99 + private static final int ROTATE_THRESHOLD = 100;
5.100 + private static final int COPY_THRESHOLD = 10;
5.101 + private static final int REPLACEALL_THRESHOLD = 11;
5.102 + private static final int INDEXOFSUBLIST_THRESHOLD = 35;
5.103 +
5.104 + /**
5.105 + * Sorts the specified list into ascending order, according to the
5.106 + * {@linkplain Comparable natural ordering} of its elements.
5.107 + * All elements in the list must implement the {@link Comparable}
5.108 + * interface. Furthermore, all elements in the list must be
5.109 + * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)}
5.110 + * must not throw a {@code ClassCastException} for any elements
5.111 + * {@code e1} and {@code e2} in the list).
5.112 + *
5.113 + * <p>This sort is guaranteed to be <i>stable</i>: equal elements will
5.114 + * not be reordered as a result of the sort.
5.115 + *
5.116 + * <p>The specified list must be modifiable, but need not be resizable.
5.117 + *
5.118 + * <p>Implementation note: This implementation is a stable, adaptive,
5.119 + * iterative mergesort that requires far fewer than n lg(n) comparisons
5.120 + * when the input array is partially sorted, while offering the
5.121 + * performance of a traditional mergesort when the input array is
5.122 + * randomly ordered. If the input array is nearly sorted, the
5.123 + * implementation requires approximately n comparisons. Temporary
5.124 + * storage requirements vary from a small constant for nearly sorted
5.125 + * input arrays to n/2 object references for randomly ordered input
5.126 + * arrays.
5.127 + *
5.128 + * <p>The implementation takes equal advantage of ascending and
5.129 + * descending order in its input array, and can take advantage of
5.130 + * ascending and descending order in different parts of the same
5.131 + * input array. It is well-suited to merging two or more sorted arrays:
5.132 + * simply concatenate the arrays and sort the resulting array.
5.133 + *
5.134 + * <p>The implementation was adapted from Tim Peters's list sort for Python
5.135 + * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
5.136 + * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic
5.137 + * Sorting and Information Theoretic Complexity", in Proceedings of the
5.138 + * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
5.139 + * January 1993.
5.140 + *
5.141 + * <p>This implementation dumps the specified list into an array, sorts
5.142 + * the array, and iterates over the list resetting each element
5.143 + * from the corresponding position in the array. This avoids the
5.144 + * n<sup>2</sup> log(n) performance that would result from attempting
5.145 + * to sort a linked list in place.
5.146 + *
5.147 + * @param list the list to be sorted.
5.148 + * @throws ClassCastException if the list contains elements that are not
5.149 + * <i>mutually comparable</i> (for example, strings and integers).
5.150 + * @throws UnsupportedOperationException if the specified list's
5.151 + * list-iterator does not support the {@code set} operation.
5.152 + * @throws IllegalArgumentException (optional) if the implementation
5.153 + * detects that the natural ordering of the list elements is
5.154 + * found to violate the {@link Comparable} contract
5.155 + */
5.156 + public static <T extends Comparable<? super T>> void sort(List<T> list) {
5.157 + Object[] a = list.toArray();
5.158 + Arrays.sort(a);
5.159 + ListIterator<T> i = list.listIterator();
5.160 + for (int j=0; j<a.length; j++) {
5.161 + i.next();
5.162 + i.set((T)a[j]);
5.163 + }
5.164 + }
5.165 +
5.166 + /**
5.167 + * Sorts the specified list according to the order induced by the
5.168 + * specified comparator. All elements in the list must be <i>mutually
5.169 + * comparable</i> using the specified comparator (that is,
5.170 + * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
5.171 + * for any elements {@code e1} and {@code e2} in the list).
5.172 + *
5.173 + * <p>This sort is guaranteed to be <i>stable</i>: equal elements will
5.174 + * not be reordered as a result of the sort.
5.175 + *
5.176 + * <p>The specified list must be modifiable, but need not be resizable.
5.177 + *
5.178 + * <p>Implementation note: This implementation is a stable, adaptive,
5.179 + * iterative mergesort that requires far fewer than n lg(n) comparisons
5.180 + * when the input array is partially sorted, while offering the
5.181 + * performance of a traditional mergesort when the input array is
5.182 + * randomly ordered. If the input array is nearly sorted, the
5.183 + * implementation requires approximately n comparisons. Temporary
5.184 + * storage requirements vary from a small constant for nearly sorted
5.185 + * input arrays to n/2 object references for randomly ordered input
5.186 + * arrays.
5.187 + *
5.188 + * <p>The implementation takes equal advantage of ascending and
5.189 + * descending order in its input array, and can take advantage of
5.190 + * ascending and descending order in different parts of the same
5.191 + * input array. It is well-suited to merging two or more sorted arrays:
5.192 + * simply concatenate the arrays and sort the resulting array.
5.193 + *
5.194 + * <p>The implementation was adapted from Tim Peters's list sort for Python
5.195 + * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
5.196 + * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic
5.197 + * Sorting and Information Theoretic Complexity", in Proceedings of the
5.198 + * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
5.199 + * January 1993.
5.200 + *
5.201 + * <p>This implementation dumps the specified list into an array, sorts
5.202 + * the array, and iterates over the list resetting each element
5.203 + * from the corresponding position in the array. This avoids the
5.204 + * n<sup>2</sup> log(n) performance that would result from attempting
5.205 + * to sort a linked list in place.
5.206 + *
5.207 + * @param list the list to be sorted.
5.208 + * @param c the comparator to determine the order of the list. A
5.209 + * {@code null} value indicates that the elements' <i>natural
5.210 + * ordering</i> should be used.
5.211 + * @throws ClassCastException if the list contains elements that are not
5.212 + * <i>mutually comparable</i> using the specified comparator.
5.213 + * @throws UnsupportedOperationException if the specified list's
5.214 + * list-iterator does not support the {@code set} operation.
5.215 + * @throws IllegalArgumentException (optional) if the comparator is
5.216 + * found to violate the {@link Comparator} contract
5.217 + */
5.218 + public static <T> void sort(List<T> list, Comparator<? super T> c) {
5.219 + Object[] a = list.toArray();
5.220 + Arrays.sort(a, (Comparator)c);
5.221 + ListIterator i = list.listIterator();
5.222 + for (int j=0; j<a.length; j++) {
5.223 + i.next();
5.224 + i.set(a[j]);
5.225 + }
5.226 + }
5.227 +
5.228 +
5.229 + /**
5.230 + * Searches the specified list for the specified object using the binary
5.231 + * search algorithm. The list must be sorted into ascending order
5.232 + * according to the {@linkplain Comparable natural ordering} of its
5.233 + * elements (as by the {@link #sort(List)} method) prior to making this
5.234 + * call. If it is not sorted, the results are undefined. If the list
5.235 + * contains multiple elements equal to the specified object, there is no
5.236 + * guarantee which one will be found.
5.237 + *
5.238 + * <p>This method runs in log(n) time for a "random access" list (which
5.239 + * provides near-constant-time positional access). If the specified list
5.240 + * does not implement the {@link RandomAccess} interface and is large,
5.241 + * this method will do an iterator-based binary search that performs
5.242 + * O(n) link traversals and O(log n) element comparisons.
5.243 + *
5.244 + * @param list the list to be searched.
5.245 + * @param key the key to be searched for.
5.246 + * @return the index of the search key, if it is contained in the list;
5.247 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
5.248 + * <i>insertion point</i> is defined as the point at which the
5.249 + * key would be inserted into the list: the index of the first
5.250 + * element greater than the key, or <tt>list.size()</tt> if all
5.251 + * elements in the list are less than the specified key. Note
5.252 + * that this guarantees that the return value will be >= 0 if
5.253 + * and only if the key is found.
5.254 + * @throws ClassCastException if the list contains elements that are not
5.255 + * <i>mutually comparable</i> (for example, strings and
5.256 + * integers), or the search key is not mutually comparable
5.257 + * with the elements of the list.
5.258 + */
5.259 + public static <T>
5.260 + int binarySearch(List<? extends Comparable<? super T>> list, T key) {
5.261 + if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
5.262 + return Collections.indexedBinarySearch(list, key);
5.263 + else
5.264 + return Collections.iteratorBinarySearch(list, key);
5.265 + }
5.266 +
5.267 + private static <T>
5.268 + int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key)
5.269 + {
5.270 + int low = 0;
5.271 + int high = list.size()-1;
5.272 +
5.273 + while (low <= high) {
5.274 + int mid = (low + high) >>> 1;
5.275 + Comparable<? super T> midVal = list.get(mid);
5.276 + int cmp = midVal.compareTo(key);
5.277 +
5.278 + if (cmp < 0)
5.279 + low = mid + 1;
5.280 + else if (cmp > 0)
5.281 + high = mid - 1;
5.282 + else
5.283 + return mid; // key found
5.284 + }
5.285 + return -(low + 1); // key not found
5.286 + }
5.287 +
5.288 + private static <T>
5.289 + int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key)
5.290 + {
5.291 + int low = 0;
5.292 + int high = list.size()-1;
5.293 + ListIterator<? extends Comparable<? super T>> i = list.listIterator();
5.294 +
5.295 + while (low <= high) {
5.296 + int mid = (low + high) >>> 1;
5.297 + Comparable<? super T> midVal = get(i, mid);
5.298 + int cmp = midVal.compareTo(key);
5.299 +
5.300 + if (cmp < 0)
5.301 + low = mid + 1;
5.302 + else if (cmp > 0)
5.303 + high = mid - 1;
5.304 + else
5.305 + return mid; // key found
5.306 + }
5.307 + return -(low + 1); // key not found
5.308 + }
5.309 +
5.310 + /**
5.311 + * Gets the ith element from the given list by repositioning the specified
5.312 + * list listIterator.
5.313 + */
5.314 + private static <T> T get(ListIterator<? extends T> i, int index) {
5.315 + T obj = null;
5.316 + int pos = i.nextIndex();
5.317 + if (pos <= index) {
5.318 + do {
5.319 + obj = i.next();
5.320 + } while (pos++ < index);
5.321 + } else {
5.322 + do {
5.323 + obj = i.previous();
5.324 + } while (--pos > index);
5.325 + }
5.326 + return obj;
5.327 + }
5.328 +
5.329 + /**
5.330 + * Searches the specified list for the specified object using the binary
5.331 + * search algorithm. The list must be sorted into ascending order
5.332 + * according to the specified comparator (as by the
5.333 + * {@link #sort(List, Comparator) sort(List, Comparator)}
5.334 + * method), prior to making this call. If it is
5.335 + * not sorted, the results are undefined. If the list contains multiple
5.336 + * elements equal to the specified object, there is no guarantee which one
5.337 + * will be found.
5.338 + *
5.339 + * <p>This method runs in log(n) time for a "random access" list (which
5.340 + * provides near-constant-time positional access). If the specified list
5.341 + * does not implement the {@link RandomAccess} interface and is large,
5.342 + * this method will do an iterator-based binary search that performs
5.343 + * O(n) link traversals and O(log n) element comparisons.
5.344 + *
5.345 + * @param list the list to be searched.
5.346 + * @param key the key to be searched for.
5.347 + * @param c the comparator by which the list is ordered.
5.348 + * A <tt>null</tt> value indicates that the elements'
5.349 + * {@linkplain Comparable natural ordering} should be used.
5.350 + * @return the index of the search key, if it is contained in the list;
5.351 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
5.352 + * <i>insertion point</i> is defined as the point at which the
5.353 + * key would be inserted into the list: the index of the first
5.354 + * element greater than the key, or <tt>list.size()</tt> if all
5.355 + * elements in the list are less than the specified key. Note
5.356 + * that this guarantees that the return value will be >= 0 if
5.357 + * and only if the key is found.
5.358 + * @throws ClassCastException if the list contains elements that are not
5.359 + * <i>mutually comparable</i> using the specified comparator,
5.360 + * or the search key is not mutually comparable with the
5.361 + * elements of the list using this comparator.
5.362 + */
5.363 + public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {
5.364 + if (c==null)
5.365 + return binarySearch((List) list, key);
5.366 +
5.367 + if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
5.368 + return Collections.indexedBinarySearch(list, key, c);
5.369 + else
5.370 + return Collections.iteratorBinarySearch(list, key, c);
5.371 + }
5.372 +
5.373 + private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
5.374 + int low = 0;
5.375 + int high = l.size()-1;
5.376 +
5.377 + while (low <= high) {
5.378 + int mid = (low + high) >>> 1;
5.379 + T midVal = l.get(mid);
5.380 + int cmp = c.compare(midVal, key);
5.381 +
5.382 + if (cmp < 0)
5.383 + low = mid + 1;
5.384 + else if (cmp > 0)
5.385 + high = mid - 1;
5.386 + else
5.387 + return mid; // key found
5.388 + }
5.389 + return -(low + 1); // key not found
5.390 + }
5.391 +
5.392 + private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
5.393 + int low = 0;
5.394 + int high = l.size()-1;
5.395 + ListIterator<? extends T> i = l.listIterator();
5.396 +
5.397 + while (low <= high) {
5.398 + int mid = (low + high) >>> 1;
5.399 + T midVal = get(i, mid);
5.400 + int cmp = c.compare(midVal, key);
5.401 +
5.402 + if (cmp < 0)
5.403 + low = mid + 1;
5.404 + else if (cmp > 0)
5.405 + high = mid - 1;
5.406 + else
5.407 + return mid; // key found
5.408 + }
5.409 + return -(low + 1); // key not found
5.410 + }
5.411 +
5.412 + private interface SelfComparable extends Comparable<SelfComparable> {}
5.413 +
5.414 +
5.415 + /**
5.416 + * Reverses the order of the elements in the specified list.<p>
5.417 + *
5.418 + * This method runs in linear time.
5.419 + *
5.420 + * @param list the list whose elements are to be reversed.
5.421 + * @throws UnsupportedOperationException if the specified list or
5.422 + * its list-iterator does not support the <tt>set</tt> operation.
5.423 + */
5.424 + public static void reverse(List<?> list) {
5.425 + int size = list.size();
5.426 + if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
5.427 + for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
5.428 + swap(list, i, j);
5.429 + } else {
5.430 + ListIterator fwd = list.listIterator();
5.431 + ListIterator rev = list.listIterator(size);
5.432 + for (int i=0, mid=list.size()>>1; i<mid; i++) {
5.433 + Object tmp = fwd.next();
5.434 + fwd.set(rev.previous());
5.435 + rev.set(tmp);
5.436 + }
5.437 + }
5.438 + }
5.439 +
5.440 + /**
5.441 + * Randomly permutes the specified list using a default source of
5.442 + * randomness. All permutations occur with approximately equal
5.443 + * likelihood.<p>
5.444 + *
5.445 + * The hedge "approximately" is used in the foregoing description because
5.446 + * default source of randomness is only approximately an unbiased source
5.447 + * of independently chosen bits. If it were a perfect source of randomly
5.448 + * chosen bits, then the algorithm would choose permutations with perfect
5.449 + * uniformity.<p>
5.450 + *
5.451 + * This implementation traverses the list backwards, from the last element
5.452 + * up to the second, repeatedly swapping a randomly selected element into
5.453 + * the "current position". Elements are randomly selected from the
5.454 + * portion of the list that runs from the first element to the current
5.455 + * position, inclusive.<p>
5.456 + *
5.457 + * This method runs in linear time. If the specified list does not
5.458 + * implement the {@link RandomAccess} interface and is large, this
5.459 + * implementation dumps the specified list into an array before shuffling
5.460 + * it, and dumps the shuffled array back into the list. This avoids the
5.461 + * quadratic behavior that would result from shuffling a "sequential
5.462 + * access" list in place.
5.463 + *
5.464 + * @param list the list to be shuffled.
5.465 + * @throws UnsupportedOperationException if the specified list or
5.466 + * its list-iterator does not support the <tt>set</tt> operation.
5.467 + */
5.468 + public static void shuffle(List<?> list) {
5.469 + Random rnd = r;
5.470 + if (rnd == null)
5.471 + r = rnd = new Random();
5.472 + shuffle(list, rnd);
5.473 + }
5.474 + private static Random r;
5.475 +
5.476 + /**
5.477 + * Randomly permute the specified list using the specified source of
5.478 + * randomness. All permutations occur with equal likelihood
5.479 + * assuming that the source of randomness is fair.<p>
5.480 + *
5.481 + * This implementation traverses the list backwards, from the last element
5.482 + * up to the second, repeatedly swapping a randomly selected element into
5.483 + * the "current position". Elements are randomly selected from the
5.484 + * portion of the list that runs from the first element to the current
5.485 + * position, inclusive.<p>
5.486 + *
5.487 + * This method runs in linear time. If the specified list does not
5.488 + * implement the {@link RandomAccess} interface and is large, this
5.489 + * implementation dumps the specified list into an array before shuffling
5.490 + * it, and dumps the shuffled array back into the list. This avoids the
5.491 + * quadratic behavior that would result from shuffling a "sequential
5.492 + * access" list in place.
5.493 + *
5.494 + * @param list the list to be shuffled.
5.495 + * @param rnd the source of randomness to use to shuffle the list.
5.496 + * @throws UnsupportedOperationException if the specified list or its
5.497 + * list-iterator does not support the <tt>set</tt> operation.
5.498 + */
5.499 + public static void shuffle(List<?> list, Random rnd) {
5.500 + int size = list.size();
5.501 + if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
5.502 + for (int i=size; i>1; i--)
5.503 + swap(list, i-1, rnd.nextInt(i));
5.504 + } else {
5.505 + Object arr[] = list.toArray();
5.506 +
5.507 + // Shuffle array
5.508 + for (int i=size; i>1; i--)
5.509 + swap(arr, i-1, rnd.nextInt(i));
5.510 +
5.511 + // Dump array back into list
5.512 + ListIterator it = list.listIterator();
5.513 + for (int i=0; i<arr.length; i++) {
5.514 + it.next();
5.515 + it.set(arr[i]);
5.516 + }
5.517 + }
5.518 + }
5.519 +
5.520 + /**
5.521 + * Swaps the elements at the specified positions in the specified list.
5.522 + * (If the specified positions are equal, invoking this method leaves
5.523 + * the list unchanged.)
5.524 + *
5.525 + * @param list The list in which to swap elements.
5.526 + * @param i the index of one element to be swapped.
5.527 + * @param j the index of the other element to be swapped.
5.528 + * @throws IndexOutOfBoundsException if either <tt>i</tt> or <tt>j</tt>
5.529 + * is out of range (i < 0 || i >= list.size()
5.530 + * || j < 0 || j >= list.size()).
5.531 + * @since 1.4
5.532 + */
5.533 + public static void swap(List<?> list, int i, int j) {
5.534 + final List l = list;
5.535 + l.set(i, l.set(j, l.get(i)));
5.536 + }
5.537 +
5.538 + /**
5.539 + * Swaps the two specified elements in the specified array.
5.540 + */
5.541 + private static void swap(Object[] arr, int i, int j) {
5.542 + Object tmp = arr[i];
5.543 + arr[i] = arr[j];
5.544 + arr[j] = tmp;
5.545 + }
5.546 +
5.547 + /**
5.548 + * Replaces all of the elements of the specified list with the specified
5.549 + * element. <p>
5.550 + *
5.551 + * This method runs in linear time.
5.552 + *
5.553 + * @param list the list to be filled with the specified element.
5.554 + * @param obj The element with which to fill the specified list.
5.555 + * @throws UnsupportedOperationException if the specified list or its
5.556 + * list-iterator does not support the <tt>set</tt> operation.
5.557 + */
5.558 + public static <T> void fill(List<? super T> list, T obj) {
5.559 + int size = list.size();
5.560 +
5.561 + if (size < FILL_THRESHOLD || list instanceof RandomAccess) {
5.562 + for (int i=0; i<size; i++)
5.563 + list.set(i, obj);
5.564 + } else {
5.565 + ListIterator<? super T> itr = list.listIterator();
5.566 + for (int i=0; i<size; i++) {
5.567 + itr.next();
5.568 + itr.set(obj);
5.569 + }
5.570 + }
5.571 + }
5.572 +
5.573 + /**
5.574 + * Copies all of the elements from one list into another. After the
5.575 + * operation, the index of each copied element in the destination list
5.576 + * will be identical to its index in the source list. The destination
5.577 + * list must be at least as long as the source list. If it is longer, the
5.578 + * remaining elements in the destination list are unaffected. <p>
5.579 + *
5.580 + * This method runs in linear time.
5.581 + *
5.582 + * @param dest The destination list.
5.583 + * @param src The source list.
5.584 + * @throws IndexOutOfBoundsException if the destination list is too small
5.585 + * to contain the entire source List.
5.586 + * @throws UnsupportedOperationException if the destination list's
5.587 + * list-iterator does not support the <tt>set</tt> operation.
5.588 + */
5.589 + public static <T> void copy(List<? super T> dest, List<? extends T> src) {
5.590 + int srcSize = src.size();
5.591 + if (srcSize > dest.size())
5.592 + throw new IndexOutOfBoundsException("Source does not fit in dest");
5.593 +
5.594 + if (srcSize < COPY_THRESHOLD ||
5.595 + (src instanceof RandomAccess && dest instanceof RandomAccess)) {
5.596 + for (int i=0; i<srcSize; i++)
5.597 + dest.set(i, src.get(i));
5.598 + } else {
5.599 + ListIterator<? super T> di=dest.listIterator();
5.600 + ListIterator<? extends T> si=src.listIterator();
5.601 + for (int i=0; i<srcSize; i++) {
5.602 + di.next();
5.603 + di.set(si.next());
5.604 + }
5.605 + }
5.606 + }
5.607 +
5.608 + /**
5.609 + * Returns the minimum element of the given collection, according to the
5.610 + * <i>natural ordering</i> of its elements. All elements in the
5.611 + * collection must implement the <tt>Comparable</tt> interface.
5.612 + * Furthermore, all elements in the collection must be <i>mutually
5.613 + * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a
5.614 + * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
5.615 + * <tt>e2</tt> in the collection).<p>
5.616 + *
5.617 + * This method iterates over the entire collection, hence it requires
5.618 + * time proportional to the size of the collection.
5.619 + *
5.620 + * @param coll the collection whose minimum element is to be determined.
5.621 + * @return the minimum element of the given collection, according
5.622 + * to the <i>natural ordering</i> of its elements.
5.623 + * @throws ClassCastException if the collection contains elements that are
5.624 + * not <i>mutually comparable</i> (for example, strings and
5.625 + * integers).
5.626 + * @throws NoSuchElementException if the collection is empty.
5.627 + * @see Comparable
5.628 + */
5.629 + public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
5.630 + Iterator<? extends T> i = coll.iterator();
5.631 + T candidate = i.next();
5.632 +
5.633 + while (i.hasNext()) {
5.634 + T next = i.next();
5.635 + if (next.compareTo(candidate) < 0)
5.636 + candidate = next;
5.637 + }
5.638 + return candidate;
5.639 + }
5.640 +
5.641 + /**
5.642 + * Returns the minimum element of the given collection, according to the
5.643 + * order induced by the specified comparator. All elements in the
5.644 + * collection must be <i>mutually comparable</i> by the specified
5.645 + * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a
5.646 + * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
5.647 + * <tt>e2</tt> in the collection).<p>
5.648 + *
5.649 + * This method iterates over the entire collection, hence it requires
5.650 + * time proportional to the size of the collection.
5.651 + *
5.652 + * @param coll the collection whose minimum element is to be determined.
5.653 + * @param comp the comparator with which to determine the minimum element.
5.654 + * A <tt>null</tt> value indicates that the elements' <i>natural
5.655 + * ordering</i> should be used.
5.656 + * @return the minimum element of the given collection, according
5.657 + * to the specified comparator.
5.658 + * @throws ClassCastException if the collection contains elements that are
5.659 + * not <i>mutually comparable</i> using the specified comparator.
5.660 + * @throws NoSuchElementException if the collection is empty.
5.661 + * @see Comparable
5.662 + */
5.663 + public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
5.664 + if (comp==null)
5.665 + return (T)min((Collection<SelfComparable>) (Collection) coll);
5.666 +
5.667 + Iterator<? extends T> i = coll.iterator();
5.668 + T candidate = i.next();
5.669 +
5.670 + while (i.hasNext()) {
5.671 + T next = i.next();
5.672 + if (comp.compare(next, candidate) < 0)
5.673 + candidate = next;
5.674 + }
5.675 + return candidate;
5.676 + }
5.677 +
5.678 + /**
5.679 + * Returns the maximum element of the given collection, according to the
5.680 + * <i>natural ordering</i> of its elements. All elements in the
5.681 + * collection must implement the <tt>Comparable</tt> interface.
5.682 + * Furthermore, all elements in the collection must be <i>mutually
5.683 + * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a
5.684 + * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
5.685 + * <tt>e2</tt> in the collection).<p>
5.686 + *
5.687 + * This method iterates over the entire collection, hence it requires
5.688 + * time proportional to the size of the collection.
5.689 + *
5.690 + * @param coll the collection whose maximum element is to be determined.
5.691 + * @return the maximum element of the given collection, according
5.692 + * to the <i>natural ordering</i> of its elements.
5.693 + * @throws ClassCastException if the collection contains elements that are
5.694 + * not <i>mutually comparable</i> (for example, strings and
5.695 + * integers).
5.696 + * @throws NoSuchElementException if the collection is empty.
5.697 + * @see Comparable
5.698 + */
5.699 + public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
5.700 + Iterator<? extends T> i = coll.iterator();
5.701 + T candidate = i.next();
5.702 +
5.703 + while (i.hasNext()) {
5.704 + T next = i.next();
5.705 + if (next.compareTo(candidate) > 0)
5.706 + candidate = next;
5.707 + }
5.708 + return candidate;
5.709 + }
5.710 +
5.711 + /**
5.712 + * Returns the maximum element of the given collection, according to the
5.713 + * order induced by the specified comparator. All elements in the
5.714 + * collection must be <i>mutually comparable</i> by the specified
5.715 + * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a
5.716 + * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
5.717 + * <tt>e2</tt> in the collection).<p>
5.718 + *
5.719 + * This method iterates over the entire collection, hence it requires
5.720 + * time proportional to the size of the collection.
5.721 + *
5.722 + * @param coll the collection whose maximum element is to be determined.
5.723 + * @param comp the comparator with which to determine the maximum element.
5.724 + * A <tt>null</tt> value indicates that the elements' <i>natural
5.725 + * ordering</i> should be used.
5.726 + * @return the maximum element of the given collection, according
5.727 + * to the specified comparator.
5.728 + * @throws ClassCastException if the collection contains elements that are
5.729 + * not <i>mutually comparable</i> using the specified comparator.
5.730 + * @throws NoSuchElementException if the collection is empty.
5.731 + * @see Comparable
5.732 + */
5.733 + public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
5.734 + if (comp==null)
5.735 + return (T)max((Collection<SelfComparable>) (Collection) coll);
5.736 +
5.737 + Iterator<? extends T> i = coll.iterator();
5.738 + T candidate = i.next();
5.739 +
5.740 + while (i.hasNext()) {
5.741 + T next = i.next();
5.742 + if (comp.compare(next, candidate) > 0)
5.743 + candidate = next;
5.744 + }
5.745 + return candidate;
5.746 + }
5.747 +
5.748 + /**
5.749 + * Rotates the elements in the specified list by the specified distance.
5.750 + * After calling this method, the element at index <tt>i</tt> will be
5.751 + * the element previously at index <tt>(i - distance)</tt> mod
5.752 + * <tt>list.size()</tt>, for all values of <tt>i</tt> between <tt>0</tt>
5.753 + * and <tt>list.size()-1</tt>, inclusive. (This method has no effect on
5.754 + * the size of the list.)
5.755 + *
5.756 + * <p>For example, suppose <tt>list</tt> comprises<tt> [t, a, n, k, s]</tt>.
5.757 + * After invoking <tt>Collections.rotate(list, 1)</tt> (or
5.758 + * <tt>Collections.rotate(list, -4)</tt>), <tt>list</tt> will comprise
5.759 + * <tt>[s, t, a, n, k]</tt>.
5.760 + *
5.761 + * <p>Note that this method can usefully be applied to sublists to
5.762 + * move one or more elements within a list while preserving the
5.763 + * order of the remaining elements. For example, the following idiom
5.764 + * moves the element at index <tt>j</tt> forward to position
5.765 + * <tt>k</tt> (which must be greater than or equal to <tt>j</tt>):
5.766 + * <pre>
5.767 + * Collections.rotate(list.subList(j, k+1), -1);
5.768 + * </pre>
5.769 + * To make this concrete, suppose <tt>list</tt> comprises
5.770 + * <tt>[a, b, c, d, e]</tt>. To move the element at index <tt>1</tt>
5.771 + * (<tt>b</tt>) forward two positions, perform the following invocation:
5.772 + * <pre>
5.773 + * Collections.rotate(l.subList(1, 4), -1);
5.774 + * </pre>
5.775 + * The resulting list is <tt>[a, c, d, b, e]</tt>.
5.776 + *
5.777 + * <p>To move more than one element forward, increase the absolute value
5.778 + * of the rotation distance. To move elements backward, use a positive
5.779 + * shift distance.
5.780 + *
5.781 + * <p>If the specified list is small or implements the {@link
5.782 + * RandomAccess} interface, this implementation exchanges the first
5.783 + * element into the location it should go, and then repeatedly exchanges
5.784 + * the displaced element into the location it should go until a displaced
5.785 + * element is swapped into the first element. If necessary, the process
5.786 + * is repeated on the second and successive elements, until the rotation
5.787 + * is complete. If the specified list is large and doesn't implement the
5.788 + * <tt>RandomAccess</tt> interface, this implementation breaks the
5.789 + * list into two sublist views around index <tt>-distance mod size</tt>.
5.790 + * Then the {@link #reverse(List)} method is invoked on each sublist view,
5.791 + * and finally it is invoked on the entire list. For a more complete
5.792 + * description of both algorithms, see Section 2.3 of Jon Bentley's
5.793 + * <i>Programming Pearls</i> (Addison-Wesley, 1986).
5.794 + *
5.795 + * @param list the list to be rotated.
5.796 + * @param distance the distance to rotate the list. There are no
5.797 + * constraints on this value; it may be zero, negative, or
5.798 + * greater than <tt>list.size()</tt>.
5.799 + * @throws UnsupportedOperationException if the specified list or
5.800 + * its list-iterator does not support the <tt>set</tt> operation.
5.801 + * @since 1.4
5.802 + */
5.803 + public static void rotate(List<?> list, int distance) {
5.804 + if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)
5.805 + rotate1(list, distance);
5.806 + else
5.807 + rotate2(list, distance);
5.808 + }
5.809 +
5.810 + private static <T> void rotate1(List<T> list, int distance) {
5.811 + int size = list.size();
5.812 + if (size == 0)
5.813 + return;
5.814 + distance = distance % size;
5.815 + if (distance < 0)
5.816 + distance += size;
5.817 + if (distance == 0)
5.818 + return;
5.819 +
5.820 + for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {
5.821 + T displaced = list.get(cycleStart);
5.822 + int i = cycleStart;
5.823 + do {
5.824 + i += distance;
5.825 + if (i >= size)
5.826 + i -= size;
5.827 + displaced = list.set(i, displaced);
5.828 + nMoved ++;
5.829 + } while (i != cycleStart);
5.830 + }
5.831 + }
5.832 +
5.833 + private static void rotate2(List<?> list, int distance) {
5.834 + int size = list.size();
5.835 + if (size == 0)
5.836 + return;
5.837 + int mid = -distance % size;
5.838 + if (mid < 0)
5.839 + mid += size;
5.840 + if (mid == 0)
5.841 + return;
5.842 +
5.843 + reverse(list.subList(0, mid));
5.844 + reverse(list.subList(mid, size));
5.845 + reverse(list);
5.846 + }
5.847 +
5.848 + /**
5.849 + * Replaces all occurrences of one specified value in a list with another.
5.850 + * More formally, replaces with <tt>newVal</tt> each element <tt>e</tt>
5.851 + * in <tt>list</tt> such that
5.852 + * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>.
5.853 + * (This method has no effect on the size of the list.)
5.854 + *
5.855 + * @param list the list in which replacement is to occur.
5.856 + * @param oldVal the old value to be replaced.
5.857 + * @param newVal the new value with which <tt>oldVal</tt> is to be
5.858 + * replaced.
5.859 + * @return <tt>true</tt> if <tt>list</tt> contained one or more elements
5.860 + * <tt>e</tt> such that
5.861 + * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>.
5.862 + * @throws UnsupportedOperationException if the specified list or
5.863 + * its list-iterator does not support the <tt>set</tt> operation.
5.864 + * @since 1.4
5.865 + */
5.866 + public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {
5.867 + boolean result = false;
5.868 + int size = list.size();
5.869 + if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {
5.870 + if (oldVal==null) {
5.871 + for (int i=0; i<size; i++) {
5.872 + if (list.get(i)==null) {
5.873 + list.set(i, newVal);
5.874 + result = true;
5.875 + }
5.876 + }
5.877 + } else {
5.878 + for (int i=0; i<size; i++) {
5.879 + if (oldVal.equals(list.get(i))) {
5.880 + list.set(i, newVal);
5.881 + result = true;
5.882 + }
5.883 + }
5.884 + }
5.885 + } else {
5.886 + ListIterator<T> itr=list.listIterator();
5.887 + if (oldVal==null) {
5.888 + for (int i=0; i<size; i++) {
5.889 + if (itr.next()==null) {
5.890 + itr.set(newVal);
5.891 + result = true;
5.892 + }
5.893 + }
5.894 + } else {
5.895 + for (int i=0; i<size; i++) {
5.896 + if (oldVal.equals(itr.next())) {
5.897 + itr.set(newVal);
5.898 + result = true;
5.899 + }
5.900 + }
5.901 + }
5.902 + }
5.903 + return result;
5.904 + }
5.905 +
5.906 + /**
5.907 + * Returns the starting position of the first occurrence of the specified
5.908 + * target list within the specified source list, or -1 if there is no
5.909 + * such occurrence. More formally, returns the lowest index <tt>i</tt>
5.910 + * such that <tt>source.subList(i, i+target.size()).equals(target)</tt>,
5.911 + * or -1 if there is no such index. (Returns -1 if
5.912 + * <tt>target.size() > source.size()</tt>.)
5.913 + *
5.914 + * <p>This implementation uses the "brute force" technique of scanning
5.915 + * over the source list, looking for a match with the target at each
5.916 + * location in turn.
5.917 + *
5.918 + * @param source the list in which to search for the first occurrence
5.919 + * of <tt>target</tt>.
5.920 + * @param target the list to search for as a subList of <tt>source</tt>.
5.921 + * @return the starting position of the first occurrence of the specified
5.922 + * target list within the specified source list, or -1 if there
5.923 + * is no such occurrence.
5.924 + * @since 1.4
5.925 + */
5.926 + public static int indexOfSubList(List<?> source, List<?> target) {
5.927 + int sourceSize = source.size();
5.928 + int targetSize = target.size();
5.929 + int maxCandidate = sourceSize - targetSize;
5.930 +
5.931 + if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
5.932 + (source instanceof RandomAccess&&target instanceof RandomAccess)) {
5.933 + nextCand:
5.934 + for (int candidate = 0; candidate <= maxCandidate; candidate++) {
5.935 + for (int i=0, j=candidate; i<targetSize; i++, j++)
5.936 + if (!eq(target.get(i), source.get(j)))
5.937 + continue nextCand; // Element mismatch, try next cand
5.938 + return candidate; // All elements of candidate matched target
5.939 + }
5.940 + } else { // Iterator version of above algorithm
5.941 + ListIterator<?> si = source.listIterator();
5.942 + nextCand:
5.943 + for (int candidate = 0; candidate <= maxCandidate; candidate++) {
5.944 + ListIterator<?> ti = target.listIterator();
5.945 + for (int i=0; i<targetSize; i++) {
5.946 + if (!eq(ti.next(), si.next())) {
5.947 + // Back up source iterator to next candidate
5.948 + for (int j=0; j<i; j++)
5.949 + si.previous();
5.950 + continue nextCand;
5.951 + }
5.952 + }
5.953 + return candidate;
5.954 + }
5.955 + }
5.956 + return -1; // No candidate matched the target
5.957 + }
5.958 +
5.959 + /**
5.960 + * Returns the starting position of the last occurrence of the specified
5.961 + * target list within the specified source list, or -1 if there is no such
5.962 + * occurrence. More formally, returns the highest index <tt>i</tt>
5.963 + * such that <tt>source.subList(i, i+target.size()).equals(target)</tt>,
5.964 + * or -1 if there is no such index. (Returns -1 if
5.965 + * <tt>target.size() > source.size()</tt>.)
5.966 + *
5.967 + * <p>This implementation uses the "brute force" technique of iterating
5.968 + * over the source list, looking for a match with the target at each
5.969 + * location in turn.
5.970 + *
5.971 + * @param source the list in which to search for the last occurrence
5.972 + * of <tt>target</tt>.
5.973 + * @param target the list to search for as a subList of <tt>source</tt>.
5.974 + * @return the starting position of the last occurrence of the specified
5.975 + * target list within the specified source list, or -1 if there
5.976 + * is no such occurrence.
5.977 + * @since 1.4
5.978 + */
5.979 + public static int lastIndexOfSubList(List<?> source, List<?> target) {
5.980 + int sourceSize = source.size();
5.981 + int targetSize = target.size();
5.982 + int maxCandidate = sourceSize - targetSize;
5.983 +
5.984 + if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
5.985 + source instanceof RandomAccess) { // Index access version
5.986 + nextCand:
5.987 + for (int candidate = maxCandidate; candidate >= 0; candidate--) {
5.988 + for (int i=0, j=candidate; i<targetSize; i++, j++)
5.989 + if (!eq(target.get(i), source.get(j)))
5.990 + continue nextCand; // Element mismatch, try next cand
5.991 + return candidate; // All elements of candidate matched target
5.992 + }
5.993 + } else { // Iterator version of above algorithm
5.994 + if (maxCandidate < 0)
5.995 + return -1;
5.996 + ListIterator<?> si = source.listIterator(maxCandidate);
5.997 + nextCand:
5.998 + for (int candidate = maxCandidate; candidate >= 0; candidate--) {
5.999 + ListIterator<?> ti = target.listIterator();
5.1000 + for (int i=0; i<targetSize; i++) {
5.1001 + if (!eq(ti.next(), si.next())) {
5.1002 + if (candidate != 0) {
5.1003 + // Back up source iterator to next candidate
5.1004 + for (int j=0; j<=i+1; j++)
5.1005 + si.previous();
5.1006 + }
5.1007 + continue nextCand;
5.1008 + }
5.1009 + }
5.1010 + return candidate;
5.1011 + }
5.1012 + }
5.1013 + return -1; // No candidate matched the target
5.1014 + }
5.1015 +
5.1016 +
5.1017 + // Unmodifiable Wrappers
5.1018 +
5.1019 + /**
5.1020 + * Returns an unmodifiable view of the specified collection. This method
5.1021 + * allows modules to provide users with "read-only" access to internal
5.1022 + * collections. Query operations on the returned collection "read through"
5.1023 + * to the specified collection, and attempts to modify the returned
5.1024 + * collection, whether direct or via its iterator, result in an
5.1025 + * <tt>UnsupportedOperationException</tt>.<p>
5.1026 + *
5.1027 + * The returned collection does <i>not</i> pass the hashCode and equals
5.1028 + * operations through to the backing collection, but relies on
5.1029 + * <tt>Object</tt>'s <tt>equals</tt> and <tt>hashCode</tt> methods. This
5.1030 + * is necessary to preserve the contracts of these operations in the case
5.1031 + * that the backing collection is a set or a list.<p>
5.1032 + *
5.1033 + * The returned collection will be serializable if the specified collection
5.1034 + * is serializable.
5.1035 + *
5.1036 + * @param c the collection for which an unmodifiable view is to be
5.1037 + * returned.
5.1038 + * @return an unmodifiable view of the specified collection.
5.1039 + */
5.1040 + public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
5.1041 + return new UnmodifiableCollection<>(c);
5.1042 + }
5.1043 +
5.1044 + /**
5.1045 + * @serial include
5.1046 + */
5.1047 + static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
5.1048 + private static final long serialVersionUID = 1820017752578914078L;
5.1049 +
5.1050 + final Collection<? extends E> c;
5.1051 +
5.1052 + UnmodifiableCollection(Collection<? extends E> c) {
5.1053 + if (c==null)
5.1054 + throw new NullPointerException();
5.1055 + this.c = c;
5.1056 + }
5.1057 +
5.1058 + public int size() {return c.size();}
5.1059 + public boolean isEmpty() {return c.isEmpty();}
5.1060 + public boolean contains(Object o) {return c.contains(o);}
5.1061 + public Object[] toArray() {return c.toArray();}
5.1062 + public <T> T[] toArray(T[] a) {return c.toArray(a);}
5.1063 + public String toString() {return c.toString();}
5.1064 +
5.1065 + public Iterator<E> iterator() {
5.1066 + return new Iterator<E>() {
5.1067 + private final Iterator<? extends E> i = c.iterator();
5.1068 +
5.1069 + public boolean hasNext() {return i.hasNext();}
5.1070 + public E next() {return i.next();}
5.1071 + public void remove() {
5.1072 + throw new UnsupportedOperationException();
5.1073 + }
5.1074 + };
5.1075 + }
5.1076 +
5.1077 + public boolean add(E e) {
5.1078 + throw new UnsupportedOperationException();
5.1079 + }
5.1080 + public boolean remove(Object o) {
5.1081 + throw new UnsupportedOperationException();
5.1082 + }
5.1083 +
5.1084 + public boolean containsAll(Collection<?> coll) {
5.1085 + return c.containsAll(coll);
5.1086 + }
5.1087 + public boolean addAll(Collection<? extends E> coll) {
5.1088 + throw new UnsupportedOperationException();
5.1089 + }
5.1090 + public boolean removeAll(Collection<?> coll) {
5.1091 + throw new UnsupportedOperationException();
5.1092 + }
5.1093 + public boolean retainAll(Collection<?> coll) {
5.1094 + throw new UnsupportedOperationException();
5.1095 + }
5.1096 + public void clear() {
5.1097 + throw new UnsupportedOperationException();
5.1098 + }
5.1099 + }
5.1100 +
5.1101 + /**
5.1102 + * Returns an unmodifiable view of the specified set. This method allows
5.1103 + * modules to provide users with "read-only" access to internal sets.
5.1104 + * Query operations on the returned set "read through" to the specified
5.1105 + * set, and attempts to modify the returned set, whether direct or via its
5.1106 + * iterator, result in an <tt>UnsupportedOperationException</tt>.<p>
5.1107 + *
5.1108 + * The returned set will be serializable if the specified set
5.1109 + * is serializable.
5.1110 + *
5.1111 + * @param s the set for which an unmodifiable view is to be returned.
5.1112 + * @return an unmodifiable view of the specified set.
5.1113 + */
5.1114 + public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
5.1115 + return new UnmodifiableSet<>(s);
5.1116 + }
5.1117 +
5.1118 + /**
5.1119 + * @serial include
5.1120 + */
5.1121 + static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
5.1122 + implements Set<E>, Serializable {
5.1123 + private static final long serialVersionUID = -9215047833775013803L;
5.1124 +
5.1125 + UnmodifiableSet(Set<? extends E> s) {super(s);}
5.1126 + public boolean equals(Object o) {return o == this || c.equals(o);}
5.1127 + public int hashCode() {return c.hashCode();}
5.1128 + }
5.1129 +
5.1130 + /**
5.1131 + * Returns an unmodifiable view of the specified sorted set. This method
5.1132 + * allows modules to provide users with "read-only" access to internal
5.1133 + * sorted sets. Query operations on the returned sorted set "read
5.1134 + * through" to the specified sorted set. Attempts to modify the returned
5.1135 + * sorted set, whether direct, via its iterator, or via its
5.1136 + * <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in
5.1137 + * an <tt>UnsupportedOperationException</tt>.<p>
5.1138 + *
5.1139 + * The returned sorted set will be serializable if the specified sorted set
5.1140 + * is serializable.
5.1141 + *
5.1142 + * @param s the sorted set for which an unmodifiable view is to be
5.1143 + * returned.
5.1144 + * @return an unmodifiable view of the specified sorted set.
5.1145 + */
5.1146 + public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
5.1147 + return new UnmodifiableSortedSet<>(s);
5.1148 + }
5.1149 +
5.1150 + /**
5.1151 + * @serial include
5.1152 + */
5.1153 + static class UnmodifiableSortedSet<E>
5.1154 + extends UnmodifiableSet<E>
5.1155 + implements SortedSet<E>, Serializable {
5.1156 + private static final long serialVersionUID = -4929149591599911165L;
5.1157 + private final SortedSet<E> ss;
5.1158 +
5.1159 + UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
5.1160 +
5.1161 + public Comparator<? super E> comparator() {return ss.comparator();}
5.1162 +
5.1163 + public SortedSet<E> subSet(E fromElement, E toElement) {
5.1164 + return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
5.1165 + }
5.1166 + public SortedSet<E> headSet(E toElement) {
5.1167 + return new UnmodifiableSortedSet<>(ss.headSet(toElement));
5.1168 + }
5.1169 + public SortedSet<E> tailSet(E fromElement) {
5.1170 + return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
5.1171 + }
5.1172 +
5.1173 + public E first() {return ss.first();}
5.1174 + public E last() {return ss.last();}
5.1175 + }
5.1176 +
5.1177 + /**
5.1178 + * Returns an unmodifiable view of the specified list. This method allows
5.1179 + * modules to provide users with "read-only" access to internal
5.1180 + * lists. Query operations on the returned list "read through" to the
5.1181 + * specified list, and attempts to modify the returned list, whether
5.1182 + * direct or via its iterator, result in an
5.1183 + * <tt>UnsupportedOperationException</tt>.<p>
5.1184 + *
5.1185 + * The returned list will be serializable if the specified list
5.1186 + * is serializable. Similarly, the returned list will implement
5.1187 + * {@link RandomAccess} if the specified list does.
5.1188 + *
5.1189 + * @param list the list for which an unmodifiable view is to be returned.
5.1190 + * @return an unmodifiable view of the specified list.
5.1191 + */
5.1192 + public static <T> List<T> unmodifiableList(List<? extends T> list) {
5.1193 + return (list instanceof RandomAccess ?
5.1194 + new UnmodifiableRandomAccessList<>(list) :
5.1195 + new UnmodifiableList<>(list));
5.1196 + }
5.1197 +
5.1198 + /**
5.1199 + * @serial include
5.1200 + */
5.1201 + static class UnmodifiableList<E> extends UnmodifiableCollection<E>
5.1202 + implements List<E> {
5.1203 + private static final long serialVersionUID = -283967356065247728L;
5.1204 + final List<? extends E> list;
5.1205 +
5.1206 + UnmodifiableList(List<? extends E> list) {
5.1207 + super(list);
5.1208 + this.list = list;
5.1209 + }
5.1210 +
5.1211 + public boolean equals(Object o) {return o == this || list.equals(o);}
5.1212 + public int hashCode() {return list.hashCode();}
5.1213 +
5.1214 + public E get(int index) {return list.get(index);}
5.1215 + public E set(int index, E element) {
5.1216 + throw new UnsupportedOperationException();
5.1217 + }
5.1218 + public void add(int index, E element) {
5.1219 + throw new UnsupportedOperationException();
5.1220 + }
5.1221 + public E remove(int index) {
5.1222 + throw new UnsupportedOperationException();
5.1223 + }
5.1224 + public int indexOf(Object o) {return list.indexOf(o);}
5.1225 + public int lastIndexOf(Object o) {return list.lastIndexOf(o);}
5.1226 + public boolean addAll(int index, Collection<? extends E> c) {
5.1227 + throw new UnsupportedOperationException();
5.1228 + }
5.1229 + public ListIterator<E> listIterator() {return listIterator(0);}
5.1230 +
5.1231 + public ListIterator<E> listIterator(final int index) {
5.1232 + return new ListIterator<E>() {
5.1233 + private final ListIterator<? extends E> i
5.1234 + = list.listIterator(index);
5.1235 +
5.1236 + public boolean hasNext() {return i.hasNext();}
5.1237 + public E next() {return i.next();}
5.1238 + public boolean hasPrevious() {return i.hasPrevious();}
5.1239 + public E previous() {return i.previous();}
5.1240 + public int nextIndex() {return i.nextIndex();}
5.1241 + public int previousIndex() {return i.previousIndex();}
5.1242 +
5.1243 + public void remove() {
5.1244 + throw new UnsupportedOperationException();
5.1245 + }
5.1246 + public void set(E e) {
5.1247 + throw new UnsupportedOperationException();
5.1248 + }
5.1249 + public void add(E e) {
5.1250 + throw new UnsupportedOperationException();
5.1251 + }
5.1252 + };
5.1253 + }
5.1254 +
5.1255 + public List<E> subList(int fromIndex, int toIndex) {
5.1256 + return new UnmodifiableList<>(list.subList(fromIndex, toIndex));
5.1257 + }
5.1258 +
5.1259 + /**
5.1260 + * UnmodifiableRandomAccessList instances are serialized as
5.1261 + * UnmodifiableList instances to allow them to be deserialized
5.1262 + * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
5.1263 + * This method inverts the transformation. As a beneficial
5.1264 + * side-effect, it also grafts the RandomAccess marker onto
5.1265 + * UnmodifiableList instances that were serialized in pre-1.4 JREs.
5.1266 + *
5.1267 + * Note: Unfortunately, UnmodifiableRandomAccessList instances
5.1268 + * serialized in 1.4.1 and deserialized in 1.4 will become
5.1269 + * UnmodifiableList instances, as this method was missing in 1.4.
5.1270 + */
5.1271 + private Object readResolve() {
5.1272 + return (list instanceof RandomAccess
5.1273 + ? new UnmodifiableRandomAccessList<>(list)
5.1274 + : this);
5.1275 + }
5.1276 + }
5.1277 +
5.1278 + /**
5.1279 + * @serial include
5.1280 + */
5.1281 + static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>
5.1282 + implements RandomAccess
5.1283 + {
5.1284 + UnmodifiableRandomAccessList(List<? extends E> list) {
5.1285 + super(list);
5.1286 + }
5.1287 +
5.1288 + public List<E> subList(int fromIndex, int toIndex) {
5.1289 + return new UnmodifiableRandomAccessList<>(
5.1290 + list.subList(fromIndex, toIndex));
5.1291 + }
5.1292 +
5.1293 + private static final long serialVersionUID = -2542308836966382001L;
5.1294 +
5.1295 + /**
5.1296 + * Allows instances to be deserialized in pre-1.4 JREs (which do
5.1297 + * not have UnmodifiableRandomAccessList). UnmodifiableList has
5.1298 + * a readResolve method that inverts this transformation upon
5.1299 + * deserialization.
5.1300 + */
5.1301 + private Object writeReplace() {
5.1302 + return new UnmodifiableList<>(list);
5.1303 + }
5.1304 + }
5.1305 +
5.1306 + /**
5.1307 + * Returns an unmodifiable view of the specified map. This method
5.1308 + * allows modules to provide users with "read-only" access to internal
5.1309 + * maps. Query operations on the returned map "read through"
5.1310 + * to the specified map, and attempts to modify the returned
5.1311 + * map, whether direct or via its collection views, result in an
5.1312 + * <tt>UnsupportedOperationException</tt>.<p>
5.1313 + *
5.1314 + * The returned map will be serializable if the specified map
5.1315 + * is serializable.
5.1316 + *
5.1317 + * @param m the map for which an unmodifiable view is to be returned.
5.1318 + * @return an unmodifiable view of the specified map.
5.1319 + */
5.1320 + public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
5.1321 + return new UnmodifiableMap<>(m);
5.1322 + }
5.1323 +
5.1324 + /**
5.1325 + * @serial include
5.1326 + */
5.1327 + private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
5.1328 + private static final long serialVersionUID = -1034234728574286014L;
5.1329 +
5.1330 + private final Map<? extends K, ? extends V> m;
5.1331 +
5.1332 + UnmodifiableMap(Map<? extends K, ? extends V> m) {
5.1333 + if (m==null)
5.1334 + throw new NullPointerException();
5.1335 + this.m = m;
5.1336 + }
5.1337 +
5.1338 + public int size() {return m.size();}
5.1339 + public boolean isEmpty() {return m.isEmpty();}
5.1340 + public boolean containsKey(Object key) {return m.containsKey(key);}
5.1341 + public boolean containsValue(Object val) {return m.containsValue(val);}
5.1342 + public V get(Object key) {return m.get(key);}
5.1343 +
5.1344 + public V put(K key, V value) {
5.1345 + throw new UnsupportedOperationException();
5.1346 + }
5.1347 + public V remove(Object key) {
5.1348 + throw new UnsupportedOperationException();
5.1349 + }
5.1350 + public void putAll(Map<? extends K, ? extends V> m) {
5.1351 + throw new UnsupportedOperationException();
5.1352 + }
5.1353 + public void clear() {
5.1354 + throw new UnsupportedOperationException();
5.1355 + }
5.1356 +
5.1357 + private transient Set<K> keySet = null;
5.1358 + private transient Set<Map.Entry<K,V>> entrySet = null;
5.1359 + private transient Collection<V> values = null;
5.1360 +
5.1361 + public Set<K> keySet() {
5.1362 + if (keySet==null)
5.1363 + keySet = unmodifiableSet(m.keySet());
5.1364 + return keySet;
5.1365 + }
5.1366 +
5.1367 + public Set<Map.Entry<K,V>> entrySet() {
5.1368 + if (entrySet==null)
5.1369 + entrySet = new UnmodifiableEntrySet<>(m.entrySet());
5.1370 + return entrySet;
5.1371 + }
5.1372 +
5.1373 + public Collection<V> values() {
5.1374 + if (values==null)
5.1375 + values = unmodifiableCollection(m.values());
5.1376 + return values;
5.1377 + }
5.1378 +
5.1379 + public boolean equals(Object o) {return o == this || m.equals(o);}
5.1380 + public int hashCode() {return m.hashCode();}
5.1381 + public String toString() {return m.toString();}
5.1382 +
5.1383 + /**
5.1384 + * We need this class in addition to UnmodifiableSet as
5.1385 + * Map.Entries themselves permit modification of the backing Map
5.1386 + * via their setValue operation. This class is subtle: there are
5.1387 + * many possible attacks that must be thwarted.
5.1388 + *
5.1389 + * @serial include
5.1390 + */
5.1391 + static class UnmodifiableEntrySet<K,V>
5.1392 + extends UnmodifiableSet<Map.Entry<K,V>> {
5.1393 + private static final long serialVersionUID = 7854390611657943733L;
5.1394 +
5.1395 + UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
5.1396 + super((Set)s);
5.1397 + }
5.1398 + public Iterator<Map.Entry<K,V>> iterator() {
5.1399 + return new Iterator<Map.Entry<K,V>>() {
5.1400 + private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
5.1401 +
5.1402 + public boolean hasNext() {
5.1403 + return i.hasNext();
5.1404 + }
5.1405 + public Map.Entry<K,V> next() {
5.1406 + return new UnmodifiableEntry<>(i.next());
5.1407 + }
5.1408 + public void remove() {
5.1409 + throw new UnsupportedOperationException();
5.1410 + }
5.1411 + };
5.1412 + }
5.1413 +
5.1414 + public Object[] toArray() {
5.1415 + Object[] a = c.toArray();
5.1416 + for (int i=0; i<a.length; i++)
5.1417 + a[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)a[i]);
5.1418 + return a;
5.1419 + }
5.1420 +
5.1421 + public <T> T[] toArray(T[] a) {
5.1422 + // We don't pass a to c.toArray, to avoid window of
5.1423 + // vulnerability wherein an unscrupulous multithreaded client
5.1424 + // could get his hands on raw (unwrapped) Entries from c.
5.1425 + Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
5.1426 +
5.1427 + for (int i=0; i<arr.length; i++)
5.1428 + arr[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)arr[i]);
5.1429 +
5.1430 + if (arr.length > a.length)
5.1431 + return (T[])arr;
5.1432 +
5.1433 + System.arraycopy(arr, 0, a, 0, arr.length);
5.1434 + if (a.length > arr.length)
5.1435 + a[arr.length] = null;
5.1436 + return a;
5.1437 + }
5.1438 +
5.1439 + /**
5.1440 + * This method is overridden to protect the backing set against
5.1441 + * an object with a nefarious equals function that senses
5.1442 + * that the equality-candidate is Map.Entry and calls its
5.1443 + * setValue method.
5.1444 + */
5.1445 + public boolean contains(Object o) {
5.1446 + if (!(o instanceof Map.Entry))
5.1447 + return false;
5.1448 + return c.contains(
5.1449 + new UnmodifiableEntry<>((Map.Entry<?,?>) o));
5.1450 + }
5.1451 +
5.1452 + /**
5.1453 + * The next two methods are overridden to protect against
5.1454 + * an unscrupulous List whose contains(Object o) method senses
5.1455 + * when o is a Map.Entry, and calls o.setValue.
5.1456 + */
5.1457 + public boolean containsAll(Collection<?> coll) {
5.1458 + for (Object e : coll) {
5.1459 + if (!contains(e)) // Invokes safe contains() above
5.1460 + return false;
5.1461 + }
5.1462 + return true;
5.1463 + }
5.1464 + public boolean equals(Object o) {
5.1465 + if (o == this)
5.1466 + return true;
5.1467 +
5.1468 + if (!(o instanceof Set))
5.1469 + return false;
5.1470 + Set s = (Set) o;
5.1471 + if (s.size() != c.size())
5.1472 + return false;
5.1473 + return containsAll(s); // Invokes safe containsAll() above
5.1474 + }
5.1475 +
5.1476 + /**
5.1477 + * This "wrapper class" serves two purposes: it prevents
5.1478 + * the client from modifying the backing Map, by short-circuiting
5.1479 + * the setValue method, and it protects the backing Map against
5.1480 + * an ill-behaved Map.Entry that attempts to modify another
5.1481 + * Map Entry when asked to perform an equality check.
5.1482 + */
5.1483 + private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {
5.1484 + private Map.Entry<? extends K, ? extends V> e;
5.1485 +
5.1486 + UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e) {this.e = e;}
5.1487 +
5.1488 + public K getKey() {return e.getKey();}
5.1489 + public V getValue() {return e.getValue();}
5.1490 + public V setValue(V value) {
5.1491 + throw new UnsupportedOperationException();
5.1492 + }
5.1493 + public int hashCode() {return e.hashCode();}
5.1494 + public boolean equals(Object o) {
5.1495 + if (!(o instanceof Map.Entry))
5.1496 + return false;
5.1497 + Map.Entry t = (Map.Entry)o;
5.1498 + return eq(e.getKey(), t.getKey()) &&
5.1499 + eq(e.getValue(), t.getValue());
5.1500 + }
5.1501 + public String toString() {return e.toString();}
5.1502 + }
5.1503 + }
5.1504 + }
5.1505 +
5.1506 + /**
5.1507 + * Returns an unmodifiable view of the specified sorted map. This method
5.1508 + * allows modules to provide users with "read-only" access to internal
5.1509 + * sorted maps. Query operations on the returned sorted map "read through"
5.1510 + * to the specified sorted map. Attempts to modify the returned
5.1511 + * sorted map, whether direct, via its collection views, or via its
5.1512 + * <tt>subMap</tt>, <tt>headMap</tt>, or <tt>tailMap</tt> views, result in
5.1513 + * an <tt>UnsupportedOperationException</tt>.<p>
5.1514 + *
5.1515 + * The returned sorted map will be serializable if the specified sorted map
5.1516 + * is serializable.
5.1517 + *
5.1518 + * @param m the sorted map for which an unmodifiable view is to be
5.1519 + * returned.
5.1520 + * @return an unmodifiable view of the specified sorted map.
5.1521 + */
5.1522 + public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
5.1523 + return new UnmodifiableSortedMap<>(m);
5.1524 + }
5.1525 +
5.1526 + /**
5.1527 + * @serial include
5.1528 + */
5.1529 + static class UnmodifiableSortedMap<K,V>
5.1530 + extends UnmodifiableMap<K,V>
5.1531 + implements SortedMap<K,V>, Serializable {
5.1532 + private static final long serialVersionUID = -8806743815996713206L;
5.1533 +
5.1534 + private final SortedMap<K, ? extends V> sm;
5.1535 +
5.1536 + UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}
5.1537 +
5.1538 + public Comparator<? super K> comparator() {return sm.comparator();}
5.1539 +
5.1540 + public SortedMap<K,V> subMap(K fromKey, K toKey) {
5.1541 + return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey));
5.1542 + }
5.1543 + public SortedMap<K,V> headMap(K toKey) {
5.1544 + return new UnmodifiableSortedMap<>(sm.headMap(toKey));
5.1545 + }
5.1546 + public SortedMap<K,V> tailMap(K fromKey) {
5.1547 + return new UnmodifiableSortedMap<>(sm.tailMap(fromKey));
5.1548 + }
5.1549 +
5.1550 + public K firstKey() {return sm.firstKey();}
5.1551 + public K lastKey() {return sm.lastKey();}
5.1552 + }
5.1553 +
5.1554 +
5.1555 + // Synch Wrappers
5.1556 +
5.1557 + /**
5.1558 + * Returns a synchronized (thread-safe) collection backed by the specified
5.1559 + * collection. In order to guarantee serial access, it is critical that
5.1560 + * <strong>all</strong> access to the backing collection is accomplished
5.1561 + * through the returned collection.<p>
5.1562 + *
5.1563 + * It is imperative that the user manually synchronize on the returned
5.1564 + * collection when iterating over it:
5.1565 + * <pre>
5.1566 + * Collection c = Collections.synchronizedCollection(myCollection);
5.1567 + * ...
5.1568 + * synchronized (c) {
5.1569 + * Iterator i = c.iterator(); // Must be in the synchronized block
5.1570 + * while (i.hasNext())
5.1571 + * foo(i.next());
5.1572 + * }
5.1573 + * </pre>
5.1574 + * Failure to follow this advice may result in non-deterministic behavior.
5.1575 + *
5.1576 + * <p>The returned collection does <i>not</i> pass the <tt>hashCode</tt>
5.1577 + * and <tt>equals</tt> operations through to the backing collection, but
5.1578 + * relies on <tt>Object</tt>'s equals and hashCode methods. This is
5.1579 + * necessary to preserve the contracts of these operations in the case
5.1580 + * that the backing collection is a set or a list.<p>
5.1581 + *
5.1582 + * The returned collection will be serializable if the specified collection
5.1583 + * is serializable.
5.1584 + *
5.1585 + * @param c the collection to be "wrapped" in a synchronized collection.
5.1586 + * @return a synchronized view of the specified collection.
5.1587 + */
5.1588 + public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
5.1589 + return new SynchronizedCollection<>(c);
5.1590 + }
5.1591 +
5.1592 + static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
5.1593 + return new SynchronizedCollection<>(c, mutex);
5.1594 + }
5.1595 +
5.1596 + /**
5.1597 + * @serial include
5.1598 + */
5.1599 + static class SynchronizedCollection<E> implements Collection<E>, Serializable {
5.1600 + private static final long serialVersionUID = 3053995032091335093L;
5.1601 +
5.1602 + final Collection<E> c; // Backing Collection
5.1603 + final Object mutex; // Object on which to synchronize
5.1604 +
5.1605 + SynchronizedCollection(Collection<E> c) {
5.1606 + if (c==null)
5.1607 + throw new NullPointerException();
5.1608 + this.c = c;
5.1609 + mutex = this;
5.1610 + }
5.1611 + SynchronizedCollection(Collection<E> c, Object mutex) {
5.1612 + this.c = c;
5.1613 + this.mutex = mutex;
5.1614 + }
5.1615 +
5.1616 + public int size() {
5.1617 + synchronized (mutex) {return c.size();}
5.1618 + }
5.1619 + public boolean isEmpty() {
5.1620 + synchronized (mutex) {return c.isEmpty();}
5.1621 + }
5.1622 + public boolean contains(Object o) {
5.1623 + synchronized (mutex) {return c.contains(o);}
5.1624 + }
5.1625 + public Object[] toArray() {
5.1626 + synchronized (mutex) {return c.toArray();}
5.1627 + }
5.1628 + public <T> T[] toArray(T[] a) {
5.1629 + synchronized (mutex) {return c.toArray(a);}
5.1630 + }
5.1631 +
5.1632 + public Iterator<E> iterator() {
5.1633 + return c.iterator(); // Must be manually synched by user!
5.1634 + }
5.1635 +
5.1636 + public boolean add(E e) {
5.1637 + synchronized (mutex) {return c.add(e);}
5.1638 + }
5.1639 + public boolean remove(Object o) {
5.1640 + synchronized (mutex) {return c.remove(o);}
5.1641 + }
5.1642 +
5.1643 + public boolean containsAll(Collection<?> coll) {
5.1644 + synchronized (mutex) {return c.containsAll(coll);}
5.1645 + }
5.1646 + public boolean addAll(Collection<? extends E> coll) {
5.1647 + synchronized (mutex) {return c.addAll(coll);}
5.1648 + }
5.1649 + public boolean removeAll(Collection<?> coll) {
5.1650 + synchronized (mutex) {return c.removeAll(coll);}
5.1651 + }
5.1652 + public boolean retainAll(Collection<?> coll) {
5.1653 + synchronized (mutex) {return c.retainAll(coll);}
5.1654 + }
5.1655 + public void clear() {
5.1656 + synchronized (mutex) {c.clear();}
5.1657 + }
5.1658 + public String toString() {
5.1659 + synchronized (mutex) {return c.toString();}
5.1660 + }
5.1661 + }
5.1662 +
5.1663 + /**
5.1664 + * Returns a synchronized (thread-safe) set backed by the specified
5.1665 + * set. In order to guarantee serial access, it is critical that
5.1666 + * <strong>all</strong> access to the backing set is accomplished
5.1667 + * through the returned set.<p>
5.1668 + *
5.1669 + * It is imperative that the user manually synchronize on the returned
5.1670 + * set when iterating over it:
5.1671 + * <pre>
5.1672 + * Set s = Collections.synchronizedSet(new HashSet());
5.1673 + * ...
5.1674 + * synchronized (s) {
5.1675 + * Iterator i = s.iterator(); // Must be in the synchronized block
5.1676 + * while (i.hasNext())
5.1677 + * foo(i.next());
5.1678 + * }
5.1679 + * </pre>
5.1680 + * Failure to follow this advice may result in non-deterministic behavior.
5.1681 + *
5.1682 + * <p>The returned set will be serializable if the specified set is
5.1683 + * serializable.
5.1684 + *
5.1685 + * @param s the set to be "wrapped" in a synchronized set.
5.1686 + * @return a synchronized view of the specified set.
5.1687 + */
5.1688 + public static <T> Set<T> synchronizedSet(Set<T> s) {
5.1689 + return new SynchronizedSet<>(s);
5.1690 + }
5.1691 +
5.1692 + static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
5.1693 + return new SynchronizedSet<>(s, mutex);
5.1694 + }
5.1695 +
5.1696 + /**
5.1697 + * @serial include
5.1698 + */
5.1699 + static class SynchronizedSet<E>
5.1700 + extends SynchronizedCollection<E>
5.1701 + implements Set<E> {
5.1702 + private static final long serialVersionUID = 487447009682186044L;
5.1703 +
5.1704 + SynchronizedSet(Set<E> s) {
5.1705 + super(s);
5.1706 + }
5.1707 + SynchronizedSet(Set<E> s, Object mutex) {
5.1708 + super(s, mutex);
5.1709 + }
5.1710 +
5.1711 + public boolean equals(Object o) {
5.1712 + synchronized (mutex) {return c.equals(o);}
5.1713 + }
5.1714 + public int hashCode() {
5.1715 + synchronized (mutex) {return c.hashCode();}
5.1716 + }
5.1717 + }
5.1718 +
5.1719 + /**
5.1720 + * Returns a synchronized (thread-safe) sorted set backed by the specified
5.1721 + * sorted set. In order to guarantee serial access, it is critical that
5.1722 + * <strong>all</strong> access to the backing sorted set is accomplished
5.1723 + * through the returned sorted set (or its views).<p>
5.1724 + *
5.1725 + * It is imperative that the user manually synchronize on the returned
5.1726 + * sorted set when iterating over it or any of its <tt>subSet</tt>,
5.1727 + * <tt>headSet</tt>, or <tt>tailSet</tt> views.
5.1728 + * <pre>
5.1729 + * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
5.1730 + * ...
5.1731 + * synchronized (s) {
5.1732 + * Iterator i = s.iterator(); // Must be in the synchronized block
5.1733 + * while (i.hasNext())
5.1734 + * foo(i.next());
5.1735 + * }
5.1736 + * </pre>
5.1737 + * or:
5.1738 + * <pre>
5.1739 + * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
5.1740 + * SortedSet s2 = s.headSet(foo);
5.1741 + * ...
5.1742 + * synchronized (s) { // Note: s, not s2!!!
5.1743 + * Iterator i = s2.iterator(); // Must be in the synchronized block
5.1744 + * while (i.hasNext())
5.1745 + * foo(i.next());
5.1746 + * }
5.1747 + * </pre>
5.1748 + * Failure to follow this advice may result in non-deterministic behavior.
5.1749 + *
5.1750 + * <p>The returned sorted set will be serializable if the specified
5.1751 + * sorted set is serializable.
5.1752 + *
5.1753 + * @param s the sorted set to be "wrapped" in a synchronized sorted set.
5.1754 + * @return a synchronized view of the specified sorted set.
5.1755 + */
5.1756 + public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
5.1757 + return new SynchronizedSortedSet<>(s);
5.1758 + }
5.1759 +
5.1760 + /**
5.1761 + * @serial include
5.1762 + */
5.1763 + static class SynchronizedSortedSet<E>
5.1764 + extends SynchronizedSet<E>
5.1765 + implements SortedSet<E>
5.1766 + {
5.1767 + private static final long serialVersionUID = 8695801310862127406L;
5.1768 +
5.1769 + private final SortedSet<E> ss;
5.1770 +
5.1771 + SynchronizedSortedSet(SortedSet<E> s) {
5.1772 + super(s);
5.1773 + ss = s;
5.1774 + }
5.1775 + SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
5.1776 + super(s, mutex);
5.1777 + ss = s;
5.1778 + }
5.1779 +
5.1780 + public Comparator<? super E> comparator() {
5.1781 + synchronized (mutex) {return ss.comparator();}
5.1782 + }
5.1783 +
5.1784 + public SortedSet<E> subSet(E fromElement, E toElement) {
5.1785 + synchronized (mutex) {
5.1786 + return new SynchronizedSortedSet<>(
5.1787 + ss.subSet(fromElement, toElement), mutex);
5.1788 + }
5.1789 + }
5.1790 + public SortedSet<E> headSet(E toElement) {
5.1791 + synchronized (mutex) {
5.1792 + return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);
5.1793 + }
5.1794 + }
5.1795 + public SortedSet<E> tailSet(E fromElement) {
5.1796 + synchronized (mutex) {
5.1797 + return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);
5.1798 + }
5.1799 + }
5.1800 +
5.1801 + public E first() {
5.1802 + synchronized (mutex) {return ss.first();}
5.1803 + }
5.1804 + public E last() {
5.1805 + synchronized (mutex) {return ss.last();}
5.1806 + }
5.1807 + }
5.1808 +
5.1809 + /**
5.1810 + * Returns a synchronized (thread-safe) list backed by the specified
5.1811 + * list. In order to guarantee serial access, it is critical that
5.1812 + * <strong>all</strong> access to the backing list is accomplished
5.1813 + * through the returned list.<p>
5.1814 + *
5.1815 + * It is imperative that the user manually synchronize on the returned
5.1816 + * list when iterating over it:
5.1817 + * <pre>
5.1818 + * List list = Collections.synchronizedList(new ArrayList());
5.1819 + * ...
5.1820 + * synchronized (list) {
5.1821 + * Iterator i = list.iterator(); // Must be in synchronized block
5.1822 + * while (i.hasNext())
5.1823 + * foo(i.next());
5.1824 + * }
5.1825 + * </pre>
5.1826 + * Failure to follow this advice may result in non-deterministic behavior.
5.1827 + *
5.1828 + * <p>The returned list will be serializable if the specified list is
5.1829 + * serializable.
5.1830 + *
5.1831 + * @param list the list to be "wrapped" in a synchronized list.
5.1832 + * @return a synchronized view of the specified list.
5.1833 + */
5.1834 + public static <T> List<T> synchronizedList(List<T> list) {
5.1835 + return (list instanceof RandomAccess ?
5.1836 + new SynchronizedRandomAccessList<>(list) :
5.1837 + new SynchronizedList<>(list));
5.1838 + }
5.1839 +
5.1840 + static <T> List<T> synchronizedList(List<T> list, Object mutex) {
5.1841 + return (list instanceof RandomAccess ?
5.1842 + new SynchronizedRandomAccessList<>(list, mutex) :
5.1843 + new SynchronizedList<>(list, mutex));
5.1844 + }
5.1845 +
5.1846 + /**
5.1847 + * @serial include
5.1848 + */
5.1849 + static class SynchronizedList<E>
5.1850 + extends SynchronizedCollection<E>
5.1851 + implements List<E> {
5.1852 + private static final long serialVersionUID = -7754090372962971524L;
5.1853 +
5.1854 + final List<E> list;
5.1855 +
5.1856 + SynchronizedList(List<E> list) {
5.1857 + super(list);
5.1858 + this.list = list;
5.1859 + }
5.1860 + SynchronizedList(List<E> list, Object mutex) {
5.1861 + super(list, mutex);
5.1862 + this.list = list;
5.1863 + }
5.1864 +
5.1865 + public boolean equals(Object o) {
5.1866 + synchronized (mutex) {return list.equals(o);}
5.1867 + }
5.1868 + public int hashCode() {
5.1869 + synchronized (mutex) {return list.hashCode();}
5.1870 + }
5.1871 +
5.1872 + public E get(int index) {
5.1873 + synchronized (mutex) {return list.get(index);}
5.1874 + }
5.1875 + public E set(int index, E element) {
5.1876 + synchronized (mutex) {return list.set(index, element);}
5.1877 + }
5.1878 + public void add(int index, E element) {
5.1879 + synchronized (mutex) {list.add(index, element);}
5.1880 + }
5.1881 + public E remove(int index) {
5.1882 + synchronized (mutex) {return list.remove(index);}
5.1883 + }
5.1884 +
5.1885 + public int indexOf(Object o) {
5.1886 + synchronized (mutex) {return list.indexOf(o);}
5.1887 + }
5.1888 + public int lastIndexOf(Object o) {
5.1889 + synchronized (mutex) {return list.lastIndexOf(o);}
5.1890 + }
5.1891 +
5.1892 + public boolean addAll(int index, Collection<? extends E> c) {
5.1893 + synchronized (mutex) {return list.addAll(index, c);}
5.1894 + }
5.1895 +
5.1896 + public ListIterator<E> listIterator() {
5.1897 + return list.listIterator(); // Must be manually synched by user
5.1898 + }
5.1899 +
5.1900 + public ListIterator<E> listIterator(int index) {
5.1901 + return list.listIterator(index); // Must be manually synched by user
5.1902 + }
5.1903 +
5.1904 + public List<E> subList(int fromIndex, int toIndex) {
5.1905 + synchronized (mutex) {
5.1906 + return new SynchronizedList<>(list.subList(fromIndex, toIndex),
5.1907 + mutex);
5.1908 + }
5.1909 + }
5.1910 +
5.1911 + /**
5.1912 + * SynchronizedRandomAccessList instances are serialized as
5.1913 + * SynchronizedList instances to allow them to be deserialized
5.1914 + * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).
5.1915 + * This method inverts the transformation. As a beneficial
5.1916 + * side-effect, it also grafts the RandomAccess marker onto
5.1917 + * SynchronizedList instances that were serialized in pre-1.4 JREs.
5.1918 + *
5.1919 + * Note: Unfortunately, SynchronizedRandomAccessList instances
5.1920 + * serialized in 1.4.1 and deserialized in 1.4 will become
5.1921 + * SynchronizedList instances, as this method was missing in 1.4.
5.1922 + */
5.1923 + private Object readResolve() {
5.1924 + return (list instanceof RandomAccess
5.1925 + ? new SynchronizedRandomAccessList<>(list)
5.1926 + : this);
5.1927 + }
5.1928 + }
5.1929 +
5.1930 + /**
5.1931 + * @serial include
5.1932 + */
5.1933 + static class SynchronizedRandomAccessList<E>
5.1934 + extends SynchronizedList<E>
5.1935 + implements RandomAccess {
5.1936 +
5.1937 + SynchronizedRandomAccessList(List<E> list) {
5.1938 + super(list);
5.1939 + }
5.1940 +
5.1941 + SynchronizedRandomAccessList(List<E> list, Object mutex) {
5.1942 + super(list, mutex);
5.1943 + }
5.1944 +
5.1945 + public List<E> subList(int fromIndex, int toIndex) {
5.1946 + synchronized (mutex) {
5.1947 + return new SynchronizedRandomAccessList<>(
5.1948 + list.subList(fromIndex, toIndex), mutex);
5.1949 + }
5.1950 + }
5.1951 +
5.1952 + private static final long serialVersionUID = 1530674583602358482L;
5.1953 +
5.1954 + /**
5.1955 + * Allows instances to be deserialized in pre-1.4 JREs (which do
5.1956 + * not have SynchronizedRandomAccessList). SynchronizedList has
5.1957 + * a readResolve method that inverts this transformation upon
5.1958 + * deserialization.
5.1959 + */
5.1960 + private Object writeReplace() {
5.1961 + return new SynchronizedList<>(list);
5.1962 + }
5.1963 + }
5.1964 +
5.1965 + /**
5.1966 + * Returns a synchronized (thread-safe) map backed by the specified
5.1967 + * map. In order to guarantee serial access, it is critical that
5.1968 + * <strong>all</strong> access to the backing map is accomplished
5.1969 + * through the returned map.<p>
5.1970 + *
5.1971 + * It is imperative that the user manually synchronize on the returned
5.1972 + * map when iterating over any of its collection views:
5.1973 + * <pre>
5.1974 + * Map m = Collections.synchronizedMap(new HashMap());
5.1975 + * ...
5.1976 + * Set s = m.keySet(); // Needn't be in synchronized block
5.1977 + * ...
5.1978 + * synchronized (m) { // Synchronizing on m, not s!
5.1979 + * Iterator i = s.iterator(); // Must be in synchronized block
5.1980 + * while (i.hasNext())
5.1981 + * foo(i.next());
5.1982 + * }
5.1983 + * </pre>
5.1984 + * Failure to follow this advice may result in non-deterministic behavior.
5.1985 + *
5.1986 + * <p>The returned map will be serializable if the specified map is
5.1987 + * serializable.
5.1988 + *
5.1989 + * @param m the map to be "wrapped" in a synchronized map.
5.1990 + * @return a synchronized view of the specified map.
5.1991 + */
5.1992 + public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
5.1993 + return new SynchronizedMap<>(m);
5.1994 + }
5.1995 +
5.1996 + /**
5.1997 + * @serial include
5.1998 + */
5.1999 + private static class SynchronizedMap<K,V>
5.2000 + implements Map<K,V>, Serializable {
5.2001 + private static final long serialVersionUID = 1978198479659022715L;
5.2002 +
5.2003 + private final Map<K,V> m; // Backing Map
5.2004 + final Object mutex; // Object on which to synchronize
5.2005 +
5.2006 + SynchronizedMap(Map<K,V> m) {
5.2007 + if (m==null)
5.2008 + throw new NullPointerException();
5.2009 + this.m = m;
5.2010 + mutex = this;
5.2011 + }
5.2012 +
5.2013 + SynchronizedMap(Map<K,V> m, Object mutex) {
5.2014 + this.m = m;
5.2015 + this.mutex = mutex;
5.2016 + }
5.2017 +
5.2018 + public int size() {
5.2019 + synchronized (mutex) {return m.size();}
5.2020 + }
5.2021 + public boolean isEmpty() {
5.2022 + synchronized (mutex) {return m.isEmpty();}
5.2023 + }
5.2024 + public boolean containsKey(Object key) {
5.2025 + synchronized (mutex) {return m.containsKey(key);}
5.2026 + }
5.2027 + public boolean containsValue(Object value) {
5.2028 + synchronized (mutex) {return m.containsValue(value);}
5.2029 + }
5.2030 + public V get(Object key) {
5.2031 + synchronized (mutex) {return m.get(key);}
5.2032 + }
5.2033 +
5.2034 + public V put(K key, V value) {
5.2035 + synchronized (mutex) {return m.put(key, value);}
5.2036 + }
5.2037 + public V remove(Object key) {
5.2038 + synchronized (mutex) {return m.remove(key);}
5.2039 + }
5.2040 + public void putAll(Map<? extends K, ? extends V> map) {
5.2041 + synchronized (mutex) {m.putAll(map);}
5.2042 + }
5.2043 + public void clear() {
5.2044 + synchronized (mutex) {m.clear();}
5.2045 + }
5.2046 +
5.2047 + private transient Set<K> keySet = null;
5.2048 + private transient Set<Map.Entry<K,V>> entrySet = null;
5.2049 + private transient Collection<V> values = null;
5.2050 +
5.2051 + public Set<K> keySet() {
5.2052 + synchronized (mutex) {
5.2053 + if (keySet==null)
5.2054 + keySet = new SynchronizedSet<>(m.keySet(), mutex);
5.2055 + return keySet;
5.2056 + }
5.2057 + }
5.2058 +
5.2059 + public Set<Map.Entry<K,V>> entrySet() {
5.2060 + synchronized (mutex) {
5.2061 + if (entrySet==null)
5.2062 + entrySet = new SynchronizedSet<>(m.entrySet(), mutex);
5.2063 + return entrySet;
5.2064 + }
5.2065 + }
5.2066 +
5.2067 + public Collection<V> values() {
5.2068 + synchronized (mutex) {
5.2069 + if (values==null)
5.2070 + values = new SynchronizedCollection<>(m.values(), mutex);
5.2071 + return values;
5.2072 + }
5.2073 + }
5.2074 +
5.2075 + public boolean equals(Object o) {
5.2076 + synchronized (mutex) {return m.equals(o);}
5.2077 + }
5.2078 + public int hashCode() {
5.2079 + synchronized (mutex) {return m.hashCode();}
5.2080 + }
5.2081 + public String toString() {
5.2082 + synchronized (mutex) {return m.toString();}
5.2083 + }
5.2084 + }
5.2085 +
5.2086 + /**
5.2087 + * Returns a synchronized (thread-safe) sorted map backed by the specified
5.2088 + * sorted map. In order to guarantee serial access, it is critical that
5.2089 + * <strong>all</strong> access to the backing sorted map is accomplished
5.2090 + * through the returned sorted map (or its views).<p>
5.2091 + *
5.2092 + * It is imperative that the user manually synchronize on the returned
5.2093 + * sorted map when iterating over any of its collection views, or the
5.2094 + * collections views of any of its <tt>subMap</tt>, <tt>headMap</tt> or
5.2095 + * <tt>tailMap</tt> views.
5.2096 + * <pre>
5.2097 + * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
5.2098 + * ...
5.2099 + * Set s = m.keySet(); // Needn't be in synchronized block
5.2100 + * ...
5.2101 + * synchronized (m) { // Synchronizing on m, not s!
5.2102 + * Iterator i = s.iterator(); // Must be in synchronized block
5.2103 + * while (i.hasNext())
5.2104 + * foo(i.next());
5.2105 + * }
5.2106 + * </pre>
5.2107 + * or:
5.2108 + * <pre>
5.2109 + * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
5.2110 + * SortedMap m2 = m.subMap(foo, bar);
5.2111 + * ...
5.2112 + * Set s2 = m2.keySet(); // Needn't be in synchronized block
5.2113 + * ...
5.2114 + * synchronized (m) { // Synchronizing on m, not m2 or s2!
5.2115 + * Iterator i = s.iterator(); // Must be in synchronized block
5.2116 + * while (i.hasNext())
5.2117 + * foo(i.next());
5.2118 + * }
5.2119 + * </pre>
5.2120 + * Failure to follow this advice may result in non-deterministic behavior.
5.2121 + *
5.2122 + * <p>The returned sorted map will be serializable if the specified
5.2123 + * sorted map is serializable.
5.2124 + *
5.2125 + * @param m the sorted map to be "wrapped" in a synchronized sorted map.
5.2126 + * @return a synchronized view of the specified sorted map.
5.2127 + */
5.2128 + public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
5.2129 + return new SynchronizedSortedMap<>(m);
5.2130 + }
5.2131 +
5.2132 +
5.2133 + /**
5.2134 + * @serial include
5.2135 + */
5.2136 + static class SynchronizedSortedMap<K,V>
5.2137 + extends SynchronizedMap<K,V>
5.2138 + implements SortedMap<K,V>
5.2139 + {
5.2140 + private static final long serialVersionUID = -8798146769416483793L;
5.2141 +
5.2142 + private final SortedMap<K,V> sm;
5.2143 +
5.2144 + SynchronizedSortedMap(SortedMap<K,V> m) {
5.2145 + super(m);
5.2146 + sm = m;
5.2147 + }
5.2148 + SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {
5.2149 + super(m, mutex);
5.2150 + sm = m;
5.2151 + }
5.2152 +
5.2153 + public Comparator<? super K> comparator() {
5.2154 + synchronized (mutex) {return sm.comparator();}
5.2155 + }
5.2156 +
5.2157 + public SortedMap<K,V> subMap(K fromKey, K toKey) {
5.2158 + synchronized (mutex) {
5.2159 + return new SynchronizedSortedMap<>(
5.2160 + sm.subMap(fromKey, toKey), mutex);
5.2161 + }
5.2162 + }
5.2163 + public SortedMap<K,V> headMap(K toKey) {
5.2164 + synchronized (mutex) {
5.2165 + return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);
5.2166 + }
5.2167 + }
5.2168 + public SortedMap<K,V> tailMap(K fromKey) {
5.2169 + synchronized (mutex) {
5.2170 + return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);
5.2171 + }
5.2172 + }
5.2173 +
5.2174 + public K firstKey() {
5.2175 + synchronized (mutex) {return sm.firstKey();}
5.2176 + }
5.2177 + public K lastKey() {
5.2178 + synchronized (mutex) {return sm.lastKey();}
5.2179 + }
5.2180 + }
5.2181 +
5.2182 + // Dynamically typesafe collection wrappers
5.2183 +
5.2184 + /**
5.2185 + * Returns a dynamically typesafe view of the specified collection.
5.2186 + * Any attempt to insert an element of the wrong type will result in an
5.2187 + * immediate {@link ClassCastException}. Assuming a collection
5.2188 + * contains no incorrectly typed elements prior to the time a
5.2189 + * dynamically typesafe view is generated, and that all subsequent
5.2190 + * access to the collection takes place through the view, it is
5.2191 + * <i>guaranteed</i> that the collection cannot contain an incorrectly
5.2192 + * typed element.
5.2193 + *
5.2194 + * <p>The generics mechanism in the language provides compile-time
5.2195 + * (static) type checking, but it is possible to defeat this mechanism
5.2196 + * with unchecked casts. Usually this is not a problem, as the compiler
5.2197 + * issues warnings on all such unchecked operations. There are, however,
5.2198 + * times when static type checking alone is not sufficient. For example,
5.2199 + * suppose a collection is passed to a third-party library and it is
5.2200 + * imperative that the library code not corrupt the collection by
5.2201 + * inserting an element of the wrong type.
5.2202 + *
5.2203 + * <p>Another use of dynamically typesafe views is debugging. Suppose a
5.2204 + * program fails with a {@code ClassCastException}, indicating that an
5.2205 + * incorrectly typed element was put into a parameterized collection.
5.2206 + * Unfortunately, the exception can occur at any time after the erroneous
5.2207 + * element is inserted, so it typically provides little or no information
5.2208 + * as to the real source of the problem. If the problem is reproducible,
5.2209 + * one can quickly determine its source by temporarily modifying the
5.2210 + * program to wrap the collection with a dynamically typesafe view.
5.2211 + * For example, this declaration:
5.2212 + * <pre> {@code
5.2213 + * Collection<String> c = new HashSet<String>();
5.2214 + * }</pre>
5.2215 + * may be replaced temporarily by this one:
5.2216 + * <pre> {@code
5.2217 + * Collection<String> c = Collections.checkedCollection(
5.2218 + * new HashSet<String>(), String.class);
5.2219 + * }</pre>
5.2220 + * Running the program again will cause it to fail at the point where
5.2221 + * an incorrectly typed element is inserted into the collection, clearly
5.2222 + * identifying the source of the problem. Once the problem is fixed, the
5.2223 + * modified declaration may be reverted back to the original.
5.2224 + *
5.2225 + * <p>The returned collection does <i>not</i> pass the hashCode and equals
5.2226 + * operations through to the backing collection, but relies on
5.2227 + * {@code Object}'s {@code equals} and {@code hashCode} methods. This
5.2228 + * is necessary to preserve the contracts of these operations in the case
5.2229 + * that the backing collection is a set or a list.
5.2230 + *
5.2231 + * <p>The returned collection will be serializable if the specified
5.2232 + * collection is serializable.
5.2233 + *
5.2234 + * <p>Since {@code null} is considered to be a value of any reference
5.2235 + * type, the returned collection permits insertion of null elements
5.2236 + * whenever the backing collection does.
5.2237 + *
5.2238 + * @param c the collection for which a dynamically typesafe view is to be
5.2239 + * returned
5.2240 + * @param type the type of element that {@code c} is permitted to hold
5.2241 + * @return a dynamically typesafe view of the specified collection
5.2242 + * @since 1.5
5.2243 + */
5.2244 + public static <E> Collection<E> checkedCollection(Collection<E> c,
5.2245 + Class<E> type) {
5.2246 + return new CheckedCollection<>(c, type);
5.2247 + }
5.2248 +
5.2249 + @SuppressWarnings("unchecked")
5.2250 + static <T> T[] zeroLengthArray(Class<T> type) {
5.2251 + return (T[]) Array.newInstance(type, 0);
5.2252 + }
5.2253 +
5.2254 + /**
5.2255 + * @serial include
5.2256 + */
5.2257 + static class CheckedCollection<E> implements Collection<E>, Serializable {
5.2258 + private static final long serialVersionUID = 1578914078182001775L;
5.2259 +
5.2260 + final Collection<E> c;
5.2261 + final Class<E> type;
5.2262 +
5.2263 + void typeCheck(Object o) {
5.2264 + if (o != null && !type.isInstance(o))
5.2265 + throw new ClassCastException(badElementMsg(o));
5.2266 + }
5.2267 +
5.2268 + private String badElementMsg(Object o) {
5.2269 + return "Attempt to insert " + o.getClass() +
5.2270 + " element into collection with element type " + type;
5.2271 + }
5.2272 +
5.2273 + CheckedCollection(Collection<E> c, Class<E> type) {
5.2274 + if (c==null || type == null)
5.2275 + throw new NullPointerException();
5.2276 + this.c = c;
5.2277 + this.type = type;
5.2278 + }
5.2279 +
5.2280 + public int size() { return c.size(); }
5.2281 + public boolean isEmpty() { return c.isEmpty(); }
5.2282 + public boolean contains(Object o) { return c.contains(o); }
5.2283 + public Object[] toArray() { return c.toArray(); }
5.2284 + public <T> T[] toArray(T[] a) { return c.toArray(a); }
5.2285 + public String toString() { return c.toString(); }
5.2286 + public boolean remove(Object o) { return c.remove(o); }
5.2287 + public void clear() { c.clear(); }
5.2288 +
5.2289 + public boolean containsAll(Collection<?> coll) {
5.2290 + return c.containsAll(coll);
5.2291 + }
5.2292 + public boolean removeAll(Collection<?> coll) {
5.2293 + return c.removeAll(coll);
5.2294 + }
5.2295 + public boolean retainAll(Collection<?> coll) {
5.2296 + return c.retainAll(coll);
5.2297 + }
5.2298 +
5.2299 + public Iterator<E> iterator() {
5.2300 + final Iterator<E> it = c.iterator();
5.2301 + return new Iterator<E>() {
5.2302 + public boolean hasNext() { return it.hasNext(); }
5.2303 + public E next() { return it.next(); }
5.2304 + public void remove() { it.remove(); }};
5.2305 + }
5.2306 +
5.2307 + public boolean add(E e) {
5.2308 + typeCheck(e);
5.2309 + return c.add(e);
5.2310 + }
5.2311 +
5.2312 + private E[] zeroLengthElementArray = null; // Lazily initialized
5.2313 +
5.2314 + private E[] zeroLengthElementArray() {
5.2315 + return zeroLengthElementArray != null ? zeroLengthElementArray :
5.2316 + (zeroLengthElementArray = zeroLengthArray(type));
5.2317 + }
5.2318 +
5.2319 + @SuppressWarnings("unchecked")
5.2320 + Collection<E> checkedCopyOf(Collection<? extends E> coll) {
5.2321 + Object[] a = null;
5.2322 + try {
5.2323 + E[] z = zeroLengthElementArray();
5.2324 + a = coll.toArray(z);
5.2325 + // Defend against coll violating the toArray contract
5.2326 + if (a.getClass() != z.getClass())
5.2327 + a = Arrays.copyOf(a, a.length, z.getClass());
5.2328 + } catch (ArrayStoreException ignore) {
5.2329 + // To get better and consistent diagnostics,
5.2330 + // we call typeCheck explicitly on each element.
5.2331 + // We call clone() to defend against coll retaining a
5.2332 + // reference to the returned array and storing a bad
5.2333 + // element into it after it has been type checked.
5.2334 + a = coll.toArray().clone();
5.2335 + for (Object o : a)
5.2336 + typeCheck(o);
5.2337 + }
5.2338 + // A slight abuse of the type system, but safe here.
5.2339 + return (Collection<E>) Arrays.asList(a);
5.2340 + }
5.2341 +
5.2342 + public boolean addAll(Collection<? extends E> coll) {
5.2343 + // Doing things this way insulates us from concurrent changes
5.2344 + // in the contents of coll and provides all-or-nothing
5.2345 + // semantics (which we wouldn't get if we type-checked each
5.2346 + // element as we added it)
5.2347 + return c.addAll(checkedCopyOf(coll));
5.2348 + }
5.2349 + }
5.2350 +
5.2351 + /**
5.2352 + * Returns a dynamically typesafe view of the specified set.
5.2353 + * Any attempt to insert an element of the wrong type will result in
5.2354 + * an immediate {@link ClassCastException}. Assuming a set contains
5.2355 + * no incorrectly typed elements prior to the time a dynamically typesafe
5.2356 + * view is generated, and that all subsequent access to the set
5.2357 + * takes place through the view, it is <i>guaranteed</i> that the
5.2358 + * set cannot contain an incorrectly typed element.
5.2359 + *
5.2360 + * <p>A discussion of the use of dynamically typesafe views may be
5.2361 + * found in the documentation for the {@link #checkedCollection
5.2362 + * checkedCollection} method.
5.2363 + *
5.2364 + * <p>The returned set will be serializable if the specified set is
5.2365 + * serializable.
5.2366 + *
5.2367 + * <p>Since {@code null} is considered to be a value of any reference
5.2368 + * type, the returned set permits insertion of null elements whenever
5.2369 + * the backing set does.
5.2370 + *
5.2371 + * @param s the set for which a dynamically typesafe view is to be
5.2372 + * returned
5.2373 + * @param type the type of element that {@code s} is permitted to hold
5.2374 + * @return a dynamically typesafe view of the specified set
5.2375 + * @since 1.5
5.2376 + */
5.2377 + public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
5.2378 + return new CheckedSet<>(s, type);
5.2379 + }
5.2380 +
5.2381 + /**
5.2382 + * @serial include
5.2383 + */
5.2384 + static class CheckedSet<E> extends CheckedCollection<E>
5.2385 + implements Set<E>, Serializable
5.2386 + {
5.2387 + private static final long serialVersionUID = 4694047833775013803L;
5.2388 +
5.2389 + CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
5.2390 +
5.2391 + public boolean equals(Object o) { return o == this || c.equals(o); }
5.2392 + public int hashCode() { return c.hashCode(); }
5.2393 + }
5.2394 +
5.2395 + /**
5.2396 + * Returns a dynamically typesafe view of the specified sorted set.
5.2397 + * Any attempt to insert an element of the wrong type will result in an
5.2398 + * immediate {@link ClassCastException}. Assuming a sorted set
5.2399 + * contains no incorrectly typed elements prior to the time a
5.2400 + * dynamically typesafe view is generated, and that all subsequent
5.2401 + * access to the sorted set takes place through the view, it is
5.2402 + * <i>guaranteed</i> that the sorted set cannot contain an incorrectly
5.2403 + * typed element.
5.2404 + *
5.2405 + * <p>A discussion of the use of dynamically typesafe views may be
5.2406 + * found in the documentation for the {@link #checkedCollection
5.2407 + * checkedCollection} method.
5.2408 + *
5.2409 + * <p>The returned sorted set will be serializable if the specified sorted
5.2410 + * set is serializable.
5.2411 + *
5.2412 + * <p>Since {@code null} is considered to be a value of any reference
5.2413 + * type, the returned sorted set permits insertion of null elements
5.2414 + * whenever the backing sorted set does.
5.2415 + *
5.2416 + * @param s the sorted set for which a dynamically typesafe view is to be
5.2417 + * returned
5.2418 + * @param type the type of element that {@code s} is permitted to hold
5.2419 + * @return a dynamically typesafe view of the specified sorted set
5.2420 + * @since 1.5
5.2421 + */
5.2422 + public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
5.2423 + Class<E> type) {
5.2424 + return new CheckedSortedSet<>(s, type);
5.2425 + }
5.2426 +
5.2427 + /**
5.2428 + * @serial include
5.2429 + */
5.2430 + static class CheckedSortedSet<E> extends CheckedSet<E>
5.2431 + implements SortedSet<E>, Serializable
5.2432 + {
5.2433 + private static final long serialVersionUID = 1599911165492914959L;
5.2434 + private final SortedSet<E> ss;
5.2435 +
5.2436 + CheckedSortedSet(SortedSet<E> s, Class<E> type) {
5.2437 + super(s, type);
5.2438 + ss = s;
5.2439 + }
5.2440 +
5.2441 + public Comparator<? super E> comparator() { return ss.comparator(); }
5.2442 + public E first() { return ss.first(); }
5.2443 + public E last() { return ss.last(); }
5.2444 +
5.2445 + public SortedSet<E> subSet(E fromElement, E toElement) {
5.2446 + return checkedSortedSet(ss.subSet(fromElement,toElement), type);
5.2447 + }
5.2448 + public SortedSet<E> headSet(E toElement) {
5.2449 + return checkedSortedSet(ss.headSet(toElement), type);
5.2450 + }
5.2451 + public SortedSet<E> tailSet(E fromElement) {
5.2452 + return checkedSortedSet(ss.tailSet(fromElement), type);
5.2453 + }
5.2454 + }
5.2455 +
5.2456 + /**
5.2457 + * Returns a dynamically typesafe view of the specified list.
5.2458 + * Any attempt to insert an element of the wrong type will result in
5.2459 + * an immediate {@link ClassCastException}. Assuming a list contains
5.2460 + * no incorrectly typed elements prior to the time a dynamically typesafe
5.2461 + * view is generated, and that all subsequent access to the list
5.2462 + * takes place through the view, it is <i>guaranteed</i> that the
5.2463 + * list cannot contain an incorrectly typed element.
5.2464 + *
5.2465 + * <p>A discussion of the use of dynamically typesafe views may be
5.2466 + * found in the documentation for the {@link #checkedCollection
5.2467 + * checkedCollection} method.
5.2468 + *
5.2469 + * <p>The returned list will be serializable if the specified list
5.2470 + * is serializable.
5.2471 + *
5.2472 + * <p>Since {@code null} is considered to be a value of any reference
5.2473 + * type, the returned list permits insertion of null elements whenever
5.2474 + * the backing list does.
5.2475 + *
5.2476 + * @param list the list for which a dynamically typesafe view is to be
5.2477 + * returned
5.2478 + * @param type the type of element that {@code list} is permitted to hold
5.2479 + * @return a dynamically typesafe view of the specified list
5.2480 + * @since 1.5
5.2481 + */
5.2482 + public static <E> List<E> checkedList(List<E> list, Class<E> type) {
5.2483 + return (list instanceof RandomAccess ?
5.2484 + new CheckedRandomAccessList<>(list, type) :
5.2485 + new CheckedList<>(list, type));
5.2486 + }
5.2487 +
5.2488 + /**
5.2489 + * @serial include
5.2490 + */
5.2491 + static class CheckedList<E>
5.2492 + extends CheckedCollection<E>
5.2493 + implements List<E>
5.2494 + {
5.2495 + private static final long serialVersionUID = 65247728283967356L;
5.2496 + final List<E> list;
5.2497 +
5.2498 + CheckedList(List<E> list, Class<E> type) {
5.2499 + super(list, type);
5.2500 + this.list = list;
5.2501 + }
5.2502 +
5.2503 + public boolean equals(Object o) { return o == this || list.equals(o); }
5.2504 + public int hashCode() { return list.hashCode(); }
5.2505 + public E get(int index) { return list.get(index); }
5.2506 + public E remove(int index) { return list.remove(index); }
5.2507 + public int indexOf(Object o) { return list.indexOf(o); }
5.2508 + public int lastIndexOf(Object o) { return list.lastIndexOf(o); }
5.2509 +
5.2510 + public E set(int index, E element) {
5.2511 + typeCheck(element);
5.2512 + return list.set(index, element);
5.2513 + }
5.2514 +
5.2515 + public void add(int index, E element) {
5.2516 + typeCheck(element);
5.2517 + list.add(index, element);
5.2518 + }
5.2519 +
5.2520 + public boolean addAll(int index, Collection<? extends E> c) {
5.2521 + return list.addAll(index, checkedCopyOf(c));
5.2522 + }
5.2523 + public ListIterator<E> listIterator() { return listIterator(0); }
5.2524 +
5.2525 + public ListIterator<E> listIterator(final int index) {
5.2526 + final ListIterator<E> i = list.listIterator(index);
5.2527 +
5.2528 + return new ListIterator<E>() {
5.2529 + public boolean hasNext() { return i.hasNext(); }
5.2530 + public E next() { return i.next(); }
5.2531 + public boolean hasPrevious() { return i.hasPrevious(); }
5.2532 + public E previous() { return i.previous(); }
5.2533 + public int nextIndex() { return i.nextIndex(); }
5.2534 + public int previousIndex() { return i.previousIndex(); }
5.2535 + public void remove() { i.remove(); }
5.2536 +
5.2537 + public void set(E e) {
5.2538 + typeCheck(e);
5.2539 + i.set(e);
5.2540 + }
5.2541 +
5.2542 + public void add(E e) {
5.2543 + typeCheck(e);
5.2544 + i.add(e);
5.2545 + }
5.2546 + };
5.2547 + }
5.2548 +
5.2549 + public List<E> subList(int fromIndex, int toIndex) {
5.2550 + return new CheckedList<>(list.subList(fromIndex, toIndex), type);
5.2551 + }
5.2552 + }
5.2553 +
5.2554 + /**
5.2555 + * @serial include
5.2556 + */
5.2557 + static class CheckedRandomAccessList<E> extends CheckedList<E>
5.2558 + implements RandomAccess
5.2559 + {
5.2560 + private static final long serialVersionUID = 1638200125423088369L;
5.2561 +
5.2562 + CheckedRandomAccessList(List<E> list, Class<E> type) {
5.2563 + super(list, type);
5.2564 + }
5.2565 +
5.2566 + public List<E> subList(int fromIndex, int toIndex) {
5.2567 + return new CheckedRandomAccessList<>(
5.2568 + list.subList(fromIndex, toIndex), type);
5.2569 + }
5.2570 + }
5.2571 +
5.2572 + /**
5.2573 + * Returns a dynamically typesafe view of the specified map.
5.2574 + * Any attempt to insert a mapping whose key or value have the wrong
5.2575 + * type will result in an immediate {@link ClassCastException}.
5.2576 + * Similarly, any attempt to modify the value currently associated with
5.2577 + * a key will result in an immediate {@link ClassCastException},
5.2578 + * whether the modification is attempted directly through the map
5.2579 + * itself, or through a {@link Map.Entry} instance obtained from the
5.2580 + * map's {@link Map#entrySet() entry set} view.
5.2581 + *
5.2582 + * <p>Assuming a map contains no incorrectly typed keys or values
5.2583 + * prior to the time a dynamically typesafe view is generated, and
5.2584 + * that all subsequent access to the map takes place through the view
5.2585 + * (or one of its collection views), it is <i>guaranteed</i> that the
5.2586 + * map cannot contain an incorrectly typed key or value.
5.2587 + *
5.2588 + * <p>A discussion of the use of dynamically typesafe views may be
5.2589 + * found in the documentation for the {@link #checkedCollection
5.2590 + * checkedCollection} method.
5.2591 + *
5.2592 + * <p>The returned map will be serializable if the specified map is
5.2593 + * serializable.
5.2594 + *
5.2595 + * <p>Since {@code null} is considered to be a value of any reference
5.2596 + * type, the returned map permits insertion of null keys or values
5.2597 + * whenever the backing map does.
5.2598 + *
5.2599 + * @param m the map for which a dynamically typesafe view is to be
5.2600 + * returned
5.2601 + * @param keyType the type of key that {@code m} is permitted to hold
5.2602 + * @param valueType the type of value that {@code m} is permitted to hold
5.2603 + * @return a dynamically typesafe view of the specified map
5.2604 + * @since 1.5
5.2605 + */
5.2606 + public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
5.2607 + Class<K> keyType,
5.2608 + Class<V> valueType) {
5.2609 + return new CheckedMap<>(m, keyType, valueType);
5.2610 + }
5.2611 +
5.2612 +
5.2613 + /**
5.2614 + * @serial include
5.2615 + */
5.2616 + private static class CheckedMap<K,V>
5.2617 + implements Map<K,V>, Serializable
5.2618 + {
5.2619 + private static final long serialVersionUID = 5742860141034234728L;
5.2620 +
5.2621 + private final Map<K, V> m;
5.2622 + final Class<K> keyType;
5.2623 + final Class<V> valueType;
5.2624 +
5.2625 + private void typeCheck(Object key, Object value) {
5.2626 + if (key != null && !keyType.isInstance(key))
5.2627 + throw new ClassCastException(badKeyMsg(key));
5.2628 +
5.2629 + if (value != null && !valueType.isInstance(value))
5.2630 + throw new ClassCastException(badValueMsg(value));
5.2631 + }
5.2632 +
5.2633 + private String badKeyMsg(Object key) {
5.2634 + return "Attempt to insert " + key.getClass() +
5.2635 + " key into map with key type " + keyType;
5.2636 + }
5.2637 +
5.2638 + private String badValueMsg(Object value) {
5.2639 + return "Attempt to insert " + value.getClass() +
5.2640 + " value into map with value type " + valueType;
5.2641 + }
5.2642 +
5.2643 + CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {
5.2644 + if (m == null || keyType == null || valueType == null)
5.2645 + throw new NullPointerException();
5.2646 + this.m = m;
5.2647 + this.keyType = keyType;
5.2648 + this.valueType = valueType;
5.2649 + }
5.2650 +
5.2651 + public int size() { return m.size(); }
5.2652 + public boolean isEmpty() { return m.isEmpty(); }
5.2653 + public boolean containsKey(Object key) { return m.containsKey(key); }
5.2654 + public boolean containsValue(Object v) { return m.containsValue(v); }
5.2655 + public V get(Object key) { return m.get(key); }
5.2656 + public V remove(Object key) { return m.remove(key); }
5.2657 + public void clear() { m.clear(); }
5.2658 + public Set<K> keySet() { return m.keySet(); }
5.2659 + public Collection<V> values() { return m.values(); }
5.2660 + public boolean equals(Object o) { return o == this || m.equals(o); }
5.2661 + public int hashCode() { return m.hashCode(); }
5.2662 + public String toString() { return m.toString(); }
5.2663 +
5.2664 + public V put(K key, V value) {
5.2665 + typeCheck(key, value);
5.2666 + return m.put(key, value);
5.2667 + }
5.2668 +
5.2669 + @SuppressWarnings("unchecked")
5.2670 + public void putAll(Map<? extends K, ? extends V> t) {
5.2671 + // Satisfy the following goals:
5.2672 + // - good diagnostics in case of type mismatch
5.2673 + // - all-or-nothing semantics
5.2674 + // - protection from malicious t
5.2675 + // - correct behavior if t is a concurrent map
5.2676 + Object[] entries = t.entrySet().toArray();
5.2677 + List<Map.Entry<K,V>> checked = new ArrayList<>(entries.length);
5.2678 + for (Object o : entries) {
5.2679 + Map.Entry<?,?> e = (Map.Entry<?,?>) o;
5.2680 + Object k = e.getKey();
5.2681 + Object v = e.getValue();
5.2682 + typeCheck(k, v);
5.2683 + checked.add(
5.2684 + new AbstractMap.SimpleImmutableEntry<>((K) k, (V) v));
5.2685 + }
5.2686 + for (Map.Entry<K,V> e : checked)
5.2687 + m.put(e.getKey(), e.getValue());
5.2688 + }
5.2689 +
5.2690 + private transient Set<Map.Entry<K,V>> entrySet = null;
5.2691 +
5.2692 + public Set<Map.Entry<K,V>> entrySet() {
5.2693 + if (entrySet==null)
5.2694 + entrySet = new CheckedEntrySet<>(m.entrySet(), valueType);
5.2695 + return entrySet;
5.2696 + }
5.2697 +
5.2698 + /**
5.2699 + * We need this class in addition to CheckedSet as Map.Entry permits
5.2700 + * modification of the backing Map via the setValue operation. This
5.2701 + * class is subtle: there are many possible attacks that must be
5.2702 + * thwarted.
5.2703 + *
5.2704 + * @serial exclude
5.2705 + */
5.2706 + static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {
5.2707 + private final Set<Map.Entry<K,V>> s;
5.2708 + private final Class<V> valueType;
5.2709 +
5.2710 + CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {
5.2711 + this.s = s;
5.2712 + this.valueType = valueType;
5.2713 + }
5.2714 +
5.2715 + public int size() { return s.size(); }
5.2716 + public boolean isEmpty() { return s.isEmpty(); }
5.2717 + public String toString() { return s.toString(); }
5.2718 + public int hashCode() { return s.hashCode(); }
5.2719 + public void clear() { s.clear(); }
5.2720 +
5.2721 + public boolean add(Map.Entry<K, V> e) {
5.2722 + throw new UnsupportedOperationException();
5.2723 + }
5.2724 + public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) {
5.2725 + throw new UnsupportedOperationException();
5.2726 + }
5.2727 +
5.2728 + public Iterator<Map.Entry<K,V>> iterator() {
5.2729 + final Iterator<Map.Entry<K, V>> i = s.iterator();
5.2730 + final Class<V> valueType = this.valueType;
5.2731 +
5.2732 + return new Iterator<Map.Entry<K,V>>() {
5.2733 + public boolean hasNext() { return i.hasNext(); }
5.2734 + public void remove() { i.remove(); }
5.2735 +
5.2736 + public Map.Entry<K,V> next() {
5.2737 + return checkedEntry(i.next(), valueType);
5.2738 + }
5.2739 + };
5.2740 + }
5.2741 +
5.2742 + @SuppressWarnings("unchecked")
5.2743 + public Object[] toArray() {
5.2744 + Object[] source = s.toArray();
5.2745 +
5.2746 + /*
5.2747 + * Ensure that we don't get an ArrayStoreException even if
5.2748 + * s.toArray returns an array of something other than Object
5.2749 + */
5.2750 + Object[] dest = (CheckedEntry.class.isInstance(
5.2751 + source.getClass().getComponentType()) ? source :
5.2752 + new Object[source.length]);
5.2753 +
5.2754 + for (int i = 0; i < source.length; i++)
5.2755 + dest[i] = checkedEntry((Map.Entry<K,V>)source[i],
5.2756 + valueType);
5.2757 + return dest;
5.2758 + }
5.2759 +
5.2760 + @SuppressWarnings("unchecked")
5.2761 + public <T> T[] toArray(T[] a) {
5.2762 + // We don't pass a to s.toArray, to avoid window of
5.2763 + // vulnerability wherein an unscrupulous multithreaded client
5.2764 + // could get his hands on raw (unwrapped) Entries from s.
5.2765 + T[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
5.2766 +
5.2767 + for (int i=0; i<arr.length; i++)
5.2768 + arr[i] = (T) checkedEntry((Map.Entry<K,V>)arr[i],
5.2769 + valueType);
5.2770 + if (arr.length > a.length)
5.2771 + return arr;
5.2772 +
5.2773 + System.arraycopy(arr, 0, a, 0, arr.length);
5.2774 + if (a.length > arr.length)
5.2775 + a[arr.length] = null;
5.2776 + return a;
5.2777 + }
5.2778 +
5.2779 + /**
5.2780 + * This method is overridden to protect the backing set against
5.2781 + * an object with a nefarious equals function that senses
5.2782 + * that the equality-candidate is Map.Entry and calls its
5.2783 + * setValue method.
5.2784 + */
5.2785 + public boolean contains(Object o) {
5.2786 + if (!(o instanceof Map.Entry))
5.2787 + return false;
5.2788 + Map.Entry<?,?> e = (Map.Entry<?,?>) o;
5.2789 + return s.contains(
5.2790 + (e instanceof CheckedEntry) ? e : checkedEntry(e, valueType));
5.2791 + }
5.2792 +
5.2793 + /**
5.2794 + * The bulk collection methods are overridden to protect
5.2795 + * against an unscrupulous collection whose contains(Object o)
5.2796 + * method senses when o is a Map.Entry, and calls o.setValue.
5.2797 + */
5.2798 + public boolean containsAll(Collection<?> c) {
5.2799 + for (Object o : c)
5.2800 + if (!contains(o)) // Invokes safe contains() above
5.2801 + return false;
5.2802 + return true;
5.2803 + }
5.2804 +
5.2805 + public boolean remove(Object o) {
5.2806 + if (!(o instanceof Map.Entry))
5.2807 + return false;
5.2808 + return s.remove(new AbstractMap.SimpleImmutableEntry
5.2809 + <>((Map.Entry<?,?>)o));
5.2810 + }
5.2811 +
5.2812 + public boolean removeAll(Collection<?> c) {
5.2813 + return batchRemove(c, false);
5.2814 + }
5.2815 + public boolean retainAll(Collection<?> c) {
5.2816 + return batchRemove(c, true);
5.2817 + }
5.2818 + private boolean batchRemove(Collection<?> c, boolean complement) {
5.2819 + boolean modified = false;
5.2820 + Iterator<Map.Entry<K,V>> it = iterator();
5.2821 + while (it.hasNext()) {
5.2822 + if (c.contains(it.next()) != complement) {
5.2823 + it.remove();
5.2824 + modified = true;
5.2825 + }
5.2826 + }
5.2827 + return modified;
5.2828 + }
5.2829 +
5.2830 + public boolean equals(Object o) {
5.2831 + if (o == this)
5.2832 + return true;
5.2833 + if (!(o instanceof Set))
5.2834 + return false;
5.2835 + Set<?> that = (Set<?>) o;
5.2836 + return that.size() == s.size()
5.2837 + && containsAll(that); // Invokes safe containsAll() above
5.2838 + }
5.2839 +
5.2840 + static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,
5.2841 + Class<T> valueType) {
5.2842 + return new CheckedEntry<>(e, valueType);
5.2843 + }
5.2844 +
5.2845 + /**
5.2846 + * This "wrapper class" serves two purposes: it prevents
5.2847 + * the client from modifying the backing Map, by short-circuiting
5.2848 + * the setValue method, and it protects the backing Map against
5.2849 + * an ill-behaved Map.Entry that attempts to modify another
5.2850 + * Map.Entry when asked to perform an equality check.
5.2851 + */
5.2852 + private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {
5.2853 + private final Map.Entry<K, V> e;
5.2854 + private final Class<T> valueType;
5.2855 +
5.2856 + CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {
5.2857 + this.e = e;
5.2858 + this.valueType = valueType;
5.2859 + }
5.2860 +
5.2861 + public K getKey() { return e.getKey(); }
5.2862 + public V getValue() { return e.getValue(); }
5.2863 + public int hashCode() { return e.hashCode(); }
5.2864 + public String toString() { return e.toString(); }
5.2865 +
5.2866 + public V setValue(V value) {
5.2867 + if (value != null && !valueType.isInstance(value))
5.2868 + throw new ClassCastException(badValueMsg(value));
5.2869 + return e.setValue(value);
5.2870 + }
5.2871 +
5.2872 + private String badValueMsg(Object value) {
5.2873 + return "Attempt to insert " + value.getClass() +
5.2874 + " value into map with value type " + valueType;
5.2875 + }
5.2876 +
5.2877 + public boolean equals(Object o) {
5.2878 + if (o == this)
5.2879 + return true;
5.2880 + if (!(o instanceof Map.Entry))
5.2881 + return false;
5.2882 + return e.equals(new AbstractMap.SimpleImmutableEntry
5.2883 + <>((Map.Entry<?,?>)o));
5.2884 + }
5.2885 + }
5.2886 + }
5.2887 + }
5.2888 +
5.2889 + /**
5.2890 + * Returns a dynamically typesafe view of the specified sorted map.
5.2891 + * Any attempt to insert a mapping whose key or value have the wrong
5.2892 + * type will result in an immediate {@link ClassCastException}.
5.2893 + * Similarly, any attempt to modify the value currently associated with
5.2894 + * a key will result in an immediate {@link ClassCastException},
5.2895 + * whether the modification is attempted directly through the map
5.2896 + * itself, or through a {@link Map.Entry} instance obtained from the
5.2897 + * map's {@link Map#entrySet() entry set} view.
5.2898 + *
5.2899 + * <p>Assuming a map contains no incorrectly typed keys or values
5.2900 + * prior to the time a dynamically typesafe view is generated, and
5.2901 + * that all subsequent access to the map takes place through the view
5.2902 + * (or one of its collection views), it is <i>guaranteed</i> that the
5.2903 + * map cannot contain an incorrectly typed key or value.
5.2904 + *
5.2905 + * <p>A discussion of the use of dynamically typesafe views may be
5.2906 + * found in the documentation for the {@link #checkedCollection
5.2907 + * checkedCollection} method.
5.2908 + *
5.2909 + * <p>The returned map will be serializable if the specified map is
5.2910 + * serializable.
5.2911 + *
5.2912 + * <p>Since {@code null} is considered to be a value of any reference
5.2913 + * type, the returned map permits insertion of null keys or values
5.2914 + * whenever the backing map does.
5.2915 + *
5.2916 + * @param m the map for which a dynamically typesafe view is to be
5.2917 + * returned
5.2918 + * @param keyType the type of key that {@code m} is permitted to hold
5.2919 + * @param valueType the type of value that {@code m} is permitted to hold
5.2920 + * @return a dynamically typesafe view of the specified map
5.2921 + * @since 1.5
5.2922 + */
5.2923 + public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
5.2924 + Class<K> keyType,
5.2925 + Class<V> valueType) {
5.2926 + return new CheckedSortedMap<>(m, keyType, valueType);
5.2927 + }
5.2928 +
5.2929 + /**
5.2930 + * @serial include
5.2931 + */
5.2932 + static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
5.2933 + implements SortedMap<K,V>, Serializable
5.2934 + {
5.2935 + private static final long serialVersionUID = 1599671320688067438L;
5.2936 +
5.2937 + private final SortedMap<K, V> sm;
5.2938 +
5.2939 + CheckedSortedMap(SortedMap<K, V> m,
5.2940 + Class<K> keyType, Class<V> valueType) {
5.2941 + super(m, keyType, valueType);
5.2942 + sm = m;
5.2943 + }
5.2944 +
5.2945 + public Comparator<? super K> comparator() { return sm.comparator(); }
5.2946 + public K firstKey() { return sm.firstKey(); }
5.2947 + public K lastKey() { return sm.lastKey(); }
5.2948 +
5.2949 + public SortedMap<K,V> subMap(K fromKey, K toKey) {
5.2950 + return checkedSortedMap(sm.subMap(fromKey, toKey),
5.2951 + keyType, valueType);
5.2952 + }
5.2953 + public SortedMap<K,V> headMap(K toKey) {
5.2954 + return checkedSortedMap(sm.headMap(toKey), keyType, valueType);
5.2955 + }
5.2956 + public SortedMap<K,V> tailMap(K fromKey) {
5.2957 + return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);
5.2958 + }
5.2959 + }
5.2960 +
5.2961 + // Empty collections
5.2962 +
5.2963 + /**
5.2964 + * Returns an iterator that has no elements. More precisely,
5.2965 + *
5.2966 + * <ul compact>
5.2967 + *
5.2968 + * <li>{@link Iterator#hasNext hasNext} always returns {@code
5.2969 + * false}.
5.2970 + *
5.2971 + * <li>{@link Iterator#next next} always throws {@link
5.2972 + * NoSuchElementException}.
5.2973 + *
5.2974 + * <li>{@link Iterator#remove remove} always throws {@link
5.2975 + * IllegalStateException}.
5.2976 + *
5.2977 + * </ul>
5.2978 + *
5.2979 + * <p>Implementations of this method are permitted, but not
5.2980 + * required, to return the same object from multiple invocations.
5.2981 + *
5.2982 + * @return an empty iterator
5.2983 + * @since 1.7
5.2984 + */
5.2985 + @SuppressWarnings("unchecked")
5.2986 + public static <T> Iterator<T> emptyIterator() {
5.2987 + return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;
5.2988 + }
5.2989 +
5.2990 + private static class EmptyIterator<E> implements Iterator<E> {
5.2991 + static final EmptyIterator<Object> EMPTY_ITERATOR
5.2992 + = new EmptyIterator<>();
5.2993 +
5.2994 + public boolean hasNext() { return false; }
5.2995 + public E next() { throw new NoSuchElementException(); }
5.2996 + public void remove() { throw new IllegalStateException(); }
5.2997 + }
5.2998 +
5.2999 + /**
5.3000 + * Returns a list iterator that has no elements. More precisely,
5.3001 + *
5.3002 + * <ul compact>
5.3003 + *
5.3004 + * <li>{@link Iterator#hasNext hasNext} and {@link
5.3005 + * ListIterator#hasPrevious hasPrevious} always return {@code
5.3006 + * false}.
5.3007 + *
5.3008 + * <li>{@link Iterator#next next} and {@link ListIterator#previous
5.3009 + * previous} always throw {@link NoSuchElementException}.
5.3010 + *
5.3011 + * <li>{@link Iterator#remove remove} and {@link ListIterator#set
5.3012 + * set} always throw {@link IllegalStateException}.
5.3013 + *
5.3014 + * <li>{@link ListIterator#add add} always throws {@link
5.3015 + * UnsupportedOperationException}.
5.3016 + *
5.3017 + * <li>{@link ListIterator#nextIndex nextIndex} always returns
5.3018 + * {@code 0} .
5.3019 + *
5.3020 + * <li>{@link ListIterator#previousIndex previousIndex} always
5.3021 + * returns {@code -1}.
5.3022 + *
5.3023 + * </ul>
5.3024 + *
5.3025 + * <p>Implementations of this method are permitted, but not
5.3026 + * required, to return the same object from multiple invocations.
5.3027 + *
5.3028 + * @return an empty list iterator
5.3029 + * @since 1.7
5.3030 + */
5.3031 + @SuppressWarnings("unchecked")
5.3032 + public static <T> ListIterator<T> emptyListIterator() {
5.3033 + return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR;
5.3034 + }
5.3035 +
5.3036 + private static class EmptyListIterator<E>
5.3037 + extends EmptyIterator<E>
5.3038 + implements ListIterator<E>
5.3039 + {
5.3040 + static final EmptyListIterator<Object> EMPTY_ITERATOR
5.3041 + = new EmptyListIterator<>();
5.3042 +
5.3043 + public boolean hasPrevious() { return false; }
5.3044 + public E previous() { throw new NoSuchElementException(); }
5.3045 + public int nextIndex() { return 0; }
5.3046 + public int previousIndex() { return -1; }
5.3047 + public void set(E e) { throw new IllegalStateException(); }
5.3048 + public void add(E e) { throw new UnsupportedOperationException(); }
5.3049 + }
5.3050 +
5.3051 + /**
5.3052 + * Returns an enumeration that has no elements. More precisely,
5.3053 + *
5.3054 + * <ul compact>
5.3055 + *
5.3056 + * <li>{@link Enumeration#hasMoreElements hasMoreElements} always
5.3057 + * returns {@code false}.
5.3058 + *
5.3059 + * <li> {@link Enumeration#nextElement nextElement} always throws
5.3060 + * {@link NoSuchElementException}.
5.3061 + *
5.3062 + * </ul>
5.3063 + *
5.3064 + * <p>Implementations of this method are permitted, but not
5.3065 + * required, to return the same object from multiple invocations.
5.3066 + *
5.3067 + * @return an empty enumeration
5.3068 + * @since 1.7
5.3069 + */
5.3070 + @SuppressWarnings("unchecked")
5.3071 + public static <T> Enumeration<T> emptyEnumeration() {
5.3072 + return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;
5.3073 + }
5.3074 +
5.3075 + private static class EmptyEnumeration<E> implements Enumeration<E> {
5.3076 + static final EmptyEnumeration<Object> EMPTY_ENUMERATION
5.3077 + = new EmptyEnumeration<>();
5.3078 +
5.3079 + public boolean hasMoreElements() { return false; }
5.3080 + public E nextElement() { throw new NoSuchElementException(); }
5.3081 + }
5.3082 +
5.3083 + /**
5.3084 + * The empty set (immutable). This set is serializable.
5.3085 + *
5.3086 + * @see #emptySet()
5.3087 + */
5.3088 + @SuppressWarnings("unchecked")
5.3089 + public static final Set EMPTY_SET = new EmptySet<>();
5.3090 +
5.3091 + /**
5.3092 + * Returns the empty set (immutable). This set is serializable.
5.3093 + * Unlike the like-named field, this method is parameterized.
5.3094 + *
5.3095 + * <p>This example illustrates the type-safe way to obtain an empty set:
5.3096 + * <pre>
5.3097 + * Set<String> s = Collections.emptySet();
5.3098 + * </pre>
5.3099 + * Implementation note: Implementations of this method need not
5.3100 + * create a separate <tt>Set</tt> object for each call. Using this
5.3101 + * method is likely to have comparable cost to using the like-named
5.3102 + * field. (Unlike this method, the field does not provide type safety.)
5.3103 + *
5.3104 + * @see #EMPTY_SET
5.3105 + * @since 1.5
5.3106 + */
5.3107 + @SuppressWarnings("unchecked")
5.3108 + public static final <T> Set<T> emptySet() {
5.3109 + return (Set<T>) EMPTY_SET;
5.3110 + }
5.3111 +
5.3112 + /**
5.3113 + * @serial include
5.3114 + */
5.3115 + private static class EmptySet<E>
5.3116 + extends AbstractSet<E>
5.3117 + implements Serializable
5.3118 + {
5.3119 + private static final long serialVersionUID = 1582296315990362920L;
5.3120 +
5.3121 + public Iterator<E> iterator() { return emptyIterator(); }
5.3122 +
5.3123 + public int size() {return 0;}
5.3124 + public boolean isEmpty() {return true;}
5.3125 +
5.3126 + public boolean contains(Object obj) {return false;}
5.3127 + public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
5.3128 +
5.3129 + public Object[] toArray() { return new Object[0]; }
5.3130 +
5.3131 + public <T> T[] toArray(T[] a) {
5.3132 + if (a.length > 0)
5.3133 + a[0] = null;
5.3134 + return a;
5.3135 + }
5.3136 +
5.3137 + // Preserves singleton property
5.3138 + private Object readResolve() {
5.3139 + return EMPTY_SET;
5.3140 + }
5.3141 + }
5.3142 +
5.3143 + /**
5.3144 + * The empty list (immutable). This list is serializable.
5.3145 + *
5.3146 + * @see #emptyList()
5.3147 + */
5.3148 + @SuppressWarnings("unchecked")
5.3149 + public static final List EMPTY_LIST = new EmptyList<>();
5.3150 +
5.3151 + /**
5.3152 + * Returns the empty list (immutable). This list is serializable.
5.3153 + *
5.3154 + * <p>This example illustrates the type-safe way to obtain an empty list:
5.3155 + * <pre>
5.3156 + * List<String> s = Collections.emptyList();
5.3157 + * </pre>
5.3158 + * Implementation note: Implementations of this method need not
5.3159 + * create a separate <tt>List</tt> object for each call. Using this
5.3160 + * method is likely to have comparable cost to using the like-named
5.3161 + * field. (Unlike this method, the field does not provide type safety.)
5.3162 + *
5.3163 + * @see #EMPTY_LIST
5.3164 + * @since 1.5
5.3165 + */
5.3166 + @SuppressWarnings("unchecked")
5.3167 + public static final <T> List<T> emptyList() {
5.3168 + return (List<T>) EMPTY_LIST;
5.3169 + }
5.3170 +
5.3171 + /**
5.3172 + * @serial include
5.3173 + */
5.3174 + private static class EmptyList<E>
5.3175 + extends AbstractList<E>
5.3176 + implements RandomAccess, Serializable {
5.3177 + private static final long serialVersionUID = 8842843931221139166L;
5.3178 +
5.3179 + public Iterator<E> iterator() {
5.3180 + return emptyIterator();
5.3181 + }
5.3182 + public ListIterator<E> listIterator() {
5.3183 + return emptyListIterator();
5.3184 + }
5.3185 +
5.3186 + public int size() {return 0;}
5.3187 + public boolean isEmpty() {return true;}
5.3188 +
5.3189 + public boolean contains(Object obj) {return false;}
5.3190 + public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
5.3191 +
5.3192 + public Object[] toArray() { return new Object[0]; }
5.3193 +
5.3194 + public <T> T[] toArray(T[] a) {
5.3195 + if (a.length > 0)
5.3196 + a[0] = null;
5.3197 + return a;
5.3198 + }
5.3199 +
5.3200 + public E get(int index) {
5.3201 + throw new IndexOutOfBoundsException("Index: "+index);
5.3202 + }
5.3203 +
5.3204 + public boolean equals(Object o) {
5.3205 + return (o instanceof List) && ((List<?>)o).isEmpty();
5.3206 + }
5.3207 +
5.3208 + public int hashCode() { return 1; }
5.3209 +
5.3210 + // Preserves singleton property
5.3211 + private Object readResolve() {
5.3212 + return EMPTY_LIST;
5.3213 + }
5.3214 + }
5.3215 +
5.3216 + /**
5.3217 + * The empty map (immutable). This map is serializable.
5.3218 + *
5.3219 + * @see #emptyMap()
5.3220 + * @since 1.3
5.3221 + */
5.3222 + @SuppressWarnings("unchecked")
5.3223 + public static final Map EMPTY_MAP = new EmptyMap<>();
5.3224 +
5.3225 + /**
5.3226 + * Returns the empty map (immutable). This map is serializable.
5.3227 + *
5.3228 + * <p>This example illustrates the type-safe way to obtain an empty set:
5.3229 + * <pre>
5.3230 + * Map<String, Date> s = Collections.emptyMap();
5.3231 + * </pre>
5.3232 + * Implementation note: Implementations of this method need not
5.3233 + * create a separate <tt>Map</tt> object for each call. Using this
5.3234 + * method is likely to have comparable cost to using the like-named
5.3235 + * field. (Unlike this method, the field does not provide type safety.)
5.3236 + *
5.3237 + * @see #EMPTY_MAP
5.3238 + * @since 1.5
5.3239 + */
5.3240 + @SuppressWarnings("unchecked")
5.3241 + public static final <K,V> Map<K,V> emptyMap() {
5.3242 + return (Map<K,V>) EMPTY_MAP;
5.3243 + }
5.3244 +
5.3245 + /**
5.3246 + * @serial include
5.3247 + */
5.3248 + private static class EmptyMap<K,V>
5.3249 + extends AbstractMap<K,V>
5.3250 + implements Serializable
5.3251 + {
5.3252 + private static final long serialVersionUID = 6428348081105594320L;
5.3253 +
5.3254 + public int size() {return 0;}
5.3255 + public boolean isEmpty() {return true;}
5.3256 + public boolean containsKey(Object key) {return false;}
5.3257 + public boolean containsValue(Object value) {return false;}
5.3258 + public V get(Object key) {return null;}
5.3259 + public Set<K> keySet() {return emptySet();}
5.3260 + public Collection<V> values() {return emptySet();}
5.3261 + public Set<Map.Entry<K,V>> entrySet() {return emptySet();}
5.3262 +
5.3263 + public boolean equals(Object o) {
5.3264 + return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
5.3265 + }
5.3266 +
5.3267 + public int hashCode() {return 0;}
5.3268 +
5.3269 + // Preserves singleton property
5.3270 + private Object readResolve() {
5.3271 + return EMPTY_MAP;
5.3272 + }
5.3273 + }
5.3274 +
5.3275 + // Singleton collections
5.3276 +
5.3277 + /**
5.3278 + * Returns an immutable set containing only the specified object.
5.3279 + * The returned set is serializable.
5.3280 + *
5.3281 + * @param o the sole object to be stored in the returned set.
5.3282 + * @return an immutable set containing only the specified object.
5.3283 + */
5.3284 + public static <T> Set<T> singleton(T o) {
5.3285 + return new SingletonSet<>(o);
5.3286 + }
5.3287 +
5.3288 + static <E> Iterator<E> singletonIterator(final E e) {
5.3289 + return new Iterator<E>() {
5.3290 + private boolean hasNext = true;
5.3291 + public boolean hasNext() {
5.3292 + return hasNext;
5.3293 + }
5.3294 + public E next() {
5.3295 + if (hasNext) {
5.3296 + hasNext = false;
5.3297 + return e;
5.3298 + }
5.3299 + throw new NoSuchElementException();
5.3300 + }
5.3301 + public void remove() {
5.3302 + throw new UnsupportedOperationException();
5.3303 + }
5.3304 + };
5.3305 + }
5.3306 +
5.3307 + /**
5.3308 + * @serial include
5.3309 + */
5.3310 + private static class SingletonSet<E>
5.3311 + extends AbstractSet<E>
5.3312 + implements Serializable
5.3313 + {
5.3314 + private static final long serialVersionUID = 3193687207550431679L;
5.3315 +
5.3316 + private final E element;
5.3317 +
5.3318 + SingletonSet(E e) {element = e;}
5.3319 +
5.3320 + public Iterator<E> iterator() {
5.3321 + return singletonIterator(element);
5.3322 + }
5.3323 +
5.3324 + public int size() {return 1;}
5.3325 +
5.3326 + public boolean contains(Object o) {return eq(o, element);}
5.3327 + }
5.3328 +
5.3329 + /**
5.3330 + * Returns an immutable list containing only the specified object.
5.3331 + * The returned list is serializable.
5.3332 + *
5.3333 + * @param o the sole object to be stored in the returned list.
5.3334 + * @return an immutable list containing only the specified object.
5.3335 + * @since 1.3
5.3336 + */
5.3337 + public static <T> List<T> singletonList(T o) {
5.3338 + return new SingletonList<>(o);
5.3339 + }
5.3340 +
5.3341 + /**
5.3342 + * @serial include
5.3343 + */
5.3344 + private static class SingletonList<E>
5.3345 + extends AbstractList<E>
5.3346 + implements RandomAccess, Serializable {
5.3347 +
5.3348 + private static final long serialVersionUID = 3093736618740652951L;
5.3349 +
5.3350 + private final E element;
5.3351 +
5.3352 + SingletonList(E obj) {element = obj;}
5.3353 +
5.3354 + public Iterator<E> iterator() {
5.3355 + return singletonIterator(element);
5.3356 + }
5.3357 +
5.3358 + public int size() {return 1;}
5.3359 +
5.3360 + public boolean contains(Object obj) {return eq(obj, element);}
5.3361 +
5.3362 + public E get(int index) {
5.3363 + if (index != 0)
5.3364 + throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
5.3365 + return element;
5.3366 + }
5.3367 + }
5.3368 +
5.3369 + /**
5.3370 + * Returns an immutable map, mapping only the specified key to the
5.3371 + * specified value. The returned map is serializable.
5.3372 + *
5.3373 + * @param key the sole key to be stored in the returned map.
5.3374 + * @param value the value to which the returned map maps <tt>key</tt>.
5.3375 + * @return an immutable map containing only the specified key-value
5.3376 + * mapping.
5.3377 + * @since 1.3
5.3378 + */
5.3379 + public static <K,V> Map<K,V> singletonMap(K key, V value) {
5.3380 + return new SingletonMap<>(key, value);
5.3381 + }
5.3382 +
5.3383 + /**
5.3384 + * @serial include
5.3385 + */
5.3386 + private static class SingletonMap<K,V>
5.3387 + extends AbstractMap<K,V>
5.3388 + implements Serializable {
5.3389 + private static final long serialVersionUID = -6979724477215052911L;
5.3390 +
5.3391 + private final K k;
5.3392 + private final V v;
5.3393 +
5.3394 + SingletonMap(K key, V value) {
5.3395 + k = key;
5.3396 + v = value;
5.3397 + }
5.3398 +
5.3399 + public int size() {return 1;}
5.3400 +
5.3401 + public boolean isEmpty() {return false;}
5.3402 +
5.3403 + public boolean containsKey(Object key) {return eq(key, k);}
5.3404 +
5.3405 + public boolean containsValue(Object value) {return eq(value, v);}
5.3406 +
5.3407 + public V get(Object key) {return (eq(key, k) ? v : null);}
5.3408 +
5.3409 + private transient Set<K> keySet = null;
5.3410 + private transient Set<Map.Entry<K,V>> entrySet = null;
5.3411 + private transient Collection<V> values = null;
5.3412 +
5.3413 + public Set<K> keySet() {
5.3414 + if (keySet==null)
5.3415 + keySet = singleton(k);
5.3416 + return keySet;
5.3417 + }
5.3418 +
5.3419 + public Set<Map.Entry<K,V>> entrySet() {
5.3420 + if (entrySet==null)
5.3421 + entrySet = Collections.<Map.Entry<K,V>>singleton(
5.3422 + new SimpleImmutableEntry<>(k, v));
5.3423 + return entrySet;
5.3424 + }
5.3425 +
5.3426 + public Collection<V> values() {
5.3427 + if (values==null)
5.3428 + values = singleton(v);
5.3429 + return values;
5.3430 + }
5.3431 +
5.3432 + }
5.3433 +
5.3434 + // Miscellaneous
5.3435 +
5.3436 + /**
5.3437 + * Returns an immutable list consisting of <tt>n</tt> copies of the
5.3438 + * specified object. The newly allocated data object is tiny (it contains
5.3439 + * a single reference to the data object). This method is useful in
5.3440 + * combination with the <tt>List.addAll</tt> method to grow lists.
5.3441 + * The returned list is serializable.
5.3442 + *
5.3443 + * @param n the number of elements in the returned list.
5.3444 + * @param o the element to appear repeatedly in the returned list.
5.3445 + * @return an immutable list consisting of <tt>n</tt> copies of the
5.3446 + * specified object.
5.3447 + * @throws IllegalArgumentException if {@code n < 0}
5.3448 + * @see List#addAll(Collection)
5.3449 + * @see List#addAll(int, Collection)
5.3450 + */
5.3451 + public static <T> List<T> nCopies(int n, T o) {
5.3452 + if (n < 0)
5.3453 + throw new IllegalArgumentException("List length = " + n);
5.3454 + return new CopiesList<>(n, o);
5.3455 + }
5.3456 +
5.3457 + /**
5.3458 + * @serial include
5.3459 + */
5.3460 + private static class CopiesList<E>
5.3461 + extends AbstractList<E>
5.3462 + implements RandomAccess, Serializable
5.3463 + {
5.3464 + private static final long serialVersionUID = 2739099268398711800L;
5.3465 +
5.3466 + final int n;
5.3467 + final E element;
5.3468 +
5.3469 + CopiesList(int n, E e) {
5.3470 + assert n >= 0;
5.3471 + this.n = n;
5.3472 + element = e;
5.3473 + }
5.3474 +
5.3475 + public int size() {
5.3476 + return n;
5.3477 + }
5.3478 +
5.3479 + public boolean contains(Object obj) {
5.3480 + return n != 0 && eq(obj, element);
5.3481 + }
5.3482 +
5.3483 + public int indexOf(Object o) {
5.3484 + return contains(o) ? 0 : -1;
5.3485 + }
5.3486 +
5.3487 + public int lastIndexOf(Object o) {
5.3488 + return contains(o) ? n - 1 : -1;
5.3489 + }
5.3490 +
5.3491 + public E get(int index) {
5.3492 + if (index < 0 || index >= n)
5.3493 + throw new IndexOutOfBoundsException("Index: "+index+
5.3494 + ", Size: "+n);
5.3495 + return element;
5.3496 + }
5.3497 +
5.3498 + public Object[] toArray() {
5.3499 + final Object[] a = new Object[n];
5.3500 + if (element != null)
5.3501 + Arrays.fill(a, 0, n, element);
5.3502 + return a;
5.3503 + }
5.3504 +
5.3505 + public <T> T[] toArray(T[] a) {
5.3506 + final int n = this.n;
5.3507 + if (a.length < n) {
5.3508 + a = (T[])java.lang.reflect.Array
5.3509 + .newInstance(a.getClass().getComponentType(), n);
5.3510 + if (element != null)
5.3511 + Arrays.fill(a, 0, n, element);
5.3512 + } else {
5.3513 + Arrays.fill(a, 0, n, element);
5.3514 + if (a.length > n)
5.3515 + a[n] = null;
5.3516 + }
5.3517 + return a;
5.3518 + }
5.3519 +
5.3520 + public List<E> subList(int fromIndex, int toIndex) {
5.3521 + if (fromIndex < 0)
5.3522 + throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
5.3523 + if (toIndex > n)
5.3524 + throw new IndexOutOfBoundsException("toIndex = " + toIndex);
5.3525 + if (fromIndex > toIndex)
5.3526 + throw new IllegalArgumentException("fromIndex(" + fromIndex +
5.3527 + ") > toIndex(" + toIndex + ")");
5.3528 + return new CopiesList<>(toIndex - fromIndex, element);
5.3529 + }
5.3530 + }
5.3531 +
5.3532 + /**
5.3533 + * Returns a comparator that imposes the reverse of the <em>natural
5.3534 + * ordering</em> on a collection of objects that implement the
5.3535 + * {@code Comparable} interface. (The natural ordering is the ordering
5.3536 + * imposed by the objects' own {@code compareTo} method.) This enables a
5.3537 + * simple idiom for sorting (or maintaining) collections (or arrays) of
5.3538 + * objects that implement the {@code Comparable} interface in
5.3539 + * reverse-natural-order. For example, suppose {@code a} is an array of
5.3540 + * strings. Then: <pre>
5.3541 + * Arrays.sort(a, Collections.reverseOrder());
5.3542 + * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
5.3543 + *
5.3544 + * The returned comparator is serializable.
5.3545 + *
5.3546 + * @return A comparator that imposes the reverse of the <i>natural
5.3547 + * ordering</i> on a collection of objects that implement
5.3548 + * the <tt>Comparable</tt> interface.
5.3549 + * @see Comparable
5.3550 + */
5.3551 + public static <T> Comparator<T> reverseOrder() {
5.3552 + return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5.3553 + }
5.3554 +
5.3555 + /**
5.3556 + * @serial include
5.3557 + */
5.3558 + private static class ReverseComparator
5.3559 + implements Comparator<Comparable<Object>>, Serializable {
5.3560 +
5.3561 + private static final long serialVersionUID = 7207038068494060240L;
5.3562 +
5.3563 + static final ReverseComparator REVERSE_ORDER
5.3564 + = new ReverseComparator();
5.3565 +
5.3566 + public int compare(Comparable<Object> c1, Comparable<Object> c2) {
5.3567 + return c2.compareTo(c1);
5.3568 + }
5.3569 +
5.3570 + private Object readResolve() { return reverseOrder(); }
5.3571 + }
5.3572 +
5.3573 + /**
5.3574 + * Returns a comparator that imposes the reverse ordering of the specified
5.3575 + * comparator. If the specified comparator is {@code null}, this method is
5.3576 + * equivalent to {@link #reverseOrder()} (in other words, it returns a
5.3577 + * comparator that imposes the reverse of the <em>natural ordering</em> on
5.3578 + * a collection of objects that implement the Comparable interface).
5.3579 + *
5.3580 + * <p>The returned comparator is serializable (assuming the specified
5.3581 + * comparator is also serializable or {@code null}).
5.3582 + *
5.3583 + * @param cmp a comparator who's ordering is to be reversed by the returned
5.3584 + * comparator or {@code null}
5.3585 + * @return A comparator that imposes the reverse ordering of the
5.3586 + * specified comparator.
5.3587 + * @since 1.5
5.3588 + */
5.3589 + public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
5.3590 + if (cmp == null)
5.3591 + return reverseOrder();
5.3592 +
5.3593 + if (cmp instanceof ReverseComparator2)
5.3594 + return ((ReverseComparator2<T>)cmp).cmp;
5.3595 +
5.3596 + return new ReverseComparator2<>(cmp);
5.3597 + }
5.3598 +
5.3599 + /**
5.3600 + * @serial include
5.3601 + */
5.3602 + private static class ReverseComparator2<T> implements Comparator<T>,
5.3603 + Serializable
5.3604 + {
5.3605 + private static final long serialVersionUID = 4374092139857L;
5.3606 +
5.3607 + /**
5.3608 + * The comparator specified in the static factory. This will never
5.3609 + * be null, as the static factory returns a ReverseComparator
5.3610 + * instance if its argument is null.
5.3611 + *
5.3612 + * @serial
5.3613 + */
5.3614 + final Comparator<T> cmp;
5.3615 +
5.3616 + ReverseComparator2(Comparator<T> cmp) {
5.3617 + assert cmp != null;
5.3618 + this.cmp = cmp;
5.3619 + }
5.3620 +
5.3621 + public int compare(T t1, T t2) {
5.3622 + return cmp.compare(t2, t1);
5.3623 + }
5.3624 +
5.3625 + public boolean equals(Object o) {
5.3626 + return (o == this) ||
5.3627 + (o instanceof ReverseComparator2 &&
5.3628 + cmp.equals(((ReverseComparator2)o).cmp));
5.3629 + }
5.3630 +
5.3631 + public int hashCode() {
5.3632 + return cmp.hashCode() ^ Integer.MIN_VALUE;
5.3633 + }
5.3634 + }
5.3635 +
5.3636 + /**
5.3637 + * Returns an enumeration over the specified collection. This provides
5.3638 + * interoperability with legacy APIs that require an enumeration
5.3639 + * as input.
5.3640 + *
5.3641 + * @param c the collection for which an enumeration is to be returned.
5.3642 + * @return an enumeration over the specified collection.
5.3643 + * @see Enumeration
5.3644 + */
5.3645 + public static <T> Enumeration<T> enumeration(final Collection<T> c) {
5.3646 + return new Enumeration<T>() {
5.3647 + private final Iterator<T> i = c.iterator();
5.3648 +
5.3649 + public boolean hasMoreElements() {
5.3650 + return i.hasNext();
5.3651 + }
5.3652 +
5.3653 + public T nextElement() {
5.3654 + return i.next();
5.3655 + }
5.3656 + };
5.3657 + }
5.3658 +
5.3659 + /**
5.3660 + * Returns an array list containing the elements returned by the
5.3661 + * specified enumeration in the order they are returned by the
5.3662 + * enumeration. This method provides interoperability between
5.3663 + * legacy APIs that return enumerations and new APIs that require
5.3664 + * collections.
5.3665 + *
5.3666 + * @param e enumeration providing elements for the returned
5.3667 + * array list
5.3668 + * @return an array list containing the elements returned
5.3669 + * by the specified enumeration.
5.3670 + * @since 1.4
5.3671 + * @see Enumeration
5.3672 + * @see ArrayList
5.3673 + */
5.3674 + public static <T> ArrayList<T> list(Enumeration<T> e) {
5.3675 + ArrayList<T> l = new ArrayList<>();
5.3676 + while (e.hasMoreElements())
5.3677 + l.add(e.nextElement());
5.3678 + return l;
5.3679 + }
5.3680 +
5.3681 + /**
5.3682 + * Returns true if the specified arguments are equal, or both null.
5.3683 + */
5.3684 + static boolean eq(Object o1, Object o2) {
5.3685 + return o1==null ? o2==null : o1.equals(o2);
5.3686 + }
5.3687 +
5.3688 + /**
5.3689 + * Returns the number of elements in the specified collection equal to the
5.3690 + * specified object. More formally, returns the number of elements
5.3691 + * <tt>e</tt> in the collection such that
5.3692 + * <tt>(o == null ? e == null : o.equals(e))</tt>.
5.3693 + *
5.3694 + * @param c the collection in which to determine the frequency
5.3695 + * of <tt>o</tt>
5.3696 + * @param o the object whose frequency is to be determined
5.3697 + * @throws NullPointerException if <tt>c</tt> is null
5.3698 + * @since 1.5
5.3699 + */
5.3700 + public static int frequency(Collection<?> c, Object o) {
5.3701 + int result = 0;
5.3702 + if (o == null) {
5.3703 + for (Object e : c)
5.3704 + if (e == null)
5.3705 + result++;
5.3706 + } else {
5.3707 + for (Object e : c)
5.3708 + if (o.equals(e))
5.3709 + result++;
5.3710 + }
5.3711 + return result;
5.3712 + }
5.3713 +
5.3714 + /**
5.3715 + * Returns {@code true} if the two specified collections have no
5.3716 + * elements in common.
5.3717 + *
5.3718 + * <p>Care must be exercised if this method is used on collections that
5.3719 + * do not comply with the general contract for {@code Collection}.
5.3720 + * Implementations may elect to iterate over either collection and test
5.3721 + * for containment in the other collection (or to perform any equivalent
5.3722 + * computation). If either collection uses a nonstandard equality test
5.3723 + * (as does a {@link SortedSet} whose ordering is not <em>compatible with
5.3724 + * equals</em>, or the key set of an {@link IdentityHashMap}), both
5.3725 + * collections must use the same nonstandard equality test, or the
5.3726 + * result of this method is undefined.
5.3727 + *
5.3728 + * <p>Care must also be exercised when using collections that have
5.3729 + * restrictions on the elements that they may contain. Collection
5.3730 + * implementations are allowed to throw exceptions for any operation
5.3731 + * involving elements they deem ineligible. For absolute safety the
5.3732 + * specified collections should contain only elements which are
5.3733 + * eligible elements for both collections.
5.3734 + *
5.3735 + * <p>Note that it is permissible to pass the same collection in both
5.3736 + * parameters, in which case the method will return {@code true} if and
5.3737 + * only if the collection is empty.
5.3738 + *
5.3739 + * @param c1 a collection
5.3740 + * @param c2 a collection
5.3741 + * @return {@code true} if the two specified collections have no
5.3742 + * elements in common.
5.3743 + * @throws NullPointerException if either collection is {@code null}.
5.3744 + * @throws NullPointerException if one collection contains a {@code null}
5.3745 + * element and {@code null} is not an eligible element for the other collection.
5.3746 + * (<a href="Collection.html#optional-restrictions">optional</a>)
5.3747 + * @throws ClassCastException if one collection contains an element that is
5.3748 + * of a type which is ineligible for the other collection.
5.3749 + * (<a href="Collection.html#optional-restrictions">optional</a>)
5.3750 + * @since 1.5
5.3751 + */
5.3752 + public static boolean disjoint(Collection<?> c1, Collection<?> c2) {
5.3753 + // The collection to be used for contains(). Preference is given to
5.3754 + // the collection who's contains() has lower O() complexity.
5.3755 + Collection<?> contains = c2;
5.3756 + // The collection to be iterated. If the collections' contains() impl
5.3757 + // are of different O() complexity, the collection with slower
5.3758 + // contains() will be used for iteration. For collections who's
5.3759 + // contains() are of the same complexity then best performance is
5.3760 + // achieved by iterating the smaller collection.
5.3761 + Collection<?> iterate = c1;
5.3762 +
5.3763 + // Performance optimization cases. The heuristics:
5.3764 + // 1. Generally iterate over c1.
5.3765 + // 2. If c1 is a Set then iterate over c2.
5.3766 + // 3. If either collection is empty then result is always true.
5.3767 + // 4. Iterate over the smaller Collection.
5.3768 + if (c1 instanceof Set) {
5.3769 + // Use c1 for contains as a Set's contains() is expected to perform
5.3770 + // better than O(N/2)
5.3771 + iterate = c2;
5.3772 + contains = c1;
5.3773 + } else if (!(c2 instanceof Set)) {
5.3774 + // Both are mere Collections. Iterate over smaller collection.
5.3775 + // Example: If c1 contains 3 elements and c2 contains 50 elements and
5.3776 + // assuming contains() requires ceiling(N/2) comparisons then
5.3777 + // checking for all c1 elements in c2 would require 75 comparisons
5.3778 + // (3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring
5.3779 + // 100 comparisons (50 * ceiling(3/2)).
5.3780 + int c1size = c1.size();
5.3781 + int c2size = c2.size();
5.3782 + if (c1size == 0 || c2size == 0) {
5.3783 + // At least one collection is empty. Nothing will match.
5.3784 + return true;
5.3785 + }
5.3786 +
5.3787 + if (c1size > c2size) {
5.3788 + iterate = c2;
5.3789 + contains = c1;
5.3790 + }
5.3791 + }
5.3792 +
5.3793 + for (Object e : iterate) {
5.3794 + if (contains.contains(e)) {
5.3795 + // Found a common element. Collections are not disjoint.
5.3796 + return false;
5.3797 + }
5.3798 + }
5.3799 +
5.3800 + // No common elements were found.
5.3801 + return true;
5.3802 + }
5.3803 +
5.3804 + /**
5.3805 + * Adds all of the specified elements to the specified collection.
5.3806 + * Elements to be added may be specified individually or as an array.
5.3807 + * The behavior of this convenience method is identical to that of
5.3808 + * <tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely
5.3809 + * to run significantly faster under most implementations.
5.3810 + *
5.3811 + * <p>When elements are specified individually, this method provides a
5.3812 + * convenient way to add a few elements to an existing collection:
5.3813 + * <pre>
5.3814 + * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
5.3815 + * </pre>
5.3816 + *
5.3817 + * @param c the collection into which <tt>elements</tt> are to be inserted
5.3818 + * @param elements the elements to insert into <tt>c</tt>
5.3819 + * @return <tt>true</tt> if the collection changed as a result of the call
5.3820 + * @throws UnsupportedOperationException if <tt>c</tt> does not support
5.3821 + * the <tt>add</tt> operation
5.3822 + * @throws NullPointerException if <tt>elements</tt> contains one or more
5.3823 + * null values and <tt>c</tt> does not permit null elements, or
5.3824 + * if <tt>c</tt> or <tt>elements</tt> are <tt>null</tt>
5.3825 + * @throws IllegalArgumentException if some property of a value in
5.3826 + * <tt>elements</tt> prevents it from being added to <tt>c</tt>
5.3827 + * @see Collection#addAll(Collection)
5.3828 + * @since 1.5
5.3829 + */
5.3830 + @SafeVarargs
5.3831 + public static <T> boolean addAll(Collection<? super T> c, T... elements) {
5.3832 + boolean result = false;
5.3833 + for (T element : elements)
5.3834 + result |= c.add(element);
5.3835 + return result;
5.3836 + }
5.3837 +
5.3838 + /**
5.3839 + * Returns a set backed by the specified map. The resulting set displays
5.3840 + * the same ordering, concurrency, and performance characteristics as the
5.3841 + * backing map. In essence, this factory method provides a {@link Set}
5.3842 + * implementation corresponding to any {@link Map} implementation. There
5.3843 + * is no need to use this method on a {@link Map} implementation that
5.3844 + * already has a corresponding {@link Set} implementation (such as {@link
5.3845 + * HashMap} or {@link TreeMap}).
5.3846 + *
5.3847 + * <p>Each method invocation on the set returned by this method results in
5.3848 + * exactly one method invocation on the backing map or its <tt>keySet</tt>
5.3849 + * view, with one exception. The <tt>addAll</tt> method is implemented
5.3850 + * as a sequence of <tt>put</tt> invocations on the backing map.
5.3851 + *
5.3852 + * <p>The specified map must be empty at the time this method is invoked,
5.3853 + * and should not be accessed directly after this method returns. These
5.3854 + * conditions are ensured if the map is created empty, passed directly
5.3855 + * to this method, and no reference to the map is retained, as illustrated
5.3856 + * in the following code fragment:
5.3857 + * <pre>
5.3858 + * Set<Object> weakHashSet = Collections.newSetFromMap(
5.3859 + * new WeakHashMap<Object, Boolean>());
5.3860 + * </pre>
5.3861 + *
5.3862 + * @param map the backing map
5.3863 + * @return the set backed by the map
5.3864 + * @throws IllegalArgumentException if <tt>map</tt> is not empty
5.3865 + * @since 1.6
5.3866 + */
5.3867 + public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
5.3868 + return new SetFromMap<>(map);
5.3869 + }
5.3870 +
5.3871 + /**
5.3872 + * @serial include
5.3873 + */
5.3874 + private static class SetFromMap<E> extends AbstractSet<E>
5.3875 + implements Set<E>, Serializable
5.3876 + {
5.3877 + private final Map<E, Boolean> m; // The backing map
5.3878 + private transient Set<E> s; // Its keySet
5.3879 +
5.3880 + SetFromMap(Map<E, Boolean> map) {
5.3881 + if (!map.isEmpty())
5.3882 + throw new IllegalArgumentException("Map is non-empty");
5.3883 + m = map;
5.3884 + s = map.keySet();
5.3885 + }
5.3886 +
5.3887 + public void clear() { m.clear(); }
5.3888 + public int size() { return m.size(); }
5.3889 + public boolean isEmpty() { return m.isEmpty(); }
5.3890 + public boolean contains(Object o) { return m.containsKey(o); }
5.3891 + public boolean remove(Object o) { return m.remove(o) != null; }
5.3892 + public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }
5.3893 + public Iterator<E> iterator() { return s.iterator(); }
5.3894 + public Object[] toArray() { return s.toArray(); }
5.3895 + public <T> T[] toArray(T[] a) { return s.toArray(a); }
5.3896 + public String toString() { return s.toString(); }
5.3897 + public int hashCode() { return s.hashCode(); }
5.3898 + public boolean equals(Object o) { return o == this || s.equals(o); }
5.3899 + public boolean containsAll(Collection<?> c) {return s.containsAll(c);}
5.3900 + public boolean removeAll(Collection<?> c) {return s.removeAll(c);}
5.3901 + public boolean retainAll(Collection<?> c) {return s.retainAll(c);}
5.3902 + // addAll is the only inherited implementation
5.3903 +
5.3904 + private static final long serialVersionUID = 2454657854757543876L;
5.3905 +
5.3906 + }
5.3907 +
5.3908 + /**
5.3909 + * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
5.3910 + * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>,
5.3911 + * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This
5.3912 + * view can be useful when you would like to use a method
5.3913 + * requiring a <tt>Queue</tt> but you need Lifo ordering.
5.3914 + *
5.3915 + * <p>Each method invocation on the queue returned by this method
5.3916 + * results in exactly one method invocation on the backing deque, with
5.3917 + * one exception. The {@link Queue#addAll addAll} method is
5.3918 + * implemented as a sequence of {@link Deque#addFirst addFirst}
5.3919 + * invocations on the backing deque.
5.3920 + *
5.3921 + * @param deque the deque
5.3922 + * @return the queue
5.3923 + * @since 1.6
5.3924 + */
5.3925 + public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
5.3926 + return new AsLIFOQueue<>(deque);
5.3927 + }
5.3928 +
5.3929 + /**
5.3930 + * @serial include
5.3931 + */
5.3932 + static class AsLIFOQueue<E> extends AbstractQueue<E>
5.3933 + implements Queue<E>, Serializable {
5.3934 + private static final long serialVersionUID = 1802017725587941708L;
5.3935 + private final Deque<E> q;
5.3936 + AsLIFOQueue(Deque<E> q) { this.q = q; }
5.3937 + public boolean add(E e) { q.addFirst(e); return true; }
5.3938 + public boolean offer(E e) { return q.offerFirst(e); }
5.3939 + public E poll() { return q.pollFirst(); }
5.3940 + public E remove() { return q.removeFirst(); }
5.3941 + public E peek() { return q.peekFirst(); }
5.3942 + public E element() { return q.getFirst(); }
5.3943 + public void clear() { q.clear(); }
5.3944 + public int size() { return q.size(); }
5.3945 + public boolean isEmpty() { return q.isEmpty(); }
5.3946 + public boolean contains(Object o) { return q.contains(o); }
5.3947 + public boolean remove(Object o) { return q.remove(o); }
5.3948 + public Iterator<E> iterator() { return q.iterator(); }
5.3949 + public Object[] toArray() { return q.toArray(); }
5.3950 + public <T> T[] toArray(T[] a) { return q.toArray(a); }
5.3951 + public String toString() { return q.toString(); }
5.3952 + public boolean containsAll(Collection<?> c) {return q.containsAll(c);}
5.3953 + public boolean removeAll(Collection<?> c) {return q.removeAll(c);}
5.3954 + public boolean retainAll(Collection<?> c) {return q.retainAll(c);}
5.3955 + // We use inherited addAll; forwarding addAll would be wrong
5.3956 + }
5.3957 +}
6.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
6.2 +++ b/emul/compact/src/main/java/java/util/Deque.java Mon Jan 28 18:14:00 2013 +0100
6.3 @@ -0,0 +1,584 @@
6.4 +/*
6.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6.6 + *
6.7 + * This code is free software; you can redistribute it and/or modify it
6.8 + * under the terms of the GNU General Public License version 2 only, as
6.9 + * published by the Free Software Foundation. Oracle designates this
6.10 + * particular file as subject to the "Classpath" exception as provided
6.11 + * by Oracle in the LICENSE file that accompanied this code.
6.12 + *
6.13 + * This code is distributed in the hope that it will be useful, but WITHOUT
6.14 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
6.15 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
6.16 + * version 2 for more details (a copy is included in the LICENSE file that
6.17 + * accompanied this code).
6.18 + *
6.19 + * You should have received a copy of the GNU General Public License version
6.20 + * 2 along with this work; if not, write to the Free Software Foundation,
6.21 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
6.22 + *
6.23 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
6.24 + * or visit www.oracle.com if you need additional information or have any
6.25 + * questions.
6.26 + */
6.27 +
6.28 +/*
6.29 + * This file is available under and governed by the GNU General Public
6.30 + * License version 2 only, as published by the Free Software Foundation.
6.31 + * However, the following notice accompanied the original version of this
6.32 + * file:
6.33 + *
6.34 + * Written by Doug Lea and Josh Bloch with assistance from members of
6.35 + * JCP JSR-166 Expert Group and released to the public domain, as explained
6.36 + * at http://creativecommons.org/publicdomain/zero/1.0/
6.37 + */
6.38 +
6.39 +package java.util;
6.40 +
6.41 +/**
6.42 + * A linear collection that supports element insertion and removal at
6.43 + * both ends. The name <i>deque</i> is short for "double ended queue"
6.44 + * and is usually pronounced "deck". Most <tt>Deque</tt>
6.45 + * implementations place no fixed limits on the number of elements
6.46 + * they may contain, but this interface supports capacity-restricted
6.47 + * deques as well as those with no fixed size limit.
6.48 + *
6.49 + * <p>This interface defines methods to access the elements at both
6.50 + * ends of the deque. Methods are provided to insert, remove, and
6.51 + * examine the element. Each of these methods exists in two forms:
6.52 + * one throws an exception if the operation fails, the other returns a
6.53 + * special value (either <tt>null</tt> or <tt>false</tt>, depending on
6.54 + * the operation). The latter form of the insert operation is
6.55 + * designed specifically for use with capacity-restricted
6.56 + * <tt>Deque</tt> implementations; in most implementations, insert
6.57 + * operations cannot fail.
6.58 + *
6.59 + * <p>The twelve methods described above are summarized in the
6.60 + * following table:
6.61 + *
6.62 + * <p>
6.63 + * <table BORDER CELLPADDING=3 CELLSPACING=1>
6.64 + * <tr>
6.65 + * <td></td>
6.66 + * <td ALIGN=CENTER COLSPAN = 2> <b>First Element (Head)</b></td>
6.67 + * <td ALIGN=CENTER COLSPAN = 2> <b>Last Element (Tail)</b></td>
6.68 + * </tr>
6.69 + * <tr>
6.70 + * <td></td>
6.71 + * <td ALIGN=CENTER><em>Throws exception</em></td>
6.72 + * <td ALIGN=CENTER><em>Special value</em></td>
6.73 + * <td ALIGN=CENTER><em>Throws exception</em></td>
6.74 + * <td ALIGN=CENTER><em>Special value</em></td>
6.75 + * </tr>
6.76 + * <tr>
6.77 + * <td><b>Insert</b></td>
6.78 + * <td>{@link #addFirst addFirst(e)}</td>
6.79 + * <td>{@link #offerFirst offerFirst(e)}</td>
6.80 + * <td>{@link #addLast addLast(e)}</td>
6.81 + * <td>{@link #offerLast offerLast(e)}</td>
6.82 + * </tr>
6.83 + * <tr>
6.84 + * <td><b>Remove</b></td>
6.85 + * <td>{@link #removeFirst removeFirst()}</td>
6.86 + * <td>{@link #pollFirst pollFirst()}</td>
6.87 + * <td>{@link #removeLast removeLast()}</td>
6.88 + * <td>{@link #pollLast pollLast()}</td>
6.89 + * </tr>
6.90 + * <tr>
6.91 + * <td><b>Examine</b></td>
6.92 + * <td>{@link #getFirst getFirst()}</td>
6.93 + * <td>{@link #peekFirst peekFirst()}</td>
6.94 + * <td>{@link #getLast getLast()}</td>
6.95 + * <td>{@link #peekLast peekLast()}</td>
6.96 + * </tr>
6.97 + * </table>
6.98 + *
6.99 + * <p>This interface extends the {@link Queue} interface. When a deque is
6.100 + * used as a queue, FIFO (First-In-First-Out) behavior results. Elements are
6.101 + * added at the end of the deque and removed from the beginning. The methods
6.102 + * inherited from the <tt>Queue</tt> interface are precisely equivalent to
6.103 + * <tt>Deque</tt> methods as indicated in the following table:
6.104 + *
6.105 + * <p>
6.106 + * <table BORDER CELLPADDING=3 CELLSPACING=1>
6.107 + * <tr>
6.108 + * <td ALIGN=CENTER> <b><tt>Queue</tt> Method</b></td>
6.109 + * <td ALIGN=CENTER> <b>Equivalent <tt>Deque</tt> Method</b></td>
6.110 + * </tr>
6.111 + * <tr>
6.112 + * <td>{@link java.util.Queue#add add(e)}</td>
6.113 + * <td>{@link #addLast addLast(e)}</td>
6.114 + * </tr>
6.115 + * <tr>
6.116 + * <td>{@link java.util.Queue#offer offer(e)}</td>
6.117 + * <td>{@link #offerLast offerLast(e)}</td>
6.118 + * </tr>
6.119 + * <tr>
6.120 + * <td>{@link java.util.Queue#remove remove()}</td>
6.121 + * <td>{@link #removeFirst removeFirst()}</td>
6.122 + * </tr>
6.123 + * <tr>
6.124 + * <td>{@link java.util.Queue#poll poll()}</td>
6.125 + * <td>{@link #pollFirst pollFirst()}</td>
6.126 + * </tr>
6.127 + * <tr>
6.128 + * <td>{@link java.util.Queue#element element()}</td>
6.129 + * <td>{@link #getFirst getFirst()}</td>
6.130 + * </tr>
6.131 + * <tr>
6.132 + * <td>{@link java.util.Queue#peek peek()}</td>
6.133 + * <td>{@link #peek peekFirst()}</td>
6.134 + * </tr>
6.135 + * </table>
6.136 + *
6.137 + * <p>Deques can also be used as LIFO (Last-In-First-Out) stacks. This
6.138 + * interface should be used in preference to the legacy {@link Stack} class.
6.139 + * When a deque is used as a stack, elements are pushed and popped from the
6.140 + * beginning of the deque. Stack methods are precisely equivalent to
6.141 + * <tt>Deque</tt> methods as indicated in the table below:
6.142 + *
6.143 + * <p>
6.144 + * <table BORDER CELLPADDING=3 CELLSPACING=1>
6.145 + * <tr>
6.146 + * <td ALIGN=CENTER> <b>Stack Method</b></td>
6.147 + * <td ALIGN=CENTER> <b>Equivalent <tt>Deque</tt> Method</b></td>
6.148 + * </tr>
6.149 + * <tr>
6.150 + * <td>{@link #push push(e)}</td>
6.151 + * <td>{@link #addFirst addFirst(e)}</td>
6.152 + * </tr>
6.153 + * <tr>
6.154 + * <td>{@link #pop pop()}</td>
6.155 + * <td>{@link #removeFirst removeFirst()}</td>
6.156 + * </tr>
6.157 + * <tr>
6.158 + * <td>{@link #peek peek()}</td>
6.159 + * <td>{@link #peekFirst peekFirst()}</td>
6.160 + * </tr>
6.161 + * </table>
6.162 + *
6.163 + * <p>Note that the {@link #peek peek} method works equally well when
6.164 + * a deque is used as a queue or a stack; in either case, elements are
6.165 + * drawn from the beginning of the deque.
6.166 + *
6.167 + * <p>This interface provides two methods to remove interior
6.168 + * elements, {@link #removeFirstOccurrence removeFirstOccurrence} and
6.169 + * {@link #removeLastOccurrence removeLastOccurrence}.
6.170 + *
6.171 + * <p>Unlike the {@link List} interface, this interface does not
6.172 + * provide support for indexed access to elements.
6.173 + *
6.174 + * <p>While <tt>Deque</tt> implementations are not strictly required
6.175 + * to prohibit the insertion of null elements, they are strongly
6.176 + * encouraged to do so. Users of any <tt>Deque</tt> implementations
6.177 + * that do allow null elements are strongly encouraged <i>not</i> to
6.178 + * take advantage of the ability to insert nulls. This is so because
6.179 + * <tt>null</tt> is used as a special return value by various methods
6.180 + * to indicated that the deque is empty.
6.181 + *
6.182 + * <p><tt>Deque</tt> implementations generally do not define
6.183 + * element-based versions of the <tt>equals</tt> and <tt>hashCode</tt>
6.184 + * methods, but instead inherit the identity-based versions from class
6.185 + * <tt>Object</tt>.
6.186 + *
6.187 + * <p>This interface is a member of the <a
6.188 + * href="{@docRoot}/../technotes/guides/collections/index.html"> Java Collections
6.189 + * Framework</a>.
6.190 + *
6.191 + * @author Doug Lea
6.192 + * @author Josh Bloch
6.193 + * @since 1.6
6.194 + * @param <E> the type of elements held in this collection
6.195 + */
6.196 +
6.197 +public interface Deque<E> extends Queue<E> {
6.198 + /**
6.199 + * Inserts the specified element at the front of this deque if it is
6.200 + * possible to do so immediately without violating capacity restrictions.
6.201 + * When using a capacity-restricted deque, it is generally preferable to
6.202 + * use method {@link #offerFirst}.
6.203 + *
6.204 + * @param e the element to add
6.205 + * @throws IllegalStateException if the element cannot be added at this
6.206 + * time due to capacity restrictions
6.207 + * @throws ClassCastException if the class of the specified element
6.208 + * prevents it from being added to this deque
6.209 + * @throws NullPointerException if the specified element is null and this
6.210 + * deque does not permit null elements
6.211 + * @throws IllegalArgumentException if some property of the specified
6.212 + * element prevents it from being added to this deque
6.213 + */
6.214 + void addFirst(E e);
6.215 +
6.216 + /**
6.217 + * Inserts the specified element at the end of this deque if it is
6.218 + * possible to do so immediately without violating capacity restrictions.
6.219 + * When using a capacity-restricted deque, it is generally preferable to
6.220 + * use method {@link #offerLast}.
6.221 + *
6.222 + * <p>This method is equivalent to {@link #add}.
6.223 + *
6.224 + * @param e the element to add
6.225 + * @throws IllegalStateException if the element cannot be added at this
6.226 + * time due to capacity restrictions
6.227 + * @throws ClassCastException if the class of the specified element
6.228 + * prevents it from being added to this deque
6.229 + * @throws NullPointerException if the specified element is null and this
6.230 + * deque does not permit null elements
6.231 + * @throws IllegalArgumentException if some property of the specified
6.232 + * element prevents it from being added to this deque
6.233 + */
6.234 + void addLast(E e);
6.235 +
6.236 + /**
6.237 + * Inserts the specified element at the front of this deque unless it would
6.238 + * violate capacity restrictions. When using a capacity-restricted deque,
6.239 + * this method is generally preferable to the {@link #addFirst} method,
6.240 + * which can fail to insert an element only by throwing an exception.
6.241 + *
6.242 + * @param e the element to add
6.243 + * @return <tt>true</tt> if the element was added to this deque, else
6.244 + * <tt>false</tt>
6.245 + * @throws ClassCastException if the class of the specified element
6.246 + * prevents it from being added to this deque
6.247 + * @throws NullPointerException if the specified element is null and this
6.248 + * deque does not permit null elements
6.249 + * @throws IllegalArgumentException if some property of the specified
6.250 + * element prevents it from being added to this deque
6.251 + */
6.252 + boolean offerFirst(E e);
6.253 +
6.254 + /**
6.255 + * Inserts the specified element at the end of this deque unless it would
6.256 + * violate capacity restrictions. When using a capacity-restricted deque,
6.257 + * this method is generally preferable to the {@link #addLast} method,
6.258 + * which can fail to insert an element only by throwing an exception.
6.259 + *
6.260 + * @param e the element to add
6.261 + * @return <tt>true</tt> if the element was added to this deque, else
6.262 + * <tt>false</tt>
6.263 + * @throws ClassCastException if the class of the specified element
6.264 + * prevents it from being added to this deque
6.265 + * @throws NullPointerException if the specified element is null and this
6.266 + * deque does not permit null elements
6.267 + * @throws IllegalArgumentException if some property of the specified
6.268 + * element prevents it from being added to this deque
6.269 + */
6.270 + boolean offerLast(E e);
6.271 +
6.272 + /**
6.273 + * Retrieves and removes the first element of this deque. This method
6.274 + * differs from {@link #pollFirst pollFirst} only in that it throws an
6.275 + * exception if this deque is empty.
6.276 + *
6.277 + * @return the head of this deque
6.278 + * @throws NoSuchElementException if this deque is empty
6.279 + */
6.280 + E removeFirst();
6.281 +
6.282 + /**
6.283 + * Retrieves and removes the last element of this deque. This method
6.284 + * differs from {@link #pollLast pollLast} only in that it throws an
6.285 + * exception if this deque is empty.
6.286 + *
6.287 + * @return the tail of this deque
6.288 + * @throws NoSuchElementException if this deque is empty
6.289 + */
6.290 + E removeLast();
6.291 +
6.292 + /**
6.293 + * Retrieves and removes the first element of this deque,
6.294 + * or returns <tt>null</tt> if this deque is empty.
6.295 + *
6.296 + * @return the head of this deque, or <tt>null</tt> if this deque is empty
6.297 + */
6.298 + E pollFirst();
6.299 +
6.300 + /**
6.301 + * Retrieves and removes the last element of this deque,
6.302 + * or returns <tt>null</tt> if this deque is empty.
6.303 + *
6.304 + * @return the tail of this deque, or <tt>null</tt> if this deque is empty
6.305 + */
6.306 + E pollLast();
6.307 +
6.308 + /**
6.309 + * Retrieves, but does not remove, the first element of this deque.
6.310 + *
6.311 + * This method differs from {@link #peekFirst peekFirst} only in that it
6.312 + * throws an exception if this deque is empty.
6.313 + *
6.314 + * @return the head of this deque
6.315 + * @throws NoSuchElementException if this deque is empty
6.316 + */
6.317 + E getFirst();
6.318 +
6.319 + /**
6.320 + * Retrieves, but does not remove, the last element of this deque.
6.321 + * This method differs from {@link #peekLast peekLast} only in that it
6.322 + * throws an exception if this deque is empty.
6.323 + *
6.324 + * @return the tail of this deque
6.325 + * @throws NoSuchElementException if this deque is empty
6.326 + */
6.327 + E getLast();
6.328 +
6.329 + /**
6.330 + * Retrieves, but does not remove, the first element of this deque,
6.331 + * or returns <tt>null</tt> if this deque is empty.
6.332 + *
6.333 + * @return the head of this deque, or <tt>null</tt> if this deque is empty
6.334 + */
6.335 + E peekFirst();
6.336 +
6.337 + /**
6.338 + * Retrieves, but does not remove, the last element of this deque,
6.339 + * or returns <tt>null</tt> if this deque is empty.
6.340 + *
6.341 + * @return the tail of this deque, or <tt>null</tt> if this deque is empty
6.342 + */
6.343 + E peekLast();
6.344 +
6.345 + /**
6.346 + * Removes the first occurrence of the specified element from this deque.
6.347 + * If the deque does not contain the element, it is unchanged.
6.348 + * More formally, removes the first element <tt>e</tt> such that
6.349 + * <tt>(o==null ? e==null : o.equals(e))</tt>
6.350 + * (if such an element exists).
6.351 + * Returns <tt>true</tt> if this deque contained the specified element
6.352 + * (or equivalently, if this deque changed as a result of the call).
6.353 + *
6.354 + * @param o element to be removed from this deque, if present
6.355 + * @return <tt>true</tt> if an element was removed as a result of this call
6.356 + * @throws ClassCastException if the class of the specified element
6.357 + * is incompatible with this deque
6.358 + * (<a href="Collection.html#optional-restrictions">optional</a>)
6.359 + * @throws NullPointerException if the specified element is null and this
6.360 + * deque does not permit null elements
6.361 + * (<a href="Collection.html#optional-restrictions">optional</a>)
6.362 + */
6.363 + boolean removeFirstOccurrence(Object o);
6.364 +
6.365 + /**
6.366 + * Removes the last occurrence of the specified element from this deque.
6.367 + * If the deque does not contain the element, it is unchanged.
6.368 + * More formally, removes the last element <tt>e</tt> such that
6.369 + * <tt>(o==null ? e==null : o.equals(e))</tt>
6.370 + * (if such an element exists).
6.371 + * Returns <tt>true</tt> if this deque contained the specified element
6.372 + * (or equivalently, if this deque changed as a result of the call).
6.373 + *
6.374 + * @param o element to be removed from this deque, if present
6.375 + * @return <tt>true</tt> if an element was removed as a result of this call
6.376 + * @throws ClassCastException if the class of the specified element
6.377 + * is incompatible with this deque
6.378 + * (<a href="Collection.html#optional-restrictions">optional</a>)
6.379 + * @throws NullPointerException if the specified element is null and this
6.380 + * deque does not permit null elements
6.381 + * (<a href="Collection.html#optional-restrictions">optional</a>)
6.382 + */
6.383 + boolean removeLastOccurrence(Object o);
6.384 +
6.385 + // *** Queue methods ***
6.386 +
6.387 + /**
6.388 + * Inserts the specified element into the queue represented by this deque
6.389 + * (in other words, at the tail of this deque) if it is possible to do so
6.390 + * immediately without violating capacity restrictions, returning
6.391 + * <tt>true</tt> upon success and throwing an
6.392 + * <tt>IllegalStateException</tt> if no space is currently available.
6.393 + * When using a capacity-restricted deque, it is generally preferable to
6.394 + * use {@link #offer(Object) offer}.
6.395 + *
6.396 + * <p>This method is equivalent to {@link #addLast}.
6.397 + *
6.398 + * @param e the element to add
6.399 + * @return <tt>true</tt> (as specified by {@link Collection#add})
6.400 + * @throws IllegalStateException if the element cannot be added at this
6.401 + * time due to capacity restrictions
6.402 + * @throws ClassCastException if the class of the specified element
6.403 + * prevents it from being added to this deque
6.404 + * @throws NullPointerException if the specified element is null and this
6.405 + * deque does not permit null elements
6.406 + * @throws IllegalArgumentException if some property of the specified
6.407 + * element prevents it from being added to this deque
6.408 + */
6.409 + boolean add(E e);
6.410 +
6.411 + /**
6.412 + * Inserts the specified element into the queue represented by this deque
6.413 + * (in other words, at the tail of this deque) if it is possible to do so
6.414 + * immediately without violating capacity restrictions, returning
6.415 + * <tt>true</tt> upon success and <tt>false</tt> if no space is currently
6.416 + * available. When using a capacity-restricted deque, this method is
6.417 + * generally preferable to the {@link #add} method, which can fail to
6.418 + * insert an element only by throwing an exception.
6.419 + *
6.420 + * <p>This method is equivalent to {@link #offerLast}.
6.421 + *
6.422 + * @param e the element to add
6.423 + * @return <tt>true</tt> if the element was added to this deque, else
6.424 + * <tt>false</tt>
6.425 + * @throws ClassCastException if the class of the specified element
6.426 + * prevents it from being added to this deque
6.427 + * @throws NullPointerException if the specified element is null and this
6.428 + * deque does not permit null elements
6.429 + * @throws IllegalArgumentException if some property of the specified
6.430 + * element prevents it from being added to this deque
6.431 + */
6.432 + boolean offer(E e);
6.433 +
6.434 + /**
6.435 + * Retrieves and removes the head of the queue represented by this deque
6.436 + * (in other words, the first element of this deque).
6.437 + * This method differs from {@link #poll poll} only in that it throws an
6.438 + * exception if this deque is empty.
6.439 + *
6.440 + * <p>This method is equivalent to {@link #removeFirst()}.
6.441 + *
6.442 + * @return the head of the queue represented by this deque
6.443 + * @throws NoSuchElementException if this deque is empty
6.444 + */
6.445 + E remove();
6.446 +
6.447 + /**
6.448 + * Retrieves and removes the head of the queue represented by this deque
6.449 + * (in other words, the first element of this deque), or returns
6.450 + * <tt>null</tt> if this deque is empty.
6.451 + *
6.452 + * <p>This method is equivalent to {@link #pollFirst()}.
6.453 + *
6.454 + * @return the first element of this deque, or <tt>null</tt> if
6.455 + * this deque is empty
6.456 + */
6.457 + E poll();
6.458 +
6.459 + /**
6.460 + * Retrieves, but does not remove, the head of the queue represented by
6.461 + * this deque (in other words, the first element of this deque).
6.462 + * This method differs from {@link #peek peek} only in that it throws an
6.463 + * exception if this deque is empty.
6.464 + *
6.465 + * <p>This method is equivalent to {@link #getFirst()}.
6.466 + *
6.467 + * @return the head of the queue represented by this deque
6.468 + * @throws NoSuchElementException if this deque is empty
6.469 + */
6.470 + E element();
6.471 +
6.472 + /**
6.473 + * Retrieves, but does not remove, the head of the queue represented by
6.474 + * this deque (in other words, the first element of this deque), or
6.475 + * returns <tt>null</tt> if this deque is empty.
6.476 + *
6.477 + * <p>This method is equivalent to {@link #peekFirst()}.
6.478 + *
6.479 + * @return the head of the queue represented by this deque, or
6.480 + * <tt>null</tt> if this deque is empty
6.481 + */
6.482 + E peek();
6.483 +
6.484 +
6.485 + // *** Stack methods ***
6.486 +
6.487 + /**
6.488 + * Pushes an element onto the stack represented by this deque (in other
6.489 + * words, at the head of this deque) if it is possible to do so
6.490 + * immediately without violating capacity restrictions, returning
6.491 + * <tt>true</tt> upon success and throwing an
6.492 + * <tt>IllegalStateException</tt> if no space is currently available.
6.493 + *
6.494 + * <p>This method is equivalent to {@link #addFirst}.
6.495 + *
6.496 + * @param e the element to push
6.497 + * @throws IllegalStateException if the element cannot be added at this
6.498 + * time due to capacity restrictions
6.499 + * @throws ClassCastException if the class of the specified element
6.500 + * prevents it from being added to this deque
6.501 + * @throws NullPointerException if the specified element is null and this
6.502 + * deque does not permit null elements
6.503 + * @throws IllegalArgumentException if some property of the specified
6.504 + * element prevents it from being added to this deque
6.505 + */
6.506 + void push(E e);
6.507 +
6.508 + /**
6.509 + * Pops an element from the stack represented by this deque. In other
6.510 + * words, removes and returns the first element of this deque.
6.511 + *
6.512 + * <p>This method is equivalent to {@link #removeFirst()}.
6.513 + *
6.514 + * @return the element at the front of this deque (which is the top
6.515 + * of the stack represented by this deque)
6.516 + * @throws NoSuchElementException if this deque is empty
6.517 + */
6.518 + E pop();
6.519 +
6.520 +
6.521 + // *** Collection methods ***
6.522 +
6.523 + /**
6.524 + * Removes the first occurrence of the specified element from this deque.
6.525 + * If the deque does not contain the element, it is unchanged.
6.526 + * More formally, removes the first element <tt>e</tt> such that
6.527 + * <tt>(o==null ? e==null : o.equals(e))</tt>
6.528 + * (if such an element exists).
6.529 + * Returns <tt>true</tt> if this deque contained the specified element
6.530 + * (or equivalently, if this deque changed as a result of the call).
6.531 + *
6.532 + * <p>This method is equivalent to {@link #removeFirstOccurrence}.
6.533 + *
6.534 + * @param o element to be removed from this deque, if present
6.535 + * @return <tt>true</tt> if an element was removed as a result of this call
6.536 + * @throws ClassCastException if the class of the specified element
6.537 + * is incompatible with this deque
6.538 + * (<a href="Collection.html#optional-restrictions">optional</a>)
6.539 + * @throws NullPointerException if the specified element is null and this
6.540 + * deque does not permit null elements
6.541 + * (<a href="Collection.html#optional-restrictions">optional</a>)
6.542 + */
6.543 + boolean remove(Object o);
6.544 +
6.545 + /**
6.546 + * Returns <tt>true</tt> if this deque contains the specified element.
6.547 + * More formally, returns <tt>true</tt> if and only if this deque contains
6.548 + * at least one element <tt>e</tt> such that
6.549 + * <tt>(o==null ? e==null : o.equals(e))</tt>.
6.550 + *
6.551 + * @param o element whose presence in this deque is to be tested
6.552 + * @return <tt>true</tt> if this deque contains the specified element
6.553 + * @throws ClassCastException if the type of the specified element
6.554 + * is incompatible with this deque
6.555 + * (<a href="Collection.html#optional-restrictions">optional</a>)
6.556 + * @throws NullPointerException if the specified element is null and this
6.557 + * deque does not permit null elements
6.558 + * (<a href="Collection.html#optional-restrictions">optional</a>)
6.559 + */
6.560 + boolean contains(Object o);
6.561 +
6.562 + /**
6.563 + * Returns the number of elements in this deque.
6.564 + *
6.565 + * @return the number of elements in this deque
6.566 + */
6.567 + public int size();
6.568 +
6.569 + /**
6.570 + * Returns an iterator over the elements in this deque in proper sequence.
6.571 + * The elements will be returned in order from first (head) to last (tail).
6.572 + *
6.573 + * @return an iterator over the elements in this deque in proper sequence
6.574 + */
6.575 + Iterator<E> iterator();
6.576 +
6.577 + /**
6.578 + * Returns an iterator over the elements in this deque in reverse
6.579 + * sequential order. The elements will be returned in order from
6.580 + * last (tail) to first (head).
6.581 + *
6.582 + * @return an iterator over the elements in this deque in reverse
6.583 + * sequence
6.584 + */
6.585 + Iterator<E> descendingIterator();
6.586 +
6.587 +}
7.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
7.2 +++ b/emul/compact/src/main/java/java/util/Dictionary.java Mon Jan 28 18:14:00 2013 +0100
7.3 @@ -0,0 +1,155 @@
7.4 +/*
7.5 + * Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved.
7.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7.7 + *
7.8 + * This code is free software; you can redistribute it and/or modify it
7.9 + * under the terms of the GNU General Public License version 2 only, as
7.10 + * published by the Free Software Foundation. Oracle designates this
7.11 + * particular file as subject to the "Classpath" exception as provided
7.12 + * by Oracle in the LICENSE file that accompanied this code.
7.13 + *
7.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
7.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
7.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
7.17 + * version 2 for more details (a copy is included in the LICENSE file that
7.18 + * accompanied this code).
7.19 + *
7.20 + * You should have received a copy of the GNU General Public License version
7.21 + * 2 along with this work; if not, write to the Free Software Foundation,
7.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
7.23 + *
7.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
7.25 + * or visit www.oracle.com if you need additional information or have any
7.26 + * questions.
7.27 + */
7.28 +
7.29 +package java.util;
7.30 +
7.31 +/**
7.32 + * The <code>Dictionary</code> class is the abstract parent of any
7.33 + * class, such as <code>Hashtable</code>, which maps keys to values.
7.34 + * Every key and every value is an object. In any one <tt>Dictionary</tt>
7.35 + * object, every key is associated with at most one value. Given a
7.36 + * <tt>Dictionary</tt> and a key, the associated element can be looked up.
7.37 + * Any non-<code>null</code> object can be used as a key and as a value.
7.38 + * <p>
7.39 + * As a rule, the <code>equals</code> method should be used by
7.40 + * implementations of this class to decide if two keys are the same.
7.41 + * <p>
7.42 + * <strong>NOTE: This class is obsolete. New implementations should
7.43 + * implement the Map interface, rather than extending this class.</strong>
7.44 + *
7.45 + * @author unascribed
7.46 + * @see java.util.Map
7.47 + * @see java.lang.Object#equals(java.lang.Object)
7.48 + * @see java.lang.Object#hashCode()
7.49 + * @see java.util.Hashtable
7.50 + * @since JDK1.0
7.51 + */
7.52 +public abstract
7.53 +class Dictionary<K,V> {
7.54 + /**
7.55 + * Sole constructor. (For invocation by subclass constructors, typically
7.56 + * implicit.)
7.57 + */
7.58 + public Dictionary() {
7.59 + }
7.60 +
7.61 + /**
7.62 + * Returns the number of entries (distinct keys) in this dictionary.
7.63 + *
7.64 + * @return the number of keys in this dictionary.
7.65 + */
7.66 + abstract public int size();
7.67 +
7.68 + /**
7.69 + * Tests if this dictionary maps no keys to value. The general contract
7.70 + * for the <tt>isEmpty</tt> method is that the result is true if and only
7.71 + * if this dictionary contains no entries.
7.72 + *
7.73 + * @return <code>true</code> if this dictionary maps no keys to values;
7.74 + * <code>false</code> otherwise.
7.75 + */
7.76 + abstract public boolean isEmpty();
7.77 +
7.78 + /**
7.79 + * Returns an enumeration of the keys in this dictionary. The general
7.80 + * contract for the keys method is that an <tt>Enumeration</tt> object
7.81 + * is returned that will generate all the keys for which this dictionary
7.82 + * contains entries.
7.83 + *
7.84 + * @return an enumeration of the keys in this dictionary.
7.85 + * @see java.util.Dictionary#elements()
7.86 + * @see java.util.Enumeration
7.87 + */
7.88 + abstract public Enumeration<K> keys();
7.89 +
7.90 + /**
7.91 + * Returns an enumeration of the values in this dictionary. The general
7.92 + * contract for the <tt>elements</tt> method is that an
7.93 + * <tt>Enumeration</tt> is returned that will generate all the elements
7.94 + * contained in entries in this dictionary.
7.95 + *
7.96 + * @return an enumeration of the values in this dictionary.
7.97 + * @see java.util.Dictionary#keys()
7.98 + * @see java.util.Enumeration
7.99 + */
7.100 + abstract public Enumeration<V> elements();
7.101 +
7.102 + /**
7.103 + * Returns the value to which the key is mapped in this dictionary.
7.104 + * The general contract for the <tt>isEmpty</tt> method is that if this
7.105 + * dictionary contains an entry for the specified key, the associated
7.106 + * value is returned; otherwise, <tt>null</tt> is returned.
7.107 + *
7.108 + * @return the value to which the key is mapped in this dictionary;
7.109 + * @param key a key in this dictionary.
7.110 + * <code>null</code> if the key is not mapped to any value in
7.111 + * this dictionary.
7.112 + * @exception NullPointerException if the <tt>key</tt> is <tt>null</tt>.
7.113 + * @see java.util.Dictionary#put(java.lang.Object, java.lang.Object)
7.114 + */
7.115 + abstract public V get(Object key);
7.116 +
7.117 + /**
7.118 + * Maps the specified <code>key</code> to the specified
7.119 + * <code>value</code> in this dictionary. Neither the key nor the
7.120 + * value can be <code>null</code>.
7.121 + * <p>
7.122 + * If this dictionary already contains an entry for the specified
7.123 + * <tt>key</tt>, the value already in this dictionary for that
7.124 + * <tt>key</tt> is returned, after modifying the entry to contain the
7.125 + * new element. <p>If this dictionary does not already have an entry
7.126 + * for the specified <tt>key</tt>, an entry is created for the
7.127 + * specified <tt>key</tt> and <tt>value</tt>, and <tt>null</tt> is
7.128 + * returned.
7.129 + * <p>
7.130 + * The <code>value</code> can be retrieved by calling the
7.131 + * <code>get</code> method with a <code>key</code> that is equal to
7.132 + * the original <code>key</code>.
7.133 + *
7.134 + * @param key the hashtable key.
7.135 + * @param value the value.
7.136 + * @return the previous value to which the <code>key</code> was mapped
7.137 + * in this dictionary, or <code>null</code> if the key did not
7.138 + * have a previous mapping.
7.139 + * @exception NullPointerException if the <code>key</code> or
7.140 + * <code>value</code> is <code>null</code>.
7.141 + * @see java.lang.Object#equals(java.lang.Object)
7.142 + * @see java.util.Dictionary#get(java.lang.Object)
7.143 + */
7.144 + abstract public V put(K key, V value);
7.145 +
7.146 + /**
7.147 + * Removes the <code>key</code> (and its corresponding
7.148 + * <code>value</code>) from this dictionary. This method does nothing
7.149 + * if the <code>key</code> is not in this dictionary.
7.150 + *
7.151 + * @param key the key that needs to be removed.
7.152 + * @return the value to which the <code>key</code> had been mapped in this
7.153 + * dictionary, or <code>null</code> if the key did not have a
7.154 + * mapping.
7.155 + * @exception NullPointerException if <tt>key</tt> is <tt>null</tt>.
7.156 + */
7.157 + abstract public V remove(Object key);
7.158 +}
8.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
8.2 +++ b/emul/compact/src/main/java/java/util/EmptyStackException.java Mon Jan 28 18:14:00 2013 +0100
8.3 @@ -0,0 +1,46 @@
8.4 +/*
8.5 + * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved.
8.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
8.7 + *
8.8 + * This code is free software; you can redistribute it and/or modify it
8.9 + * under the terms of the GNU General Public License version 2 only, as
8.10 + * published by the Free Software Foundation. Oracle designates this
8.11 + * particular file as subject to the "Classpath" exception as provided
8.12 + * by Oracle in the LICENSE file that accompanied this code.
8.13 + *
8.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
8.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
8.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
8.17 + * version 2 for more details (a copy is included in the LICENSE file that
8.18 + * accompanied this code).
8.19 + *
8.20 + * You should have received a copy of the GNU General Public License version
8.21 + * 2 along with this work; if not, write to the Free Software Foundation,
8.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
8.23 + *
8.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
8.25 + * or visit www.oracle.com if you need additional information or have any
8.26 + * questions.
8.27 + */
8.28 +
8.29 +package java.util;
8.30 +
8.31 +/**
8.32 + * Thrown by methods in the <code>Stack</code> class to indicate
8.33 + * that the stack is empty.
8.34 + *
8.35 + * @author Jonathan Payne
8.36 + * @see java.util.Stack
8.37 + * @since JDK1.0
8.38 + */
8.39 +public
8.40 +class EmptyStackException extends RuntimeException {
8.41 + private static final long serialVersionUID = 5084686378493302095L;
8.42 +
8.43 + /**
8.44 + * Constructs a new <code>EmptyStackException</code> with <tt>null</tt>
8.45 + * as its error message string.
8.46 + */
8.47 + public EmptyStackException() {
8.48 + }
8.49 +}
9.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
9.2 +++ b/emul/compact/src/main/java/java/util/EventListener.java Mon Jan 28 18:14:00 2013 +0100
9.3 @@ -0,0 +1,33 @@
9.4 +/*
9.5 + * Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved.
9.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
9.7 + *
9.8 + * This code is free software; you can redistribute it and/or modify it
9.9 + * under the terms of the GNU General Public License version 2 only, as
9.10 + * published by the Free Software Foundation. Oracle designates this
9.11 + * particular file as subject to the "Classpath" exception as provided
9.12 + * by Oracle in the LICENSE file that accompanied this code.
9.13 + *
9.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
9.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
9.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
9.17 + * version 2 for more details (a copy is included in the LICENSE file that
9.18 + * accompanied this code).
9.19 + *
9.20 + * You should have received a copy of the GNU General Public License version
9.21 + * 2 along with this work; if not, write to the Free Software Foundation,
9.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
9.23 + *
9.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
9.25 + * or visit www.oracle.com if you need additional information or have any
9.26 + * questions.
9.27 + */
9.28 +
9.29 +package java.util;
9.30 +
9.31 +/**
9.32 + * A tagging interface that all event listener interfaces must extend.
9.33 + * @since JDK1.1
9.34 + */
9.35 +public interface EventListener {
9.36 +}
10.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
10.2 +++ b/emul/compact/src/main/java/java/util/EventObject.java Mon Jan 28 18:14:00 2013 +0100
10.3 @@ -0,0 +1,78 @@
10.4 +/*
10.5 + * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved.
10.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10.7 + *
10.8 + * This code is free software; you can redistribute it and/or modify it
10.9 + * under the terms of the GNU General Public License version 2 only, as
10.10 + * published by the Free Software Foundation. Oracle designates this
10.11 + * particular file as subject to the "Classpath" exception as provided
10.12 + * by Oracle in the LICENSE file that accompanied this code.
10.13 + *
10.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
10.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
10.17 + * version 2 for more details (a copy is included in the LICENSE file that
10.18 + * accompanied this code).
10.19 + *
10.20 + * You should have received a copy of the GNU General Public License version
10.21 + * 2 along with this work; if not, write to the Free Software Foundation,
10.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
10.23 + *
10.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
10.25 + * or visit www.oracle.com if you need additional information or have any
10.26 + * questions.
10.27 + */
10.28 +
10.29 +package java.util;
10.30 +
10.31 +/**
10.32 + * <p>
10.33 + * The root class from which all event state objects shall be derived.
10.34 + * <p>
10.35 + * All Events are constructed with a reference to the object, the "source",
10.36 + * that is logically deemed to be the object upon which the Event in question
10.37 + * initially occurred upon.
10.38 + *
10.39 + * @since JDK1.1
10.40 + */
10.41 +
10.42 +public class EventObject implements java.io.Serializable {
10.43 +
10.44 + private static final long serialVersionUID = 5516075349620653480L;
10.45 +
10.46 + /**
10.47 + * The object on which the Event initially occurred.
10.48 + */
10.49 + protected transient Object source;
10.50 +
10.51 + /**
10.52 + * Constructs a prototypical Event.
10.53 + *
10.54 + * @param source The object on which the Event initially occurred.
10.55 + * @exception IllegalArgumentException if source is null.
10.56 + */
10.57 + public EventObject(Object source) {
10.58 + if (source == null)
10.59 + throw new IllegalArgumentException("null source");
10.60 +
10.61 + this.source = source;
10.62 + }
10.63 +
10.64 + /**
10.65 + * The object on which the Event initially occurred.
10.66 + *
10.67 + * @return The object on which the Event initially occurred.
10.68 + */
10.69 + public Object getSource() {
10.70 + return source;
10.71 + }
10.72 +
10.73 + /**
10.74 + * Returns a String representation of this EventObject.
10.75 + *
10.76 + * @return A a String representation of this EventObject.
10.77 + */
10.78 + public String toString() {
10.79 + return getClass().getName() + "[source=" + source + "]";
10.80 + }
10.81 +}
11.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
11.2 +++ b/emul/compact/src/main/java/java/util/Hashtable.java Mon Jan 28 18:14:00 2013 +0100
11.3 @@ -0,0 +1,1005 @@
11.4 +/*
11.5 + * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
11.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
11.7 + *
11.8 + * This code is free software; you can redistribute it and/or modify it
11.9 + * under the terms of the GNU General Public License version 2 only, as
11.10 + * published by the Free Software Foundation. Oracle designates this
11.11 + * particular file as subject to the "Classpath" exception as provided
11.12 + * by Oracle in the LICENSE file that accompanied this code.
11.13 + *
11.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
11.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
11.17 + * version 2 for more details (a copy is included in the LICENSE file that
11.18 + * accompanied this code).
11.19 + *
11.20 + * You should have received a copy of the GNU General Public License version
11.21 + * 2 along with this work; if not, write to the Free Software Foundation,
11.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
11.23 + *
11.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
11.25 + * or visit www.oracle.com if you need additional information or have any
11.26 + * questions.
11.27 + */
11.28 +
11.29 +package java.util;
11.30 +import java.io.*;
11.31 +
11.32 +/**
11.33 + * This class implements a hash table, which maps keys to values. Any
11.34 + * non-<code>null</code> object can be used as a key or as a value. <p>
11.35 + *
11.36 + * To successfully store and retrieve objects from a hashtable, the
11.37 + * objects used as keys must implement the <code>hashCode</code>
11.38 + * method and the <code>equals</code> method. <p>
11.39 + *
11.40 + * An instance of <code>Hashtable</code> has two parameters that affect its
11.41 + * performance: <i>initial capacity</i> and <i>load factor</i>. The
11.42 + * <i>capacity</i> is the number of <i>buckets</i> in the hash table, and the
11.43 + * <i>initial capacity</i> is simply the capacity at the time the hash table
11.44 + * is created. Note that the hash table is <i>open</i>: in the case of a "hash
11.45 + * collision", a single bucket stores multiple entries, which must be searched
11.46 + * sequentially. The <i>load factor</i> is a measure of how full the hash
11.47 + * table is allowed to get before its capacity is automatically increased.
11.48 + * The initial capacity and load factor parameters are merely hints to
11.49 + * the implementation. The exact details as to when and whether the rehash
11.50 + * method is invoked are implementation-dependent.<p>
11.51 + *
11.52 + * Generally, the default load factor (.75) offers a good tradeoff between
11.53 + * time and space costs. Higher values decrease the space overhead but
11.54 + * increase the time cost to look up an entry (which is reflected in most
11.55 + * <tt>Hashtable</tt> operations, including <tt>get</tt> and <tt>put</tt>).<p>
11.56 + *
11.57 + * The initial capacity controls a tradeoff between wasted space and the
11.58 + * need for <code>rehash</code> operations, which are time-consuming.
11.59 + * No <code>rehash</code> operations will <i>ever</i> occur if the initial
11.60 + * capacity is greater than the maximum number of entries the
11.61 + * <tt>Hashtable</tt> will contain divided by its load factor. However,
11.62 + * setting the initial capacity too high can waste space.<p>
11.63 + *
11.64 + * If many entries are to be made into a <code>Hashtable</code>,
11.65 + * creating it with a sufficiently large capacity may allow the
11.66 + * entries to be inserted more efficiently than letting it perform
11.67 + * automatic rehashing as needed to grow the table. <p>
11.68 + *
11.69 + * This example creates a hashtable of numbers. It uses the names of
11.70 + * the numbers as keys:
11.71 + * <pre> {@code
11.72 + * Hashtable<String, Integer> numbers
11.73 + * = new Hashtable<String, Integer>();
11.74 + * numbers.put("one", 1);
11.75 + * numbers.put("two", 2);
11.76 + * numbers.put("three", 3);}</pre>
11.77 + *
11.78 + * <p>To retrieve a number, use the following code:
11.79 + * <pre> {@code
11.80 + * Integer n = numbers.get("two");
11.81 + * if (n != null) {
11.82 + * System.out.println("two = " + n);
11.83 + * }}</pre>
11.84 + *
11.85 + * <p>The iterators returned by the <tt>iterator</tt> method of the collections
11.86 + * returned by all of this class's "collection view methods" are
11.87 + * <em>fail-fast</em>: if the Hashtable is structurally modified at any time
11.88 + * after the iterator is created, in any way except through the iterator's own
11.89 + * <tt>remove</tt> method, the iterator will throw a {@link
11.90 + * ConcurrentModificationException}. Thus, in the face of concurrent
11.91 + * modification, the iterator fails quickly and cleanly, rather than risking
11.92 + * arbitrary, non-deterministic behavior at an undetermined time in the future.
11.93 + * The Enumerations returned by Hashtable's keys and elements methods are
11.94 + * <em>not</em> fail-fast.
11.95 + *
11.96 + * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
11.97 + * as it is, generally speaking, impossible to make any hard guarantees in the
11.98 + * presence of unsynchronized concurrent modification. Fail-fast iterators
11.99 + * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
11.100 + * Therefore, it would be wrong to write a program that depended on this
11.101 + * exception for its correctness: <i>the fail-fast behavior of iterators
11.102 + * should be used only to detect bugs.</i>
11.103 + *
11.104 + * <p>As of the Java 2 platform v1.2, this class was retrofitted to
11.105 + * implement the {@link Map} interface, making it a member of the
11.106 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
11.107 + *
11.108 + * Java Collections Framework</a>. Unlike the new collection
11.109 + * implementations, {@code Hashtable} is synchronized. If a
11.110 + * thread-safe implementation is not needed, it is recommended to use
11.111 + * {@link HashMap} in place of {@code Hashtable}. If a thread-safe
11.112 + * highly-concurrent implementation is desired, then it is recommended
11.113 + * to use {@link java.util.concurrent.ConcurrentHashMap} in place of
11.114 + * {@code Hashtable}.
11.115 + *
11.116 + * @author Arthur van Hoff
11.117 + * @author Josh Bloch
11.118 + * @author Neal Gafter
11.119 + * @see Object#equals(java.lang.Object)
11.120 + * @see Object#hashCode()
11.121 + * @see Hashtable#rehash()
11.122 + * @see Collection
11.123 + * @see Map
11.124 + * @see HashMap
11.125 + * @see TreeMap
11.126 + * @since JDK1.0
11.127 + */
11.128 +public class Hashtable<K,V>
11.129 + extends Dictionary<K,V>
11.130 + implements Map<K,V>, Cloneable, java.io.Serializable {
11.131 +
11.132 + /**
11.133 + * The hash table data.
11.134 + */
11.135 + private transient Entry[] table;
11.136 +
11.137 + /**
11.138 + * The total number of entries in the hash table.
11.139 + */
11.140 + private transient int count;
11.141 +
11.142 + /**
11.143 + * The table is rehashed when its size exceeds this threshold. (The
11.144 + * value of this field is (int)(capacity * loadFactor).)
11.145 + *
11.146 + * @serial
11.147 + */
11.148 + private int threshold;
11.149 +
11.150 + /**
11.151 + * The load factor for the hashtable.
11.152 + *
11.153 + * @serial
11.154 + */
11.155 + private float loadFactor;
11.156 +
11.157 + /**
11.158 + * The number of times this Hashtable has been structurally modified
11.159 + * Structural modifications are those that change the number of entries in
11.160 + * the Hashtable or otherwise modify its internal structure (e.g.,
11.161 + * rehash). This field is used to make iterators on Collection-views of
11.162 + * the Hashtable fail-fast. (See ConcurrentModificationException).
11.163 + */
11.164 + private transient int modCount = 0;
11.165 +
11.166 + /** use serialVersionUID from JDK 1.0.2 for interoperability */
11.167 + private static final long serialVersionUID = 1421746759512286392L;
11.168 +
11.169 + /**
11.170 + * Constructs a new, empty hashtable with the specified initial
11.171 + * capacity and the specified load factor.
11.172 + *
11.173 + * @param initialCapacity the initial capacity of the hashtable.
11.174 + * @param loadFactor the load factor of the hashtable.
11.175 + * @exception IllegalArgumentException if the initial capacity is less
11.176 + * than zero, or if the load factor is nonpositive.
11.177 + */
11.178 + public Hashtable(int initialCapacity, float loadFactor) {
11.179 + if (initialCapacity < 0)
11.180 + throw new IllegalArgumentException("Illegal Capacity: "+
11.181 + initialCapacity);
11.182 + if (loadFactor <= 0 || Float.isNaN(loadFactor))
11.183 + throw new IllegalArgumentException("Illegal Load: "+loadFactor);
11.184 +
11.185 + if (initialCapacity==0)
11.186 + initialCapacity = 1;
11.187 + this.loadFactor = loadFactor;
11.188 + table = new Entry[initialCapacity];
11.189 + threshold = (int)(initialCapacity * loadFactor);
11.190 + }
11.191 +
11.192 + /**
11.193 + * Constructs a new, empty hashtable with the specified initial capacity
11.194 + * and default load factor (0.75).
11.195 + *
11.196 + * @param initialCapacity the initial capacity of the hashtable.
11.197 + * @exception IllegalArgumentException if the initial capacity is less
11.198 + * than zero.
11.199 + */
11.200 + public Hashtable(int initialCapacity) {
11.201 + this(initialCapacity, 0.75f);
11.202 + }
11.203 +
11.204 + /**
11.205 + * Constructs a new, empty hashtable with a default initial capacity (11)
11.206 + * and load factor (0.75).
11.207 + */
11.208 + public Hashtable() {
11.209 + this(11, 0.75f);
11.210 + }
11.211 +
11.212 + /**
11.213 + * Constructs a new hashtable with the same mappings as the given
11.214 + * Map. The hashtable is created with an initial capacity sufficient to
11.215 + * hold the mappings in the given Map and a default load factor (0.75).
11.216 + *
11.217 + * @param t the map whose mappings are to be placed in this map.
11.218 + * @throws NullPointerException if the specified map is null.
11.219 + * @since 1.2
11.220 + */
11.221 + public Hashtable(Map<? extends K, ? extends V> t) {
11.222 + this(Math.max(2*t.size(), 11), 0.75f);
11.223 + putAll(t);
11.224 + }
11.225 +
11.226 + /**
11.227 + * Returns the number of keys in this hashtable.
11.228 + *
11.229 + * @return the number of keys in this hashtable.
11.230 + */
11.231 + public synchronized int size() {
11.232 + return count;
11.233 + }
11.234 +
11.235 + /**
11.236 + * Tests if this hashtable maps no keys to values.
11.237 + *
11.238 + * @return <code>true</code> if this hashtable maps no keys to values;
11.239 + * <code>false</code> otherwise.
11.240 + */
11.241 + public synchronized boolean isEmpty() {
11.242 + return count == 0;
11.243 + }
11.244 +
11.245 + /**
11.246 + * Returns an enumeration of the keys in this hashtable.
11.247 + *
11.248 + * @return an enumeration of the keys in this hashtable.
11.249 + * @see Enumeration
11.250 + * @see #elements()
11.251 + * @see #keySet()
11.252 + * @see Map
11.253 + */
11.254 + public synchronized Enumeration<K> keys() {
11.255 + return this.<K>getEnumeration(KEYS);
11.256 + }
11.257 +
11.258 + /**
11.259 + * Returns an enumeration of the values in this hashtable.
11.260 + * Use the Enumeration methods on the returned object to fetch the elements
11.261 + * sequentially.
11.262 + *
11.263 + * @return an enumeration of the values in this hashtable.
11.264 + * @see java.util.Enumeration
11.265 + * @see #keys()
11.266 + * @see #values()
11.267 + * @see Map
11.268 + */
11.269 + public synchronized Enumeration<V> elements() {
11.270 + return this.<V>getEnumeration(VALUES);
11.271 + }
11.272 +
11.273 + /**
11.274 + * Tests if some key maps into the specified value in this hashtable.
11.275 + * This operation is more expensive than the {@link #containsKey
11.276 + * containsKey} method.
11.277 + *
11.278 + * <p>Note that this method is identical in functionality to
11.279 + * {@link #containsValue containsValue}, (which is part of the
11.280 + * {@link Map} interface in the collections framework).
11.281 + *
11.282 + * @param value a value to search for
11.283 + * @return <code>true</code> if and only if some key maps to the
11.284 + * <code>value</code> argument in this hashtable as
11.285 + * determined by the <tt>equals</tt> method;
11.286 + * <code>false</code> otherwise.
11.287 + * @exception NullPointerException if the value is <code>null</code>
11.288 + */
11.289 + public synchronized boolean contains(Object value) {
11.290 + if (value == null) {
11.291 + throw new NullPointerException();
11.292 + }
11.293 +
11.294 + Entry tab[] = table;
11.295 + for (int i = tab.length ; i-- > 0 ;) {
11.296 + for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) {
11.297 + if (e.value.equals(value)) {
11.298 + return true;
11.299 + }
11.300 + }
11.301 + }
11.302 + return false;
11.303 + }
11.304 +
11.305 + /**
11.306 + * Returns true if this hashtable maps one or more keys to this value.
11.307 + *
11.308 + * <p>Note that this method is identical in functionality to {@link
11.309 + * #contains contains} (which predates the {@link Map} interface).
11.310 + *
11.311 + * @param value value whose presence in this hashtable is to be tested
11.312 + * @return <tt>true</tt> if this map maps one or more keys to the
11.313 + * specified value
11.314 + * @throws NullPointerException if the value is <code>null</code>
11.315 + * @since 1.2
11.316 + */
11.317 + public boolean containsValue(Object value) {
11.318 + return contains(value);
11.319 + }
11.320 +
11.321 + /**
11.322 + * Tests if the specified object is a key in this hashtable.
11.323 + *
11.324 + * @param key possible key
11.325 + * @return <code>true</code> if and only if the specified object
11.326 + * is a key in this hashtable, as determined by the
11.327 + * <tt>equals</tt> method; <code>false</code> otherwise.
11.328 + * @throws NullPointerException if the key is <code>null</code>
11.329 + * @see #contains(Object)
11.330 + */
11.331 + public synchronized boolean containsKey(Object key) {
11.332 + Entry tab[] = table;
11.333 + int hash = key.hashCode();
11.334 + int index = (hash & 0x7FFFFFFF) % tab.length;
11.335 + for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
11.336 + if ((e.hash == hash) && e.key.equals(key)) {
11.337 + return true;
11.338 + }
11.339 + }
11.340 + return false;
11.341 + }
11.342 +
11.343 + /**
11.344 + * Returns the value to which the specified key is mapped,
11.345 + * or {@code null} if this map contains no mapping for the key.
11.346 + *
11.347 + * <p>More formally, if this map contains a mapping from a key
11.348 + * {@code k} to a value {@code v} such that {@code (key.equals(k))},
11.349 + * then this method returns {@code v}; otherwise it returns
11.350 + * {@code null}. (There can be at most one such mapping.)
11.351 + *
11.352 + * @param key the key whose associated value is to be returned
11.353 + * @return the value to which the specified key is mapped, or
11.354 + * {@code null} if this map contains no mapping for the key
11.355 + * @throws NullPointerException if the specified key is null
11.356 + * @see #put(Object, Object)
11.357 + */
11.358 + public synchronized V get(Object key) {
11.359 + Entry tab[] = table;
11.360 + int hash = key.hashCode();
11.361 + int index = (hash & 0x7FFFFFFF) % tab.length;
11.362 + for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
11.363 + if ((e.hash == hash) && e.key.equals(key)) {
11.364 + return e.value;
11.365 + }
11.366 + }
11.367 + return null;
11.368 + }
11.369 +
11.370 + /**
11.371 + * The maximum size of array to allocate.
11.372 + * Some VMs reserve some header words in an array.
11.373 + * Attempts to allocate larger arrays may result in
11.374 + * OutOfMemoryError: Requested array size exceeds VM limit
11.375 + */
11.376 + private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
11.377 +
11.378 + /**
11.379 + * Increases the capacity of and internally reorganizes this
11.380 + * hashtable, in order to accommodate and access its entries more
11.381 + * efficiently. This method is called automatically when the
11.382 + * number of keys in the hashtable exceeds this hashtable's capacity
11.383 + * and load factor.
11.384 + */
11.385 + protected void rehash() {
11.386 + int oldCapacity = table.length;
11.387 + Entry[] oldMap = table;
11.388 +
11.389 + // overflow-conscious code
11.390 + int newCapacity = (oldCapacity << 1) + 1;
11.391 + if (newCapacity - MAX_ARRAY_SIZE > 0) {
11.392 + if (oldCapacity == MAX_ARRAY_SIZE)
11.393 + // Keep running with MAX_ARRAY_SIZE buckets
11.394 + return;
11.395 + newCapacity = MAX_ARRAY_SIZE;
11.396 + }
11.397 + Entry[] newMap = new Entry[newCapacity];
11.398 +
11.399 + modCount++;
11.400 + threshold = (int)(newCapacity * loadFactor);
11.401 + table = newMap;
11.402 +
11.403 + for (int i = oldCapacity ; i-- > 0 ;) {
11.404 + for (Entry<K,V> old = oldMap[i] ; old != null ; ) {
11.405 + Entry<K,V> e = old;
11.406 + old = old.next;
11.407 +
11.408 + int index = (e.hash & 0x7FFFFFFF) % newCapacity;
11.409 + e.next = newMap[index];
11.410 + newMap[index] = e;
11.411 + }
11.412 + }
11.413 + }
11.414 +
11.415 + /**
11.416 + * Maps the specified <code>key</code> to the specified
11.417 + * <code>value</code> in this hashtable. Neither the key nor the
11.418 + * value can be <code>null</code>. <p>
11.419 + *
11.420 + * The value can be retrieved by calling the <code>get</code> method
11.421 + * with a key that is equal to the original key.
11.422 + *
11.423 + * @param key the hashtable key
11.424 + * @param value the value
11.425 + * @return the previous value of the specified key in this hashtable,
11.426 + * or <code>null</code> if it did not have one
11.427 + * @exception NullPointerException if the key or value is
11.428 + * <code>null</code>
11.429 + * @see Object#equals(Object)
11.430 + * @see #get(Object)
11.431 + */
11.432 + public synchronized V put(K key, V value) {
11.433 + // Make sure the value is not null
11.434 + if (value == null) {
11.435 + throw new NullPointerException();
11.436 + }
11.437 +
11.438 + // Makes sure the key is not already in the hashtable.
11.439 + Entry tab[] = table;
11.440 + int hash = key.hashCode();
11.441 + int index = (hash & 0x7FFFFFFF) % tab.length;
11.442 + for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
11.443 + if ((e.hash == hash) && e.key.equals(key)) {
11.444 + V old = e.value;
11.445 + e.value = value;
11.446 + return old;
11.447 + }
11.448 + }
11.449 +
11.450 + modCount++;
11.451 + if (count >= threshold) {
11.452 + // Rehash the table if the threshold is exceeded
11.453 + rehash();
11.454 +
11.455 + tab = table;
11.456 + index = (hash & 0x7FFFFFFF) % tab.length;
11.457 + }
11.458 +
11.459 + // Creates the new entry.
11.460 + Entry<K,V> e = tab[index];
11.461 + tab[index] = new Entry<>(hash, key, value, e);
11.462 + count++;
11.463 + return null;
11.464 + }
11.465 +
11.466 + /**
11.467 + * Removes the key (and its corresponding value) from this
11.468 + * hashtable. This method does nothing if the key is not in the hashtable.
11.469 + *
11.470 + * @param key the key that needs to be removed
11.471 + * @return the value to which the key had been mapped in this hashtable,
11.472 + * or <code>null</code> if the key did not have a mapping
11.473 + * @throws NullPointerException if the key is <code>null</code>
11.474 + */
11.475 + public synchronized V remove(Object key) {
11.476 + Entry tab[] = table;
11.477 + int hash = key.hashCode();
11.478 + int index = (hash & 0x7FFFFFFF) % tab.length;
11.479 + for (Entry<K,V> e = tab[index], prev = null ; e != null ; prev = e, e = e.next) {
11.480 + if ((e.hash == hash) && e.key.equals(key)) {
11.481 + modCount++;
11.482 + if (prev != null) {
11.483 + prev.next = e.next;
11.484 + } else {
11.485 + tab[index] = e.next;
11.486 + }
11.487 + count--;
11.488 + V oldValue = e.value;
11.489 + e.value = null;
11.490 + return oldValue;
11.491 + }
11.492 + }
11.493 + return null;
11.494 + }
11.495 +
11.496 + /**
11.497 + * Copies all of the mappings from the specified map to this hashtable.
11.498 + * These mappings will replace any mappings that this hashtable had for any
11.499 + * of the keys currently in the specified map.
11.500 + *
11.501 + * @param t mappings to be stored in this map
11.502 + * @throws NullPointerException if the specified map is null
11.503 + * @since 1.2
11.504 + */
11.505 + public synchronized void putAll(Map<? extends K, ? extends V> t) {
11.506 + for (Map.Entry<? extends K, ? extends V> e : t.entrySet())
11.507 + put(e.getKey(), e.getValue());
11.508 + }
11.509 +
11.510 + /**
11.511 + * Clears this hashtable so that it contains no keys.
11.512 + */
11.513 + public synchronized void clear() {
11.514 + Entry tab[] = table;
11.515 + modCount++;
11.516 + for (int index = tab.length; --index >= 0; )
11.517 + tab[index] = null;
11.518 + count = 0;
11.519 + }
11.520 +
11.521 + /**
11.522 + * Creates a shallow copy of this hashtable. All the structure of the
11.523 + * hashtable itself is copied, but the keys and values are not cloned.
11.524 + * This is a relatively expensive operation.
11.525 + *
11.526 + * @return a clone of the hashtable
11.527 + */
11.528 + public synchronized Object clone() {
11.529 + try {
11.530 + Hashtable<K,V> t = (Hashtable<K,V>) super.clone();
11.531 + t.table = new Entry[table.length];
11.532 + for (int i = table.length ; i-- > 0 ; ) {
11.533 + t.table[i] = (table[i] != null)
11.534 + ? (Entry<K,V>) table[i].clone() : null;
11.535 + }
11.536 + t.keySet = null;
11.537 + t.entrySet = null;
11.538 + t.values = null;
11.539 + t.modCount = 0;
11.540 + return t;
11.541 + } catch (CloneNotSupportedException e) {
11.542 + // this shouldn't happen, since we are Cloneable
11.543 + throw new InternalError();
11.544 + }
11.545 + }
11.546 +
11.547 + /**
11.548 + * Returns a string representation of this <tt>Hashtable</tt> object
11.549 + * in the form of a set of entries, enclosed in braces and separated
11.550 + * by the ASCII characters "<tt>, </tt>" (comma and space). Each
11.551 + * entry is rendered as the key, an equals sign <tt>=</tt>, and the
11.552 + * associated element, where the <tt>toString</tt> method is used to
11.553 + * convert the key and element to strings.
11.554 + *
11.555 + * @return a string representation of this hashtable
11.556 + */
11.557 + public synchronized String toString() {
11.558 + int max = size() - 1;
11.559 + if (max == -1)
11.560 + return "{}";
11.561 +
11.562 + StringBuilder sb = new StringBuilder();
11.563 + Iterator<Map.Entry<K,V>> it = entrySet().iterator();
11.564 +
11.565 + sb.append('{');
11.566 + for (int i = 0; ; i++) {
11.567 + Map.Entry<K,V> e = it.next();
11.568 + K key = e.getKey();
11.569 + V value = e.getValue();
11.570 + sb.append(key == this ? "(this Map)" : key.toString());
11.571 + sb.append('=');
11.572 + sb.append(value == this ? "(this Map)" : value.toString());
11.573 +
11.574 + if (i == max)
11.575 + return sb.append('}').toString();
11.576 + sb.append(", ");
11.577 + }
11.578 + }
11.579 +
11.580 +
11.581 + private <T> Enumeration<T> getEnumeration(int type) {
11.582 + if (count == 0) {
11.583 + return Collections.emptyEnumeration();
11.584 + } else {
11.585 + return new Enumerator<>(type, false);
11.586 + }
11.587 + }
11.588 +
11.589 + private <T> Iterator<T> getIterator(int type) {
11.590 + if (count == 0) {
11.591 + return Collections.emptyIterator();
11.592 + } else {
11.593 + return new Enumerator<>(type, true);
11.594 + }
11.595 + }
11.596 +
11.597 + // Views
11.598 +
11.599 + /**
11.600 + * Each of these fields are initialized to contain an instance of the
11.601 + * appropriate view the first time this view is requested. The views are
11.602 + * stateless, so there's no reason to create more than one of each.
11.603 + */
11.604 + private transient volatile Set<K> keySet = null;
11.605 + private transient volatile Set<Map.Entry<K,V>> entrySet = null;
11.606 + private transient volatile Collection<V> values = null;
11.607 +
11.608 + /**
11.609 + * Returns a {@link Set} view of the keys contained in this map.
11.610 + * The set is backed by the map, so changes to the map are
11.611 + * reflected in the set, and vice-versa. If the map is modified
11.612 + * while an iteration over the set is in progress (except through
11.613 + * the iterator's own <tt>remove</tt> operation), the results of
11.614 + * the iteration are undefined. The set supports element removal,
11.615 + * which removes the corresponding mapping from the map, via the
11.616 + * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
11.617 + * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
11.618 + * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
11.619 + * operations.
11.620 + *
11.621 + * @since 1.2
11.622 + */
11.623 + public Set<K> keySet() {
11.624 + if (keySet == null)
11.625 + keySet = Collections.synchronizedSet(new KeySet(), this);
11.626 + return keySet;
11.627 + }
11.628 +
11.629 + private class KeySet extends AbstractSet<K> {
11.630 + public Iterator<K> iterator() {
11.631 + return getIterator(KEYS);
11.632 + }
11.633 + public int size() {
11.634 + return count;
11.635 + }
11.636 + public boolean contains(Object o) {
11.637 + return containsKey(o);
11.638 + }
11.639 + public boolean remove(Object o) {
11.640 + return Hashtable.this.remove(o) != null;
11.641 + }
11.642 + public void clear() {
11.643 + Hashtable.this.clear();
11.644 + }
11.645 + }
11.646 +
11.647 + /**
11.648 + * Returns a {@link Set} view of the mappings contained in this map.
11.649 + * The set is backed by the map, so changes to the map are
11.650 + * reflected in the set, and vice-versa. If the map is modified
11.651 + * while an iteration over the set is in progress (except through
11.652 + * the iterator's own <tt>remove</tt> operation, or through the
11.653 + * <tt>setValue</tt> operation on a map entry returned by the
11.654 + * iterator) the results of the iteration are undefined. The set
11.655 + * supports element removal, which removes the corresponding
11.656 + * mapping from the map, via the <tt>Iterator.remove</tt>,
11.657 + * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
11.658 + * <tt>clear</tt> operations. It does not support the
11.659 + * <tt>add</tt> or <tt>addAll</tt> operations.
11.660 + *
11.661 + * @since 1.2
11.662 + */
11.663 + public Set<Map.Entry<K,V>> entrySet() {
11.664 + if (entrySet==null)
11.665 + entrySet = Collections.synchronizedSet(new EntrySet(), this);
11.666 + return entrySet;
11.667 + }
11.668 +
11.669 + private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
11.670 + public Iterator<Map.Entry<K,V>> iterator() {
11.671 + return getIterator(ENTRIES);
11.672 + }
11.673 +
11.674 + public boolean add(Map.Entry<K,V> o) {
11.675 + return super.add(o);
11.676 + }
11.677 +
11.678 + public boolean contains(Object o) {
11.679 + if (!(o instanceof Map.Entry))
11.680 + return false;
11.681 + Map.Entry entry = (Map.Entry)o;
11.682 + Object key = entry.getKey();
11.683 + Entry[] tab = table;
11.684 + int hash = key.hashCode();
11.685 + int index = (hash & 0x7FFFFFFF) % tab.length;
11.686 +
11.687 + for (Entry e = tab[index]; e != null; e = e.next)
11.688 + if (e.hash==hash && e.equals(entry))
11.689 + return true;
11.690 + return false;
11.691 + }
11.692 +
11.693 + public boolean remove(Object o) {
11.694 + if (!(o instanceof Map.Entry))
11.695 + return false;
11.696 + Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
11.697 + K key = entry.getKey();
11.698 + Entry[] tab = table;
11.699 + int hash = key.hashCode();
11.700 + int index = (hash & 0x7FFFFFFF) % tab.length;
11.701 +
11.702 + for (Entry<K,V> e = tab[index], prev = null; e != null;
11.703 + prev = e, e = e.next) {
11.704 + if (e.hash==hash && e.equals(entry)) {
11.705 + modCount++;
11.706 + if (prev != null)
11.707 + prev.next = e.next;
11.708 + else
11.709 + tab[index] = e.next;
11.710 +
11.711 + count--;
11.712 + e.value = null;
11.713 + return true;
11.714 + }
11.715 + }
11.716 + return false;
11.717 + }
11.718 +
11.719 + public int size() {
11.720 + return count;
11.721 + }
11.722 +
11.723 + public void clear() {
11.724 + Hashtable.this.clear();
11.725 + }
11.726 + }
11.727 +
11.728 + /**
11.729 + * Returns a {@link Collection} view of the values contained in this map.
11.730 + * The collection is backed by the map, so changes to the map are
11.731 + * reflected in the collection, and vice-versa. If the map is
11.732 + * modified while an iteration over the collection is in progress
11.733 + * (except through the iterator's own <tt>remove</tt> operation),
11.734 + * the results of the iteration are undefined. The collection
11.735 + * supports element removal, which removes the corresponding
11.736 + * mapping from the map, via the <tt>Iterator.remove</tt>,
11.737 + * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
11.738 + * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
11.739 + * support the <tt>add</tt> or <tt>addAll</tt> operations.
11.740 + *
11.741 + * @since 1.2
11.742 + */
11.743 + public Collection<V> values() {
11.744 + if (values==null)
11.745 + values = Collections.synchronizedCollection(new ValueCollection(),
11.746 + this);
11.747 + return values;
11.748 + }
11.749 +
11.750 + private class ValueCollection extends AbstractCollection<V> {
11.751 + public Iterator<V> iterator() {
11.752 + return getIterator(VALUES);
11.753 + }
11.754 + public int size() {
11.755 + return count;
11.756 + }
11.757 + public boolean contains(Object o) {
11.758 + return containsValue(o);
11.759 + }
11.760 + public void clear() {
11.761 + Hashtable.this.clear();
11.762 + }
11.763 + }
11.764 +
11.765 + // Comparison and hashing
11.766 +
11.767 + /**
11.768 + * Compares the specified Object with this Map for equality,
11.769 + * as per the definition in the Map interface.
11.770 + *
11.771 + * @param o object to be compared for equality with this hashtable
11.772 + * @return true if the specified Object is equal to this Map
11.773 + * @see Map#equals(Object)
11.774 + * @since 1.2
11.775 + */
11.776 + public synchronized boolean equals(Object o) {
11.777 + if (o == this)
11.778 + return true;
11.779 +
11.780 + if (!(o instanceof Map))
11.781 + return false;
11.782 + Map<K,V> t = (Map<K,V>) o;
11.783 + if (t.size() != size())
11.784 + return false;
11.785 +
11.786 + try {
11.787 + Iterator<Map.Entry<K,V>> i = entrySet().iterator();
11.788 + while (i.hasNext()) {
11.789 + Map.Entry<K,V> e = i.next();
11.790 + K key = e.getKey();
11.791 + V value = e.getValue();
11.792 + if (value == null) {
11.793 + if (!(t.get(key)==null && t.containsKey(key)))
11.794 + return false;
11.795 + } else {
11.796 + if (!value.equals(t.get(key)))
11.797 + return false;
11.798 + }
11.799 + }
11.800 + } catch (ClassCastException unused) {
11.801 + return false;
11.802 + } catch (NullPointerException unused) {
11.803 + return false;
11.804 + }
11.805 +
11.806 + return true;
11.807 + }
11.808 +
11.809 + /**
11.810 + * Returns the hash code value for this Map as per the definition in the
11.811 + * Map interface.
11.812 + *
11.813 + * @see Map#hashCode()
11.814 + * @since 1.2
11.815 + */
11.816 + public synchronized int hashCode() {
11.817 + /*
11.818 + * This code detects the recursion caused by computing the hash code
11.819 + * of a self-referential hash table and prevents the stack overflow
11.820 + * that would otherwise result. This allows certain 1.1-era
11.821 + * applets with self-referential hash tables to work. This code
11.822 + * abuses the loadFactor field to do double-duty as a hashCode
11.823 + * in progress flag, so as not to worsen the space performance.
11.824 + * A negative load factor indicates that hash code computation is
11.825 + * in progress.
11.826 + */
11.827 + int h = 0;
11.828 + if (count == 0 || loadFactor < 0)
11.829 + return h; // Returns zero
11.830 +
11.831 + loadFactor = -loadFactor; // Mark hashCode computation in progress
11.832 + Entry[] tab = table;
11.833 + for (int i = 0; i < tab.length; i++)
11.834 + for (Entry e = tab[i]; e != null; e = e.next)
11.835 + h += e.key.hashCode() ^ e.value.hashCode();
11.836 + loadFactor = -loadFactor; // Mark hashCode computation complete
11.837 +
11.838 + return h;
11.839 + }
11.840 +
11.841 + /**
11.842 + * Hashtable collision list.
11.843 + */
11.844 + private static class Entry<K,V> implements Map.Entry<K,V> {
11.845 + int hash;
11.846 + K key;
11.847 + V value;
11.848 + Entry<K,V> next;
11.849 +
11.850 + protected Entry(int hash, K key, V value, Entry<K,V> next) {
11.851 + this.hash = hash;
11.852 + this.key = key;
11.853 + this.value = value;
11.854 + this.next = next;
11.855 + }
11.856 +
11.857 + protected Object clone() {
11.858 + return new Entry<>(hash, key, value,
11.859 + (next==null ? null : (Entry<K,V>) next.clone()));
11.860 + }
11.861 +
11.862 + // Map.Entry Ops
11.863 +
11.864 + public K getKey() {
11.865 + return key;
11.866 + }
11.867 +
11.868 + public V getValue() {
11.869 + return value;
11.870 + }
11.871 +
11.872 + public V setValue(V value) {
11.873 + if (value == null)
11.874 + throw new NullPointerException();
11.875 +
11.876 + V oldValue = this.value;
11.877 + this.value = value;
11.878 + return oldValue;
11.879 + }
11.880 +
11.881 + public boolean equals(Object o) {
11.882 + if (!(o instanceof Map.Entry))
11.883 + return false;
11.884 + Map.Entry e = (Map.Entry)o;
11.885 +
11.886 + return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
11.887 + (value==null ? e.getValue()==null : value.equals(e.getValue()));
11.888 + }
11.889 +
11.890 + public int hashCode() {
11.891 + return hash ^ (value==null ? 0 : value.hashCode());
11.892 + }
11.893 +
11.894 + public String toString() {
11.895 + return key.toString()+"="+value.toString();
11.896 + }
11.897 + }
11.898 +
11.899 + // Types of Enumerations/Iterations
11.900 + private static final int KEYS = 0;
11.901 + private static final int VALUES = 1;
11.902 + private static final int ENTRIES = 2;
11.903 +
11.904 + /**
11.905 + * A hashtable enumerator class. This class implements both the
11.906 + * Enumeration and Iterator interfaces, but individual instances
11.907 + * can be created with the Iterator methods disabled. This is necessary
11.908 + * to avoid unintentionally increasing the capabilities granted a user
11.909 + * by passing an Enumeration.
11.910 + */
11.911 + private class Enumerator<T> implements Enumeration<T>, Iterator<T> {
11.912 + Entry[] table = Hashtable.this.table;
11.913 + int index = table.length;
11.914 + Entry<K,V> entry = null;
11.915 + Entry<K,V> lastReturned = null;
11.916 + int type;
11.917 +
11.918 + /**
11.919 + * Indicates whether this Enumerator is serving as an Iterator
11.920 + * or an Enumeration. (true -> Iterator).
11.921 + */
11.922 + boolean iterator;
11.923 +
11.924 + /**
11.925 + * The modCount value that the iterator believes that the backing
11.926 + * Hashtable should have. If this expectation is violated, the iterator
11.927 + * has detected concurrent modification.
11.928 + */
11.929 + protected int expectedModCount = modCount;
11.930 +
11.931 + Enumerator(int type, boolean iterator) {
11.932 + this.type = type;
11.933 + this.iterator = iterator;
11.934 + }
11.935 +
11.936 + public boolean hasMoreElements() {
11.937 + Entry<K,V> e = entry;
11.938 + int i = index;
11.939 + Entry[] t = table;
11.940 + /* Use locals for faster loop iteration */
11.941 + while (e == null && i > 0) {
11.942 + e = t[--i];
11.943 + }
11.944 + entry = e;
11.945 + index = i;
11.946 + return e != null;
11.947 + }
11.948 +
11.949 + public T nextElement() {
11.950 + Entry<K,V> et = entry;
11.951 + int i = index;
11.952 + Entry[] t = table;
11.953 + /* Use locals for faster loop iteration */
11.954 + while (et == null && i > 0) {
11.955 + et = t[--i];
11.956 + }
11.957 + entry = et;
11.958 + index = i;
11.959 + if (et != null) {
11.960 + Entry<K,V> e = lastReturned = entry;
11.961 + entry = e.next;
11.962 + return type == KEYS ? (T)e.key : (type == VALUES ? (T)e.value : (T)e);
11.963 + }
11.964 + throw new NoSuchElementException("Hashtable Enumerator");
11.965 + }
11.966 +
11.967 + // Iterator methods
11.968 + public boolean hasNext() {
11.969 + return hasMoreElements();
11.970 + }
11.971 +
11.972 + public T next() {
11.973 + if (modCount != expectedModCount)
11.974 + throw new ConcurrentModificationException();
11.975 + return nextElement();
11.976 + }
11.977 +
11.978 + public void remove() {
11.979 + if (!iterator)
11.980 + throw new UnsupportedOperationException();
11.981 + if (lastReturned == null)
11.982 + throw new IllegalStateException("Hashtable Enumerator");
11.983 + if (modCount != expectedModCount)
11.984 + throw new ConcurrentModificationException();
11.985 +
11.986 + synchronized(Hashtable.this) {
11.987 + Entry[] tab = Hashtable.this.table;
11.988 + int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;
11.989 +
11.990 + for (Entry<K,V> e = tab[index], prev = null; e != null;
11.991 + prev = e, e = e.next) {
11.992 + if (e == lastReturned) {
11.993 + modCount++;
11.994 + expectedModCount++;
11.995 + if (prev == null)
11.996 + tab[index] = e.next;
11.997 + else
11.998 + prev.next = e.next;
11.999 + count--;
11.1000 + lastReturned = null;
11.1001 + return;
11.1002 + }
11.1003 + }
11.1004 + throw new ConcurrentModificationException();
11.1005 + }
11.1006 + }
11.1007 + }
11.1008 +}
12.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
12.2 +++ b/emul/compact/src/main/java/java/util/LinkedList.java Mon Jan 28 18:14:00 2013 +0100
12.3 @@ -0,0 +1,1100 @@
12.4 +/*
12.5 + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
12.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
12.7 + *
12.8 + * This code is free software; you can redistribute it and/or modify it
12.9 + * under the terms of the GNU General Public License version 2 only, as
12.10 + * published by the Free Software Foundation. Oracle designates this
12.11 + * particular file as subject to the "Classpath" exception as provided
12.12 + * by Oracle in the LICENSE file that accompanied this code.
12.13 + *
12.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
12.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12.17 + * version 2 for more details (a copy is included in the LICENSE file that
12.18 + * accompanied this code).
12.19 + *
12.20 + * You should have received a copy of the GNU General Public License version
12.21 + * 2 along with this work; if not, write to the Free Software Foundation,
12.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
12.23 + *
12.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
12.25 + * or visit www.oracle.com if you need additional information or have any
12.26 + * questions.
12.27 + */
12.28 +
12.29 +package java.util;
12.30 +
12.31 +/**
12.32 + * Doubly-linked list implementation of the {@code List} and {@code Deque}
12.33 + * interfaces. Implements all optional list operations, and permits all
12.34 + * elements (including {@code null}).
12.35 + *
12.36 + * <p>All of the operations perform as could be expected for a doubly-linked
12.37 + * list. Operations that index into the list will traverse the list from
12.38 + * the beginning or the end, whichever is closer to the specified index.
12.39 + *
12.40 + * <p><strong>Note that this implementation is not synchronized.</strong>
12.41 + * If multiple threads access a linked list concurrently, and at least
12.42 + * one of the threads modifies the list structurally, it <i>must</i> be
12.43 + * synchronized externally. (A structural modification is any operation
12.44 + * that adds or deletes one or more elements; merely setting the value of
12.45 + * an element is not a structural modification.) This is typically
12.46 + * accomplished by synchronizing on some object that naturally
12.47 + * encapsulates the list.
12.48 + *
12.49 + * If no such object exists, the list should be "wrapped" using the
12.50 + * {@link Collections#synchronizedList Collections.synchronizedList}
12.51 + * method. This is best done at creation time, to prevent accidental
12.52 + * unsynchronized access to the list:<pre>
12.53 + * List list = Collections.synchronizedList(new LinkedList(...));</pre>
12.54 + *
12.55 + * <p>The iterators returned by this class's {@code iterator} and
12.56 + * {@code listIterator} methods are <i>fail-fast</i>: if the list is
12.57 + * structurally modified at any time after the iterator is created, in
12.58 + * any way except through the Iterator's own {@code remove} or
12.59 + * {@code add} methods, the iterator will throw a {@link
12.60 + * ConcurrentModificationException}. Thus, in the face of concurrent
12.61 + * modification, the iterator fails quickly and cleanly, rather than
12.62 + * risking arbitrary, non-deterministic behavior at an undetermined
12.63 + * time in the future.
12.64 + *
12.65 + * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
12.66 + * as it is, generally speaking, impossible to make any hard guarantees in the
12.67 + * presence of unsynchronized concurrent modification. Fail-fast iterators
12.68 + * throw {@code ConcurrentModificationException} on a best-effort basis.
12.69 + * Therefore, it would be wrong to write a program that depended on this
12.70 + * exception for its correctness: <i>the fail-fast behavior of iterators
12.71 + * should be used only to detect bugs.</i>
12.72 + *
12.73 + * <p>This class is a member of the
12.74 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
12.75 + * Java Collections Framework</a>.
12.76 + *
12.77 + * @author Josh Bloch
12.78 + * @see List
12.79 + * @see ArrayList
12.80 + * @since 1.2
12.81 + * @param <E> the type of elements held in this collection
12.82 + */
12.83 +
12.84 +public class LinkedList<E>
12.85 + extends AbstractSequentialList<E>
12.86 + implements List<E>, Deque<E>, Cloneable, java.io.Serializable
12.87 +{
12.88 + transient int size = 0;
12.89 +
12.90 + /**
12.91 + * Pointer to first node.
12.92 + * Invariant: (first == null && last == null) ||
12.93 + * (first.prev == null && first.item != null)
12.94 + */
12.95 + transient Node<E> first;
12.96 +
12.97 + /**
12.98 + * Pointer to last node.
12.99 + * Invariant: (first == null && last == null) ||
12.100 + * (last.next == null && last.item != null)
12.101 + */
12.102 + transient Node<E> last;
12.103 +
12.104 + /**
12.105 + * Constructs an empty list.
12.106 + */
12.107 + public LinkedList() {
12.108 + }
12.109 +
12.110 + /**
12.111 + * Constructs a list containing the elements of the specified
12.112 + * collection, in the order they are returned by the collection's
12.113 + * iterator.
12.114 + *
12.115 + * @param c the collection whose elements are to be placed into this list
12.116 + * @throws NullPointerException if the specified collection is null
12.117 + */
12.118 + public LinkedList(Collection<? extends E> c) {
12.119 + this();
12.120 + addAll(c);
12.121 + }
12.122 +
12.123 + /**
12.124 + * Links e as first element.
12.125 + */
12.126 + private void linkFirst(E e) {
12.127 + final Node<E> f = first;
12.128 + final Node<E> newNode = new Node<>(null, e, f);
12.129 + first = newNode;
12.130 + if (f == null)
12.131 + last = newNode;
12.132 + else
12.133 + f.prev = newNode;
12.134 + size++;
12.135 + modCount++;
12.136 + }
12.137 +
12.138 + /**
12.139 + * Links e as last element.
12.140 + */
12.141 + void linkLast(E e) {
12.142 + final Node<E> l = last;
12.143 + final Node<E> newNode = new Node<>(l, e, null);
12.144 + last = newNode;
12.145 + if (l == null)
12.146 + first = newNode;
12.147 + else
12.148 + l.next = newNode;
12.149 + size++;
12.150 + modCount++;
12.151 + }
12.152 +
12.153 + /**
12.154 + * Inserts element e before non-null Node succ.
12.155 + */
12.156 + void linkBefore(E e, Node<E> succ) {
12.157 + // assert succ != null;
12.158 + final Node<E> pred = succ.prev;
12.159 + final Node<E> newNode = new Node<>(pred, e, succ);
12.160 + succ.prev = newNode;
12.161 + if (pred == null)
12.162 + first = newNode;
12.163 + else
12.164 + pred.next = newNode;
12.165 + size++;
12.166 + modCount++;
12.167 + }
12.168 +
12.169 + /**
12.170 + * Unlinks non-null first node f.
12.171 + */
12.172 + private E unlinkFirst(Node<E> f) {
12.173 + // assert f == first && f != null;
12.174 + final E element = f.item;
12.175 + final Node<E> next = f.next;
12.176 + f.item = null;
12.177 + f.next = null; // help GC
12.178 + first = next;
12.179 + if (next == null)
12.180 + last = null;
12.181 + else
12.182 + next.prev = null;
12.183 + size--;
12.184 + modCount++;
12.185 + return element;
12.186 + }
12.187 +
12.188 + /**
12.189 + * Unlinks non-null last node l.
12.190 + */
12.191 + private E unlinkLast(Node<E> l) {
12.192 + // assert l == last && l != null;
12.193 + final E element = l.item;
12.194 + final Node<E> prev = l.prev;
12.195 + l.item = null;
12.196 + l.prev = null; // help GC
12.197 + last = prev;
12.198 + if (prev == null)
12.199 + first = null;
12.200 + else
12.201 + prev.next = null;
12.202 + size--;
12.203 + modCount++;
12.204 + return element;
12.205 + }
12.206 +
12.207 + /**
12.208 + * Unlinks non-null node x.
12.209 + */
12.210 + E unlink(Node<E> x) {
12.211 + // assert x != null;
12.212 + final E element = x.item;
12.213 + final Node<E> next = x.next;
12.214 + final Node<E> prev = x.prev;
12.215 +
12.216 + if (prev == null) {
12.217 + first = next;
12.218 + } else {
12.219 + prev.next = next;
12.220 + x.prev = null;
12.221 + }
12.222 +
12.223 + if (next == null) {
12.224 + last = prev;
12.225 + } else {
12.226 + next.prev = prev;
12.227 + x.next = null;
12.228 + }
12.229 +
12.230 + x.item = null;
12.231 + size--;
12.232 + modCount++;
12.233 + return element;
12.234 + }
12.235 +
12.236 + /**
12.237 + * Returns the first element in this list.
12.238 + *
12.239 + * @return the first element in this list
12.240 + * @throws NoSuchElementException if this list is empty
12.241 + */
12.242 + public E getFirst() {
12.243 + final Node<E> f = first;
12.244 + if (f == null)
12.245 + throw new NoSuchElementException();
12.246 + return f.item;
12.247 + }
12.248 +
12.249 + /**
12.250 + * Returns the last element in this list.
12.251 + *
12.252 + * @return the last element in this list
12.253 + * @throws NoSuchElementException if this list is empty
12.254 + */
12.255 + public E getLast() {
12.256 + final Node<E> l = last;
12.257 + if (l == null)
12.258 + throw new NoSuchElementException();
12.259 + return l.item;
12.260 + }
12.261 +
12.262 + /**
12.263 + * Removes and returns the first element from this list.
12.264 + *
12.265 + * @return the first element from this list
12.266 + * @throws NoSuchElementException if this list is empty
12.267 + */
12.268 + public E removeFirst() {
12.269 + final Node<E> f = first;
12.270 + if (f == null)
12.271 + throw new NoSuchElementException();
12.272 + return unlinkFirst(f);
12.273 + }
12.274 +
12.275 + /**
12.276 + * Removes and returns the last element from this list.
12.277 + *
12.278 + * @return the last element from this list
12.279 + * @throws NoSuchElementException if this list is empty
12.280 + */
12.281 + public E removeLast() {
12.282 + final Node<E> l = last;
12.283 + if (l == null)
12.284 + throw new NoSuchElementException();
12.285 + return unlinkLast(l);
12.286 + }
12.287 +
12.288 + /**
12.289 + * Inserts the specified element at the beginning of this list.
12.290 + *
12.291 + * @param e the element to add
12.292 + */
12.293 + public void addFirst(E e) {
12.294 + linkFirst(e);
12.295 + }
12.296 +
12.297 + /**
12.298 + * Appends the specified element to the end of this list.
12.299 + *
12.300 + * <p>This method is equivalent to {@link #add}.
12.301 + *
12.302 + * @param e the element to add
12.303 + */
12.304 + public void addLast(E e) {
12.305 + linkLast(e);
12.306 + }
12.307 +
12.308 + /**
12.309 + * Returns {@code true} if this list contains the specified element.
12.310 + * More formally, returns {@code true} if and only if this list contains
12.311 + * at least one element {@code e} such that
12.312 + * <tt>(o==null ? e==null : o.equals(e))</tt>.
12.313 + *
12.314 + * @param o element whose presence in this list is to be tested
12.315 + * @return {@code true} if this list contains the specified element
12.316 + */
12.317 + public boolean contains(Object o) {
12.318 + return indexOf(o) != -1;
12.319 + }
12.320 +
12.321 + /**
12.322 + * Returns the number of elements in this list.
12.323 + *
12.324 + * @return the number of elements in this list
12.325 + */
12.326 + public int size() {
12.327 + return size;
12.328 + }
12.329 +
12.330 + /**
12.331 + * Appends the specified element to the end of this list.
12.332 + *
12.333 + * <p>This method is equivalent to {@link #addLast}.
12.334 + *
12.335 + * @param e element to be appended to this list
12.336 + * @return {@code true} (as specified by {@link Collection#add})
12.337 + */
12.338 + public boolean add(E e) {
12.339 + linkLast(e);
12.340 + return true;
12.341 + }
12.342 +
12.343 + /**
12.344 + * Removes the first occurrence of the specified element from this list,
12.345 + * if it is present. If this list does not contain the element, it is
12.346 + * unchanged. More formally, removes the element with the lowest index
12.347 + * {@code i} such that
12.348 + * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
12.349 + * (if such an element exists). Returns {@code true} if this list
12.350 + * contained the specified element (or equivalently, if this list
12.351 + * changed as a result of the call).
12.352 + *
12.353 + * @param o element to be removed from this list, if present
12.354 + * @return {@code true} if this list contained the specified element
12.355 + */
12.356 + public boolean remove(Object o) {
12.357 + if (o == null) {
12.358 + for (Node<E> x = first; x != null; x = x.next) {
12.359 + if (x.item == null) {
12.360 + unlink(x);
12.361 + return true;
12.362 + }
12.363 + }
12.364 + } else {
12.365 + for (Node<E> x = first; x != null; x = x.next) {
12.366 + if (o.equals(x.item)) {
12.367 + unlink(x);
12.368 + return true;
12.369 + }
12.370 + }
12.371 + }
12.372 + return false;
12.373 + }
12.374 +
12.375 + /**
12.376 + * Appends all of the elements in the specified collection to the end of
12.377 + * this list, in the order that they are returned by the specified
12.378 + * collection's iterator. The behavior of this operation is undefined if
12.379 + * the specified collection is modified while the operation is in
12.380 + * progress. (Note that this will occur if the specified collection is
12.381 + * this list, and it's nonempty.)
12.382 + *
12.383 + * @param c collection containing elements to be added to this list
12.384 + * @return {@code true} if this list changed as a result of the call
12.385 + * @throws NullPointerException if the specified collection is null
12.386 + */
12.387 + public boolean addAll(Collection<? extends E> c) {
12.388 + return addAll(size, c);
12.389 + }
12.390 +
12.391 + /**
12.392 + * Inserts all of the elements in the specified collection into this
12.393 + * list, starting at the specified position. Shifts the element
12.394 + * currently at that position (if any) and any subsequent elements to
12.395 + * the right (increases their indices). The new elements will appear
12.396 + * in the list in the order that they are returned by the
12.397 + * specified collection's iterator.
12.398 + *
12.399 + * @param index index at which to insert the first element
12.400 + * from the specified collection
12.401 + * @param c collection containing elements to be added to this list
12.402 + * @return {@code true} if this list changed as a result of the call
12.403 + * @throws IndexOutOfBoundsException {@inheritDoc}
12.404 + * @throws NullPointerException if the specified collection is null
12.405 + */
12.406 + public boolean addAll(int index, Collection<? extends E> c) {
12.407 + checkPositionIndex(index);
12.408 +
12.409 + Object[] a = c.toArray();
12.410 + int numNew = a.length;
12.411 + if (numNew == 0)
12.412 + return false;
12.413 +
12.414 + Node<E> pred, succ;
12.415 + if (index == size) {
12.416 + succ = null;
12.417 + pred = last;
12.418 + } else {
12.419 + succ = node(index);
12.420 + pred = succ.prev;
12.421 + }
12.422 +
12.423 + for (Object o : a) {
12.424 + @SuppressWarnings("unchecked") E e = (E) o;
12.425 + Node<E> newNode = new Node<>(pred, e, null);
12.426 + if (pred == null)
12.427 + first = newNode;
12.428 + else
12.429 + pred.next = newNode;
12.430 + pred = newNode;
12.431 + }
12.432 +
12.433 + if (succ == null) {
12.434 + last = pred;
12.435 + } else {
12.436 + pred.next = succ;
12.437 + succ.prev = pred;
12.438 + }
12.439 +
12.440 + size += numNew;
12.441 + modCount++;
12.442 + return true;
12.443 + }
12.444 +
12.445 + /**
12.446 + * Removes all of the elements from this list.
12.447 + * The list will be empty after this call returns.
12.448 + */
12.449 + public void clear() {
12.450 + // Clearing all of the links between nodes is "unnecessary", but:
12.451 + // - helps a generational GC if the discarded nodes inhabit
12.452 + // more than one generation
12.453 + // - is sure to free memory even if there is a reachable Iterator
12.454 + for (Node<E> x = first; x != null; ) {
12.455 + Node<E> next = x.next;
12.456 + x.item = null;
12.457 + x.next = null;
12.458 + x.prev = null;
12.459 + x = next;
12.460 + }
12.461 + first = last = null;
12.462 + size = 0;
12.463 + modCount++;
12.464 + }
12.465 +
12.466 +
12.467 + // Positional Access Operations
12.468 +
12.469 + /**
12.470 + * Returns the element at the specified position in this list.
12.471 + *
12.472 + * @param index index of the element to return
12.473 + * @return the element at the specified position in this list
12.474 + * @throws IndexOutOfBoundsException {@inheritDoc}
12.475 + */
12.476 + public E get(int index) {
12.477 + checkElementIndex(index);
12.478 + return node(index).item;
12.479 + }
12.480 +
12.481 + /**
12.482 + * Replaces the element at the specified position in this list with the
12.483 + * specified element.
12.484 + *
12.485 + * @param index index of the element to replace
12.486 + * @param element element to be stored at the specified position
12.487 + * @return the element previously at the specified position
12.488 + * @throws IndexOutOfBoundsException {@inheritDoc}
12.489 + */
12.490 + public E set(int index, E element) {
12.491 + checkElementIndex(index);
12.492 + Node<E> x = node(index);
12.493 + E oldVal = x.item;
12.494 + x.item = element;
12.495 + return oldVal;
12.496 + }
12.497 +
12.498 + /**
12.499 + * Inserts the specified element at the specified position in this list.
12.500 + * Shifts the element currently at that position (if any) and any
12.501 + * subsequent elements to the right (adds one to their indices).
12.502 + *
12.503 + * @param index index at which the specified element is to be inserted
12.504 + * @param element element to be inserted
12.505 + * @throws IndexOutOfBoundsException {@inheritDoc}
12.506 + */
12.507 + public void add(int index, E element) {
12.508 + checkPositionIndex(index);
12.509 +
12.510 + if (index == size)
12.511 + linkLast(element);
12.512 + else
12.513 + linkBefore(element, node(index));
12.514 + }
12.515 +
12.516 + /**
12.517 + * Removes the element at the specified position in this list. Shifts any
12.518 + * subsequent elements to the left (subtracts one from their indices).
12.519 + * Returns the element that was removed from the list.
12.520 + *
12.521 + * @param index the index of the element to be removed
12.522 + * @return the element previously at the specified position
12.523 + * @throws IndexOutOfBoundsException {@inheritDoc}
12.524 + */
12.525 + public E remove(int index) {
12.526 + checkElementIndex(index);
12.527 + return unlink(node(index));
12.528 + }
12.529 +
12.530 + /**
12.531 + * Tells if the argument is the index of an existing element.
12.532 + */
12.533 + private boolean isElementIndex(int index) {
12.534 + return index >= 0 && index < size;
12.535 + }
12.536 +
12.537 + /**
12.538 + * Tells if the argument is the index of a valid position for an
12.539 + * iterator or an add operation.
12.540 + */
12.541 + private boolean isPositionIndex(int index) {
12.542 + return index >= 0 && index <= size;
12.543 + }
12.544 +
12.545 + /**
12.546 + * Constructs an IndexOutOfBoundsException detail message.
12.547 + * Of the many possible refactorings of the error handling code,
12.548 + * this "outlining" performs best with both server and client VMs.
12.549 + */
12.550 + private String outOfBoundsMsg(int index) {
12.551 + return "Index: "+index+", Size: "+size;
12.552 + }
12.553 +
12.554 + private void checkElementIndex(int index) {
12.555 + if (!isElementIndex(index))
12.556 + throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
12.557 + }
12.558 +
12.559 + private void checkPositionIndex(int index) {
12.560 + if (!isPositionIndex(index))
12.561 + throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
12.562 + }
12.563 +
12.564 + /**
12.565 + * Returns the (non-null) Node at the specified element index.
12.566 + */
12.567 + Node<E> node(int index) {
12.568 + // assert isElementIndex(index);
12.569 +
12.570 + if (index < (size >> 1)) {
12.571 + Node<E> x = first;
12.572 + for (int i = 0; i < index; i++)
12.573 + x = x.next;
12.574 + return x;
12.575 + } else {
12.576 + Node<E> x = last;
12.577 + for (int i = size - 1; i > index; i--)
12.578 + x = x.prev;
12.579 + return x;
12.580 + }
12.581 + }
12.582 +
12.583 + // Search Operations
12.584 +
12.585 + /**
12.586 + * Returns the index of the first occurrence of the specified element
12.587 + * in this list, or -1 if this list does not contain the element.
12.588 + * More formally, returns the lowest index {@code i} such that
12.589 + * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
12.590 + * or -1 if there is no such index.
12.591 + *
12.592 + * @param o element to search for
12.593 + * @return the index of the first occurrence of the specified element in
12.594 + * this list, or -1 if this list does not contain the element
12.595 + */
12.596 + public int indexOf(Object o) {
12.597 + int index = 0;
12.598 + if (o == null) {
12.599 + for (Node<E> x = first; x != null; x = x.next) {
12.600 + if (x.item == null)
12.601 + return index;
12.602 + index++;
12.603 + }
12.604 + } else {
12.605 + for (Node<E> x = first; x != null; x = x.next) {
12.606 + if (o.equals(x.item))
12.607 + return index;
12.608 + index++;
12.609 + }
12.610 + }
12.611 + return -1;
12.612 + }
12.613 +
12.614 + /**
12.615 + * Returns the index of the last occurrence of the specified element
12.616 + * in this list, or -1 if this list does not contain the element.
12.617 + * More formally, returns the highest index {@code i} such that
12.618 + * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
12.619 + * or -1 if there is no such index.
12.620 + *
12.621 + * @param o element to search for
12.622 + * @return the index of the last occurrence of the specified element in
12.623 + * this list, or -1 if this list does not contain the element
12.624 + */
12.625 + public int lastIndexOf(Object o) {
12.626 + int index = size;
12.627 + if (o == null) {
12.628 + for (Node<E> x = last; x != null; x = x.prev) {
12.629 + index--;
12.630 + if (x.item == null)
12.631 + return index;
12.632 + }
12.633 + } else {
12.634 + for (Node<E> x = last; x != null; x = x.prev) {
12.635 + index--;
12.636 + if (o.equals(x.item))
12.637 + return index;
12.638 + }
12.639 + }
12.640 + return -1;
12.641 + }
12.642 +
12.643 + // Queue operations.
12.644 +
12.645 + /**
12.646 + * Retrieves, but does not remove, the head (first element) of this list.
12.647 + *
12.648 + * @return the head of this list, or {@code null} if this list is empty
12.649 + * @since 1.5
12.650 + */
12.651 + public E peek() {
12.652 + final Node<E> f = first;
12.653 + return (f == null) ? null : f.item;
12.654 + }
12.655 +
12.656 + /**
12.657 + * Retrieves, but does not remove, the head (first element) of this list.
12.658 + *
12.659 + * @return the head of this list
12.660 + * @throws NoSuchElementException if this list is empty
12.661 + * @since 1.5
12.662 + */
12.663 + public E element() {
12.664 + return getFirst();
12.665 + }
12.666 +
12.667 + /**
12.668 + * Retrieves and removes the head (first element) of this list.
12.669 + *
12.670 + * @return the head of this list, or {@code null} if this list is empty
12.671 + * @since 1.5
12.672 + */
12.673 + public E poll() {
12.674 + final Node<E> f = first;
12.675 + return (f == null) ? null : unlinkFirst(f);
12.676 + }
12.677 +
12.678 + /**
12.679 + * Retrieves and removes the head (first element) of this list.
12.680 + *
12.681 + * @return the head of this list
12.682 + * @throws NoSuchElementException if this list is empty
12.683 + * @since 1.5
12.684 + */
12.685 + public E remove() {
12.686 + return removeFirst();
12.687 + }
12.688 +
12.689 + /**
12.690 + * Adds the specified element as the tail (last element) of this list.
12.691 + *
12.692 + * @param e the element to add
12.693 + * @return {@code true} (as specified by {@link Queue#offer})
12.694 + * @since 1.5
12.695 + */
12.696 + public boolean offer(E e) {
12.697 + return add(e);
12.698 + }
12.699 +
12.700 + // Deque operations
12.701 + /**
12.702 + * Inserts the specified element at the front of this list.
12.703 + *
12.704 + * @param e the element to insert
12.705 + * @return {@code true} (as specified by {@link Deque#offerFirst})
12.706 + * @since 1.6
12.707 + */
12.708 + public boolean offerFirst(E e) {
12.709 + addFirst(e);
12.710 + return true;
12.711 + }
12.712 +
12.713 + /**
12.714 + * Inserts the specified element at the end of this list.
12.715 + *
12.716 + * @param e the element to insert
12.717 + * @return {@code true} (as specified by {@link Deque#offerLast})
12.718 + * @since 1.6
12.719 + */
12.720 + public boolean offerLast(E e) {
12.721 + addLast(e);
12.722 + return true;
12.723 + }
12.724 +
12.725 + /**
12.726 + * Retrieves, but does not remove, the first element of this list,
12.727 + * or returns {@code null} if this list is empty.
12.728 + *
12.729 + * @return the first element of this list, or {@code null}
12.730 + * if this list is empty
12.731 + * @since 1.6
12.732 + */
12.733 + public E peekFirst() {
12.734 + final Node<E> f = first;
12.735 + return (f == null) ? null : f.item;
12.736 + }
12.737 +
12.738 + /**
12.739 + * Retrieves, but does not remove, the last element of this list,
12.740 + * or returns {@code null} if this list is empty.
12.741 + *
12.742 + * @return the last element of this list, or {@code null}
12.743 + * if this list is empty
12.744 + * @since 1.6
12.745 + */
12.746 + public E peekLast() {
12.747 + final Node<E> l = last;
12.748 + return (l == null) ? null : l.item;
12.749 + }
12.750 +
12.751 + /**
12.752 + * Retrieves and removes the first element of this list,
12.753 + * or returns {@code null} if this list is empty.
12.754 + *
12.755 + * @return the first element of this list, or {@code null} if
12.756 + * this list is empty
12.757 + * @since 1.6
12.758 + */
12.759 + public E pollFirst() {
12.760 + final Node<E> f = first;
12.761 + return (f == null) ? null : unlinkFirst(f);
12.762 + }
12.763 +
12.764 + /**
12.765 + * Retrieves and removes the last element of this list,
12.766 + * or returns {@code null} if this list is empty.
12.767 + *
12.768 + * @return the last element of this list, or {@code null} if
12.769 + * this list is empty
12.770 + * @since 1.6
12.771 + */
12.772 + public E pollLast() {
12.773 + final Node<E> l = last;
12.774 + return (l == null) ? null : unlinkLast(l);
12.775 + }
12.776 +
12.777 + /**
12.778 + * Pushes an element onto the stack represented by this list. In other
12.779 + * words, inserts the element at the front of this list.
12.780 + *
12.781 + * <p>This method is equivalent to {@link #addFirst}.
12.782 + *
12.783 + * @param e the element to push
12.784 + * @since 1.6
12.785 + */
12.786 + public void push(E e) {
12.787 + addFirst(e);
12.788 + }
12.789 +
12.790 + /**
12.791 + * Pops an element from the stack represented by this list. In other
12.792 + * words, removes and returns the first element of this list.
12.793 + *
12.794 + * <p>This method is equivalent to {@link #removeFirst()}.
12.795 + *
12.796 + * @return the element at the front of this list (which is the top
12.797 + * of the stack represented by this list)
12.798 + * @throws NoSuchElementException if this list is empty
12.799 + * @since 1.6
12.800 + */
12.801 + public E pop() {
12.802 + return removeFirst();
12.803 + }
12.804 +
12.805 + /**
12.806 + * Removes the first occurrence of the specified element in this
12.807 + * list (when traversing the list from head to tail). If the list
12.808 + * does not contain the element, it is unchanged.
12.809 + *
12.810 + * @param o element to be removed from this list, if present
12.811 + * @return {@code true} if the list contained the specified element
12.812 + * @since 1.6
12.813 + */
12.814 + public boolean removeFirstOccurrence(Object o) {
12.815 + return remove(o);
12.816 + }
12.817 +
12.818 + /**
12.819 + * Removes the last occurrence of the specified element in this
12.820 + * list (when traversing the list from head to tail). If the list
12.821 + * does not contain the element, it is unchanged.
12.822 + *
12.823 + * @param o element to be removed from this list, if present
12.824 + * @return {@code true} if the list contained the specified element
12.825 + * @since 1.6
12.826 + */
12.827 + public boolean removeLastOccurrence(Object o) {
12.828 + if (o == null) {
12.829 + for (Node<E> x = last; x != null; x = x.prev) {
12.830 + if (x.item == null) {
12.831 + unlink(x);
12.832 + return true;
12.833 + }
12.834 + }
12.835 + } else {
12.836 + for (Node<E> x = last; x != null; x = x.prev) {
12.837 + if (o.equals(x.item)) {
12.838 + unlink(x);
12.839 + return true;
12.840 + }
12.841 + }
12.842 + }
12.843 + return false;
12.844 + }
12.845 +
12.846 + /**
12.847 + * Returns a list-iterator of the elements in this list (in proper
12.848 + * sequence), starting at the specified position in the list.
12.849 + * Obeys the general contract of {@code List.listIterator(int)}.<p>
12.850 + *
12.851 + * The list-iterator is <i>fail-fast</i>: if the list is structurally
12.852 + * modified at any time after the Iterator is created, in any way except
12.853 + * through the list-iterator's own {@code remove} or {@code add}
12.854 + * methods, the list-iterator will throw a
12.855 + * {@code ConcurrentModificationException}. Thus, in the face of
12.856 + * concurrent modification, the iterator fails quickly and cleanly, rather
12.857 + * than risking arbitrary, non-deterministic behavior at an undetermined
12.858 + * time in the future.
12.859 + *
12.860 + * @param index index of the first element to be returned from the
12.861 + * list-iterator (by a call to {@code next})
12.862 + * @return a ListIterator of the elements in this list (in proper
12.863 + * sequence), starting at the specified position in the list
12.864 + * @throws IndexOutOfBoundsException {@inheritDoc}
12.865 + * @see List#listIterator(int)
12.866 + */
12.867 + public ListIterator<E> listIterator(int index) {
12.868 + checkPositionIndex(index);
12.869 + return new ListItr(index);
12.870 + }
12.871 +
12.872 + private class ListItr implements ListIterator<E> {
12.873 + private Node<E> lastReturned = null;
12.874 + private Node<E> next;
12.875 + private int nextIndex;
12.876 + private int expectedModCount = modCount;
12.877 +
12.878 + ListItr(int index) {
12.879 + // assert isPositionIndex(index);
12.880 + next = (index == size) ? null : node(index);
12.881 + nextIndex = index;
12.882 + }
12.883 +
12.884 + public boolean hasNext() {
12.885 + return nextIndex < size;
12.886 + }
12.887 +
12.888 + public E next() {
12.889 + checkForComodification();
12.890 + if (!hasNext())
12.891 + throw new NoSuchElementException();
12.892 +
12.893 + lastReturned = next;
12.894 + next = next.next;
12.895 + nextIndex++;
12.896 + return lastReturned.item;
12.897 + }
12.898 +
12.899 + public boolean hasPrevious() {
12.900 + return nextIndex > 0;
12.901 + }
12.902 +
12.903 + public E previous() {
12.904 + checkForComodification();
12.905 + if (!hasPrevious())
12.906 + throw new NoSuchElementException();
12.907 +
12.908 + lastReturned = next = (next == null) ? last : next.prev;
12.909 + nextIndex--;
12.910 + return lastReturned.item;
12.911 + }
12.912 +
12.913 + public int nextIndex() {
12.914 + return nextIndex;
12.915 + }
12.916 +
12.917 + public int previousIndex() {
12.918 + return nextIndex - 1;
12.919 + }
12.920 +
12.921 + public void remove() {
12.922 + checkForComodification();
12.923 + if (lastReturned == null)
12.924 + throw new IllegalStateException();
12.925 +
12.926 + Node<E> lastNext = lastReturned.next;
12.927 + unlink(lastReturned);
12.928 + if (next == lastReturned)
12.929 + next = lastNext;
12.930 + else
12.931 + nextIndex--;
12.932 + lastReturned = null;
12.933 + expectedModCount++;
12.934 + }
12.935 +
12.936 + public void set(E e) {
12.937 + if (lastReturned == null)
12.938 + throw new IllegalStateException();
12.939 + checkForComodification();
12.940 + lastReturned.item = e;
12.941 + }
12.942 +
12.943 + public void add(E e) {
12.944 + checkForComodification();
12.945 + lastReturned = null;
12.946 + if (next == null)
12.947 + linkLast(e);
12.948 + else
12.949 + linkBefore(e, next);
12.950 + nextIndex++;
12.951 + expectedModCount++;
12.952 + }
12.953 +
12.954 + final void checkForComodification() {
12.955 + if (modCount != expectedModCount)
12.956 + throw new ConcurrentModificationException();
12.957 + }
12.958 + }
12.959 +
12.960 + private static class Node<E> {
12.961 + E item;
12.962 + Node<E> next;
12.963 + Node<E> prev;
12.964 +
12.965 + Node(Node<E> prev, E element, Node<E> next) {
12.966 + this.item = element;
12.967 + this.next = next;
12.968 + this.prev = prev;
12.969 + }
12.970 + }
12.971 +
12.972 + /**
12.973 + * @since 1.6
12.974 + */
12.975 + public Iterator<E> descendingIterator() {
12.976 + return new DescendingIterator();
12.977 + }
12.978 +
12.979 + /**
12.980 + * Adapter to provide descending iterators via ListItr.previous
12.981 + */
12.982 + private class DescendingIterator implements Iterator<E> {
12.983 + private final ListItr itr = new ListItr(size());
12.984 + public boolean hasNext() {
12.985 + return itr.hasPrevious();
12.986 + }
12.987 + public E next() {
12.988 + return itr.previous();
12.989 + }
12.990 + public void remove() {
12.991 + itr.remove();
12.992 + }
12.993 + }
12.994 +
12.995 + @SuppressWarnings("unchecked")
12.996 + private LinkedList<E> superClone() {
12.997 + try {
12.998 + return (LinkedList<E>) super.clone();
12.999 + } catch (CloneNotSupportedException e) {
12.1000 + throw new InternalError();
12.1001 + }
12.1002 + }
12.1003 +
12.1004 + /**
12.1005 + * Returns a shallow copy of this {@code LinkedList}. (The elements
12.1006 + * themselves are not cloned.)
12.1007 + *
12.1008 + * @return a shallow copy of this {@code LinkedList} instance
12.1009 + */
12.1010 + public Object clone() {
12.1011 + LinkedList<E> clone = superClone();
12.1012 +
12.1013 + // Put clone into "virgin" state
12.1014 + clone.first = clone.last = null;
12.1015 + clone.size = 0;
12.1016 + clone.modCount = 0;
12.1017 +
12.1018 + // Initialize clone with our elements
12.1019 + for (Node<E> x = first; x != null; x = x.next)
12.1020 + clone.add(x.item);
12.1021 +
12.1022 + return clone;
12.1023 + }
12.1024 +
12.1025 + /**
12.1026 + * Returns an array containing all of the elements in this list
12.1027 + * in proper sequence (from first to last element).
12.1028 + *
12.1029 + * <p>The returned array will be "safe" in that no references to it are
12.1030 + * maintained by this list. (In other words, this method must allocate
12.1031 + * a new array). The caller is thus free to modify the returned array.
12.1032 + *
12.1033 + * <p>This method acts as bridge between array-based and collection-based
12.1034 + * APIs.
12.1035 + *
12.1036 + * @return an array containing all of the elements in this list
12.1037 + * in proper sequence
12.1038 + */
12.1039 + public Object[] toArray() {
12.1040 + Object[] result = new Object[size];
12.1041 + int i = 0;
12.1042 + for (Node<E> x = first; x != null; x = x.next)
12.1043 + result[i++] = x.item;
12.1044 + return result;
12.1045 + }
12.1046 +
12.1047 + /**
12.1048 + * Returns an array containing all of the elements in this list in
12.1049 + * proper sequence (from first to last element); the runtime type of
12.1050 + * the returned array is that of the specified array. If the list fits
12.1051 + * in the specified array, it is returned therein. Otherwise, a new
12.1052 + * array is allocated with the runtime type of the specified array and
12.1053 + * the size of this list.
12.1054 + *
12.1055 + * <p>If the list fits in the specified array with room to spare (i.e.,
12.1056 + * the array has more elements than the list), the element in the array
12.1057 + * immediately following the end of the list is set to {@code null}.
12.1058 + * (This is useful in determining the length of the list <i>only</i> if
12.1059 + * the caller knows that the list does not contain any null elements.)
12.1060 + *
12.1061 + * <p>Like the {@link #toArray()} method, this method acts as bridge between
12.1062 + * array-based and collection-based APIs. Further, this method allows
12.1063 + * precise control over the runtime type of the output array, and may,
12.1064 + * under certain circumstances, be used to save allocation costs.
12.1065 + *
12.1066 + * <p>Suppose {@code x} is a list known to contain only strings.
12.1067 + * The following code can be used to dump the list into a newly
12.1068 + * allocated array of {@code String}:
12.1069 + *
12.1070 + * <pre>
12.1071 + * String[] y = x.toArray(new String[0]);</pre>
12.1072 + *
12.1073 + * Note that {@code toArray(new Object[0])} is identical in function to
12.1074 + * {@code toArray()}.
12.1075 + *
12.1076 + * @param a the array into which the elements of the list are to
12.1077 + * be stored, if it is big enough; otherwise, a new array of the
12.1078 + * same runtime type is allocated for this purpose.
12.1079 + * @return an array containing the elements of the list
12.1080 + * @throws ArrayStoreException if the runtime type of the specified array
12.1081 + * is not a supertype of the runtime type of every element in
12.1082 + * this list
12.1083 + * @throws NullPointerException if the specified array is null
12.1084 + */
12.1085 + @SuppressWarnings("unchecked")
12.1086 + public <T> T[] toArray(T[] a) {
12.1087 + if (a.length < size)
12.1088 + a = (T[])java.lang.reflect.Array.newInstance(
12.1089 + a.getClass().getComponentType(), size);
12.1090 + int i = 0;
12.1091 + Object[] result = a;
12.1092 + for (Node<E> x = first; x != null; x = x.next)
12.1093 + result[i++] = x.item;
12.1094 +
12.1095 + if (a.length > size)
12.1096 + a[size] = null;
12.1097 +
12.1098 + return a;
12.1099 + }
12.1100 +
12.1101 + private static final long serialVersionUID = 876323262645176354L;
12.1102 +
12.1103 +}
13.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
13.2 +++ b/emul/compact/src/main/java/java/util/Queue.java Mon Jan 28 18:14:00 2013 +0100
13.3 @@ -0,0 +1,218 @@
13.4 +/*
13.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
13.6 + *
13.7 + * This code is free software; you can redistribute it and/or modify it
13.8 + * under the terms of the GNU General Public License version 2 only, as
13.9 + * published by the Free Software Foundation. Oracle designates this
13.10 + * particular file as subject to the "Classpath" exception as provided
13.11 + * by Oracle in the LICENSE file that accompanied this code.
13.12 + *
13.13 + * This code is distributed in the hope that it will be useful, but WITHOUT
13.14 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13.15 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13.16 + * version 2 for more details (a copy is included in the LICENSE file that
13.17 + * accompanied this code).
13.18 + *
13.19 + * You should have received a copy of the GNU General Public License version
13.20 + * 2 along with this work; if not, write to the Free Software Foundation,
13.21 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
13.22 + *
13.23 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
13.24 + * or visit www.oracle.com if you need additional information or have any
13.25 + * questions.
13.26 + */
13.27 +
13.28 +/*
13.29 + * This file is available under and governed by the GNU General Public
13.30 + * License version 2 only, as published by the Free Software Foundation.
13.31 + * However, the following notice accompanied the original version of this
13.32 + * file:
13.33 + *
13.34 + * Written by Doug Lea with assistance from members of JCP JSR-166
13.35 + * Expert Group and released to the public domain, as explained at
13.36 + * http://creativecommons.org/publicdomain/zero/1.0/
13.37 + */
13.38 +
13.39 +package java.util;
13.40 +
13.41 +/**
13.42 + * A collection designed for holding elements prior to processing.
13.43 + * Besides basic {@link java.util.Collection Collection} operations,
13.44 + * queues provide additional insertion, extraction, and inspection
13.45 + * operations. Each of these methods exists in two forms: one throws
13.46 + * an exception if the operation fails, the other returns a special
13.47 + * value (either <tt>null</tt> or <tt>false</tt>, depending on the
13.48 + * operation). The latter form of the insert operation is designed
13.49 + * specifically for use with capacity-restricted <tt>Queue</tt>
13.50 + * implementations; in most implementations, insert operations cannot
13.51 + * fail.
13.52 + *
13.53 + * <p>
13.54 + * <table BORDER CELLPADDING=3 CELLSPACING=1>
13.55 + * <tr>
13.56 + * <td></td>
13.57 + * <td ALIGN=CENTER><em>Throws exception</em></td>
13.58 + * <td ALIGN=CENTER><em>Returns special value</em></td>
13.59 + * </tr>
13.60 + * <tr>
13.61 + * <td><b>Insert</b></td>
13.62 + * <td>{@link #add add(e)}</td>
13.63 + * <td>{@link #offer offer(e)}</td>
13.64 + * </tr>
13.65 + * <tr>
13.66 + * <td><b>Remove</b></td>
13.67 + * <td>{@link #remove remove()}</td>
13.68 + * <td>{@link #poll poll()}</td>
13.69 + * </tr>
13.70 + * <tr>
13.71 + * <td><b>Examine</b></td>
13.72 + * <td>{@link #element element()}</td>
13.73 + * <td>{@link #peek peek()}</td>
13.74 + * </tr>
13.75 + * </table>
13.76 + *
13.77 + * <p>Queues typically, but do not necessarily, order elements in a
13.78 + * FIFO (first-in-first-out) manner. Among the exceptions are
13.79 + * priority queues, which order elements according to a supplied
13.80 + * comparator, or the elements' natural ordering, and LIFO queues (or
13.81 + * stacks) which order the elements LIFO (last-in-first-out).
13.82 + * Whatever the ordering used, the <em>head</em> of the queue is that
13.83 + * element which would be removed by a call to {@link #remove() } or
13.84 + * {@link #poll()}. In a FIFO queue, all new elements are inserted at
13.85 + * the <em> tail</em> of the queue. Other kinds of queues may use
13.86 + * different placement rules. Every <tt>Queue</tt> implementation
13.87 + * must specify its ordering properties.
13.88 + *
13.89 + * <p>The {@link #offer offer} method inserts an element if possible,
13.90 + * otherwise returning <tt>false</tt>. This differs from the {@link
13.91 + * java.util.Collection#add Collection.add} method, which can fail to
13.92 + * add an element only by throwing an unchecked exception. The
13.93 + * <tt>offer</tt> method is designed for use when failure is a normal,
13.94 + * rather than exceptional occurrence, for example, in fixed-capacity
13.95 + * (or "bounded") queues.
13.96 + *
13.97 + * <p>The {@link #remove()} and {@link #poll()} methods remove and
13.98 + * return the head of the queue.
13.99 + * Exactly which element is removed from the queue is a
13.100 + * function of the queue's ordering policy, which differs from
13.101 + * implementation to implementation. The <tt>remove()</tt> and
13.102 + * <tt>poll()</tt> methods differ only in their behavior when the
13.103 + * queue is empty: the <tt>remove()</tt> method throws an exception,
13.104 + * while the <tt>poll()</tt> method returns <tt>null</tt>.
13.105 + *
13.106 + * <p>The {@link #element()} and {@link #peek()} methods return, but do
13.107 + * not remove, the head of the queue.
13.108 + *
13.109 + * <p>The <tt>Queue</tt> interface does not define the <i>blocking queue
13.110 + * methods</i>, which are common in concurrent programming. These methods,
13.111 + * which wait for elements to appear or for space to become available, are
13.112 + * defined in the {@link java.util.concurrent.BlockingQueue} interface, which
13.113 + * extends this interface.
13.114 + *
13.115 + * <p><tt>Queue</tt> implementations generally do not allow insertion
13.116 + * of <tt>null</tt> elements, although some implementations, such as
13.117 + * {@link LinkedList}, do not prohibit insertion of <tt>null</tt>.
13.118 + * Even in the implementations that permit it, <tt>null</tt> should
13.119 + * not be inserted into a <tt>Queue</tt>, as <tt>null</tt> is also
13.120 + * used as a special return value by the <tt>poll</tt> method to
13.121 + * indicate that the queue contains no elements.
13.122 + *
13.123 + * <p><tt>Queue</tt> implementations generally do not define
13.124 + * element-based versions of methods <tt>equals</tt> and
13.125 + * <tt>hashCode</tt> but instead inherit the identity based versions
13.126 + * from class <tt>Object</tt>, because element-based equality is not
13.127 + * always well-defined for queues with the same elements but different
13.128 + * ordering properties.
13.129 + *
13.130 + *
13.131 + * <p>This interface is a member of the
13.132 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
13.133 + * Java Collections Framework</a>.
13.134 + *
13.135 + * @see java.util.Collection
13.136 + * @see LinkedList
13.137 + * @see PriorityQueue
13.138 + * @see java.util.concurrent.LinkedBlockingQueue
13.139 + * @see java.util.concurrent.BlockingQueue
13.140 + * @see java.util.concurrent.ArrayBlockingQueue
13.141 + * @see java.util.concurrent.LinkedBlockingQueue
13.142 + * @see java.util.concurrent.PriorityBlockingQueue
13.143 + * @since 1.5
13.144 + * @author Doug Lea
13.145 + * @param <E> the type of elements held in this collection
13.146 + */
13.147 +public interface Queue<E> extends Collection<E> {
13.148 + /**
13.149 + * Inserts the specified element into this queue if it is possible to do so
13.150 + * immediately without violating capacity restrictions, returning
13.151 + * <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt>
13.152 + * if no space is currently available.
13.153 + *
13.154 + * @param e the element to add
13.155 + * @return <tt>true</tt> (as specified by {@link Collection#add})
13.156 + * @throws IllegalStateException if the element cannot be added at this
13.157 + * time due to capacity restrictions
13.158 + * @throws ClassCastException if the class of the specified element
13.159 + * prevents it from being added to this queue
13.160 + * @throws NullPointerException if the specified element is null and
13.161 + * this queue does not permit null elements
13.162 + * @throws IllegalArgumentException if some property of this element
13.163 + * prevents it from being added to this queue
13.164 + */
13.165 + boolean add(E e);
13.166 +
13.167 + /**
13.168 + * Inserts the specified element into this queue if it is possible to do
13.169 + * so immediately without violating capacity restrictions.
13.170 + * When using a capacity-restricted queue, this method is generally
13.171 + * preferable to {@link #add}, which can fail to insert an element only
13.172 + * by throwing an exception.
13.173 + *
13.174 + * @param e the element to add
13.175 + * @return <tt>true</tt> if the element was added to this queue, else
13.176 + * <tt>false</tt>
13.177 + * @throws ClassCastException if the class of the specified element
13.178 + * prevents it from being added to this queue
13.179 + * @throws NullPointerException if the specified element is null and
13.180 + * this queue does not permit null elements
13.181 + * @throws IllegalArgumentException if some property of this element
13.182 + * prevents it from being added to this queue
13.183 + */
13.184 + boolean offer(E e);
13.185 +
13.186 + /**
13.187 + * Retrieves and removes the head of this queue. This method differs
13.188 + * from {@link #poll poll} only in that it throws an exception if this
13.189 + * queue is empty.
13.190 + *
13.191 + * @return the head of this queue
13.192 + * @throws NoSuchElementException if this queue is empty
13.193 + */
13.194 + E remove();
13.195 +
13.196 + /**
13.197 + * Retrieves and removes the head of this queue,
13.198 + * or returns <tt>null</tt> if this queue is empty.
13.199 + *
13.200 + * @return the head of this queue, or <tt>null</tt> if this queue is empty
13.201 + */
13.202 + E poll();
13.203 +
13.204 + /**
13.205 + * Retrieves, but does not remove, the head of this queue. This method
13.206 + * differs from {@link #peek peek} only in that it throws an exception
13.207 + * if this queue is empty.
13.208 + *
13.209 + * @return the head of this queue
13.210 + * @throws NoSuchElementException if this queue is empty
13.211 + */
13.212 + E element();
13.213 +
13.214 + /**
13.215 + * Retrieves, but does not remove, the head of this queue,
13.216 + * or returns <tt>null</tt> if this queue is empty.
13.217 + *
13.218 + * @return the head of this queue, or <tt>null</tt> if this queue is empty
13.219 + */
13.220 + E peek();
13.221 +}
14.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
14.2 +++ b/emul/compact/src/main/java/java/util/Random.java Mon Jan 28 18:14:00 2013 +0100
14.3 @@ -0,0 +1,503 @@
14.4 +/*
14.5 + * Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
14.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
14.7 + *
14.8 + * This code is free software; you can redistribute it and/or modify it
14.9 + * under the terms of the GNU General Public License version 2 only, as
14.10 + * published by the Free Software Foundation. Oracle designates this
14.11 + * particular file as subject to the "Classpath" exception as provided
14.12 + * by Oracle in the LICENSE file that accompanied this code.
14.13 + *
14.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
14.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14.17 + * version 2 for more details (a copy is included in the LICENSE file that
14.18 + * accompanied this code).
14.19 + *
14.20 + * You should have received a copy of the GNU General Public License version
14.21 + * 2 along with this work; if not, write to the Free Software Foundation,
14.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
14.23 + *
14.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
14.25 + * or visit www.oracle.com if you need additional information or have any
14.26 + * questions.
14.27 + */
14.28 +
14.29 +package java.util;
14.30 +
14.31 +import org.apidesign.bck2brwsr.emul.lang.System;
14.32 +
14.33 +/**
14.34 + * An instance of this class is used to generate a stream of
14.35 + * pseudorandom numbers. The class uses a 48-bit seed, which is
14.36 + * modified using a linear congruential formula. (See Donald Knuth,
14.37 + * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
14.38 + * <p>
14.39 + * If two instances of {@code Random} are created with the same
14.40 + * seed, and the same sequence of method calls is made for each, they
14.41 + * will generate and return identical sequences of numbers. In order to
14.42 + * guarantee this property, particular algorithms are specified for the
14.43 + * class {@code Random}. Java implementations must use all the algorithms
14.44 + * shown here for the class {@code Random}, for the sake of absolute
14.45 + * portability of Java code. However, subclasses of class {@code Random}
14.46 + * are permitted to use other algorithms, so long as they adhere to the
14.47 + * general contracts for all the methods.
14.48 + * <p>
14.49 + * The algorithms implemented by class {@code Random} use a
14.50 + * {@code protected} utility method that on each invocation can supply
14.51 + * up to 32 pseudorandomly generated bits.
14.52 + * <p>
14.53 + * Many applications will find the method {@link Math#random} simpler to use.
14.54 + *
14.55 + * <p>Instances of {@code java.util.Random} are threadsafe.
14.56 + * However, the concurrent use of the same {@code java.util.Random}
14.57 + * instance across threads may encounter contention and consequent
14.58 + * poor performance. Consider instead using
14.59 + * {@link java.util.concurrent.ThreadLocalRandom} in multithreaded
14.60 + * designs.
14.61 + *
14.62 + * <p>Instances of {@code java.util.Random} are not cryptographically
14.63 + * secure. Consider instead using {@link java.security.SecureRandom} to
14.64 + * get a cryptographically secure pseudo-random number generator for use
14.65 + * by security-sensitive applications.
14.66 + *
14.67 + * @author Frank Yellin
14.68 + * @since 1.0
14.69 + */
14.70 +public
14.71 +class Random implements java.io.Serializable {
14.72 + /** use serialVersionUID from JDK 1.1 for interoperability */
14.73 + static final long serialVersionUID = 3905348978240129619L;
14.74 +
14.75 + /**
14.76 + * The internal state associated with this pseudorandom number generator.
14.77 + * (The specs for the methods in this class describe the ongoing
14.78 + * computation of this value.)
14.79 + */
14.80 + private long seed;
14.81 +
14.82 + private static final long multiplier = 0x5DEECE66DL;
14.83 + private static final long addend = 0xBL;
14.84 + private static final long mask = (1L << 48) - 1;
14.85 +
14.86 + /**
14.87 + * Creates a new random number generator. This constructor sets
14.88 + * the seed of the random number generator to a value very likely
14.89 + * to be distinct from any other invocation of this constructor.
14.90 + */
14.91 + public Random() {
14.92 + this(seedUniquifier() ^ System.nanoTime());
14.93 + }
14.94 +
14.95 + private static synchronized long seedUniquifier() {
14.96 + // L'Ecuyer, "Tables of Linear Congruential Generators of
14.97 + // Different Sizes and Good Lattice Structure", 1999
14.98 + long current = seedUniquifier;
14.99 + long next = current * 181783497276652981L;
14.100 + seedUniquifier = next;
14.101 + return next;
14.102 + }
14.103 +
14.104 + private static long seedUniquifier = 8682522807148012L;
14.105 +
14.106 + /**
14.107 + * Creates a new random number generator using a single {@code long} seed.
14.108 + * The seed is the initial value of the internal state of the pseudorandom
14.109 + * number generator which is maintained by method {@link #next}.
14.110 + *
14.111 + * <p>The invocation {@code new Random(seed)} is equivalent to:
14.112 + * <pre> {@code
14.113 + * Random rnd = new Random();
14.114 + * rnd.setSeed(seed);}</pre>
14.115 + *
14.116 + * @param seed the initial seed
14.117 + * @see #setSeed(long)
14.118 + */
14.119 + public Random(long seed) {
14.120 + this.seed = initialScramble(seed);
14.121 + }
14.122 +
14.123 + private static long initialScramble(long seed) {
14.124 + return (seed ^ multiplier) & mask;
14.125 + }
14.126 +
14.127 + /**
14.128 + * Sets the seed of this random number generator using a single
14.129 + * {@code long} seed. The general contract of {@code setSeed} is
14.130 + * that it alters the state of this random number generator object
14.131 + * so as to be in exactly the same state as if it had just been
14.132 + * created with the argument {@code seed} as a seed. The method
14.133 + * {@code setSeed} is implemented by class {@code Random} by
14.134 + * atomically updating the seed to
14.135 + * <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre>
14.136 + * and clearing the {@code haveNextNextGaussian} flag used by {@link
14.137 + * #nextGaussian}.
14.138 + *
14.139 + * <p>The implementation of {@code setSeed} by class {@code Random}
14.140 + * happens to use only 48 bits of the given seed. In general, however,
14.141 + * an overriding method may use all 64 bits of the {@code long}
14.142 + * argument as a seed value.
14.143 + *
14.144 + * @param seed the initial seed
14.145 + */
14.146 + synchronized public void setSeed(long seed) {
14.147 + this.seed = initialScramble(seed);
14.148 + haveNextNextGaussian = false;
14.149 + }
14.150 +
14.151 + /**
14.152 + * Generates the next pseudorandom number. Subclasses should
14.153 + * override this, as this is used by all other methods.
14.154 + *
14.155 + * <p>The general contract of {@code next} is that it returns an
14.156 + * {@code int} value and if the argument {@code bits} is between
14.157 + * {@code 1} and {@code 32} (inclusive), then that many low-order
14.158 + * bits of the returned value will be (approximately) independently
14.159 + * chosen bit values, each of which is (approximately) equally
14.160 + * likely to be {@code 0} or {@code 1}. The method {@code next} is
14.161 + * implemented by class {@code Random} by atomically updating the seed to
14.162 + * <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
14.163 + * and returning
14.164 + * <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
14.165 + *
14.166 + * This is a linear congruential pseudorandom number generator, as
14.167 + * defined by D. H. Lehmer and described by Donald E. Knuth in
14.168 + * <i>The Art of Computer Programming,</i> Volume 3:
14.169 + * <i>Seminumerical Algorithms</i>, section 3.2.1.
14.170 + *
14.171 + * @param bits random bits
14.172 + * @return the next pseudorandom value from this random number
14.173 + * generator's sequence
14.174 + * @since 1.1
14.175 + */
14.176 + protected synchronized int next(int bits) {
14.177 + long oldseed, nextseed;
14.178 + long seed = this.seed;
14.179 + oldseed = seed;
14.180 + nextseed = (oldseed * multiplier + addend) & mask;
14.181 + this.seed = nextseed;
14.182 + return (int)(nextseed >>> (48 - bits));
14.183 + }
14.184 +
14.185 + /**
14.186 + * Generates random bytes and places them into a user-supplied
14.187 + * byte array. The number of random bytes produced is equal to
14.188 + * the length of the byte array.
14.189 + *
14.190 + * <p>The method {@code nextBytes} is implemented by class {@code Random}
14.191 + * as if by:
14.192 + * <pre> {@code
14.193 + * public void nextBytes(byte[] bytes) {
14.194 + * for (int i = 0; i < bytes.length; )
14.195 + * for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
14.196 + * n-- > 0; rnd >>= 8)
14.197 + * bytes[i++] = (byte)rnd;
14.198 + * }}</pre>
14.199 + *
14.200 + * @param bytes the byte array to fill with random bytes
14.201 + * @throws NullPointerException if the byte array is null
14.202 + * @since 1.1
14.203 + */
14.204 + public void nextBytes(byte[] bytes) {
14.205 + for (int i = 0, len = bytes.length; i < len; )
14.206 + for (int rnd = nextInt(),
14.207 + n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
14.208 + n-- > 0; rnd >>= Byte.SIZE)
14.209 + bytes[i++] = (byte)rnd;
14.210 + }
14.211 +
14.212 + /**
14.213 + * Returns the next pseudorandom, uniformly distributed {@code int}
14.214 + * value from this random number generator's sequence. The general
14.215 + * contract of {@code nextInt} is that one {@code int} value is
14.216 + * pseudorandomly generated and returned. All 2<font size="-1"><sup>32
14.217 + * </sup></font> possible {@code int} values are produced with
14.218 + * (approximately) equal probability.
14.219 + *
14.220 + * <p>The method {@code nextInt} is implemented by class {@code Random}
14.221 + * as if by:
14.222 + * <pre> {@code
14.223 + * public int nextInt() {
14.224 + * return next(32);
14.225 + * }}</pre>
14.226 + *
14.227 + * @return the next pseudorandom, uniformly distributed {@code int}
14.228 + * value from this random number generator's sequence
14.229 + */
14.230 + public int nextInt() {
14.231 + return next(32);
14.232 + }
14.233 +
14.234 + /**
14.235 + * Returns a pseudorandom, uniformly distributed {@code int} value
14.236 + * between 0 (inclusive) and the specified value (exclusive), drawn from
14.237 + * this random number generator's sequence. The general contract of
14.238 + * {@code nextInt} is that one {@code int} value in the specified range
14.239 + * is pseudorandomly generated and returned. All {@code n} possible
14.240 + * {@code int} values are produced with (approximately) equal
14.241 + * probability. The method {@code nextInt(int n)} is implemented by
14.242 + * class {@code Random} as if by:
14.243 + * <pre> {@code
14.244 + * public int nextInt(int n) {
14.245 + * if (n <= 0)
14.246 + * throw new IllegalArgumentException("n must be positive");
14.247 + *
14.248 + * if ((n & -n) == n) // i.e., n is a power of 2
14.249 + * return (int)((n * (long)next(31)) >> 31);
14.250 + *
14.251 + * int bits, val;
14.252 + * do {
14.253 + * bits = next(31);
14.254 + * val = bits % n;
14.255 + * } while (bits - val + (n-1) < 0);
14.256 + * return val;
14.257 + * }}</pre>
14.258 + *
14.259 + * <p>The hedge "approximately" is used in the foregoing description only
14.260 + * because the next method is only approximately an unbiased source of
14.261 + * independently chosen bits. If it were a perfect source of randomly
14.262 + * chosen bits, then the algorithm shown would choose {@code int}
14.263 + * values from the stated range with perfect uniformity.
14.264 + * <p>
14.265 + * The algorithm is slightly tricky. It rejects values that would result
14.266 + * in an uneven distribution (due to the fact that 2^31 is not divisible
14.267 + * by n). The probability of a value being rejected depends on n. The
14.268 + * worst case is n=2^30+1, for which the probability of a reject is 1/2,
14.269 + * and the expected number of iterations before the loop terminates is 2.
14.270 + * <p>
14.271 + * The algorithm treats the case where n is a power of two specially: it
14.272 + * returns the correct number of high-order bits from the underlying
14.273 + * pseudo-random number generator. In the absence of special treatment,
14.274 + * the correct number of <i>low-order</i> bits would be returned. Linear
14.275 + * congruential pseudo-random number generators such as the one
14.276 + * implemented by this class are known to have short periods in the
14.277 + * sequence of values of their low-order bits. Thus, this special case
14.278 + * greatly increases the length of the sequence of values returned by
14.279 + * successive calls to this method if n is a small power of two.
14.280 + *
14.281 + * @param n the bound on the random number to be returned. Must be
14.282 + * positive.
14.283 + * @return the next pseudorandom, uniformly distributed {@code int}
14.284 + * value between {@code 0} (inclusive) and {@code n} (exclusive)
14.285 + * from this random number generator's sequence
14.286 + * @throws IllegalArgumentException if n is not positive
14.287 + * @since 1.2
14.288 + */
14.289 +
14.290 + public int nextInt(int n) {
14.291 + if (n <= 0)
14.292 + throw new IllegalArgumentException("n must be positive");
14.293 +
14.294 + if ((n & -n) == n) // i.e., n is a power of 2
14.295 + return (int)((n * (long)next(31)) >> 31);
14.296 +
14.297 + int bits, val;
14.298 + do {
14.299 + bits = next(31);
14.300 + val = bits % n;
14.301 + } while (bits - val + (n-1) < 0);
14.302 + return val;
14.303 + }
14.304 +
14.305 + /**
14.306 + * Returns the next pseudorandom, uniformly distributed {@code long}
14.307 + * value from this random number generator's sequence. The general
14.308 + * contract of {@code nextLong} is that one {@code long} value is
14.309 + * pseudorandomly generated and returned.
14.310 + *
14.311 + * <p>The method {@code nextLong} is implemented by class {@code Random}
14.312 + * as if by:
14.313 + * <pre> {@code
14.314 + * public long nextLong() {
14.315 + * return ((long)next(32) << 32) + next(32);
14.316 + * }}</pre>
14.317 + *
14.318 + * Because class {@code Random} uses a seed with only 48 bits,
14.319 + * this algorithm will not return all possible {@code long} values.
14.320 + *
14.321 + * @return the next pseudorandom, uniformly distributed {@code long}
14.322 + * value from this random number generator's sequence
14.323 + */
14.324 + public long nextLong() {
14.325 + // it's okay that the bottom word remains signed.
14.326 + return ((long)(next(32)) << 32) + next(32);
14.327 + }
14.328 +
14.329 + /**
14.330 + * Returns the next pseudorandom, uniformly distributed
14.331 + * {@code boolean} value from this random number generator's
14.332 + * sequence. The general contract of {@code nextBoolean} is that one
14.333 + * {@code boolean} value is pseudorandomly generated and returned. The
14.334 + * values {@code true} and {@code false} are produced with
14.335 + * (approximately) equal probability.
14.336 + *
14.337 + * <p>The method {@code nextBoolean} is implemented by class {@code Random}
14.338 + * as if by:
14.339 + * <pre> {@code
14.340 + * public boolean nextBoolean() {
14.341 + * return next(1) != 0;
14.342 + * }}</pre>
14.343 + *
14.344 + * @return the next pseudorandom, uniformly distributed
14.345 + * {@code boolean} value from this random number generator's
14.346 + * sequence
14.347 + * @since 1.2
14.348 + */
14.349 + public boolean nextBoolean() {
14.350 + return next(1) != 0;
14.351 + }
14.352 +
14.353 + /**
14.354 + * Returns the next pseudorandom, uniformly distributed {@code float}
14.355 + * value between {@code 0.0} and {@code 1.0} from this random
14.356 + * number generator's sequence.
14.357 + *
14.358 + * <p>The general contract of {@code nextFloat} is that one
14.359 + * {@code float} value, chosen (approximately) uniformly from the
14.360 + * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
14.361 + * pseudorandomly generated and returned. All 2<font
14.362 + * size="-1"><sup>24</sup></font> possible {@code float} values
14.363 + * of the form <i>m x </i>2<font
14.364 + * size="-1"><sup>-24</sup></font>, where <i>m</i> is a positive
14.365 + * integer less than 2<font size="-1"><sup>24</sup> </font>, are
14.366 + * produced with (approximately) equal probability.
14.367 + *
14.368 + * <p>The method {@code nextFloat} is implemented by class {@code Random}
14.369 + * as if by:
14.370 + * <pre> {@code
14.371 + * public float nextFloat() {
14.372 + * return next(24) / ((float)(1 << 24));
14.373 + * }}</pre>
14.374 + *
14.375 + * <p>The hedge "approximately" is used in the foregoing description only
14.376 + * because the next method is only approximately an unbiased source of
14.377 + * independently chosen bits. If it were a perfect source of randomly
14.378 + * chosen bits, then the algorithm shown would choose {@code float}
14.379 + * values from the stated range with perfect uniformity.<p>
14.380 + * [In early versions of Java, the result was incorrectly calculated as:
14.381 + * <pre> {@code
14.382 + * return next(30) / ((float)(1 << 30));}</pre>
14.383 + * This might seem to be equivalent, if not better, but in fact it
14.384 + * introduced a slight nonuniformity because of the bias in the rounding
14.385 + * of floating-point numbers: it was slightly more likely that the
14.386 + * low-order bit of the significand would be 0 than that it would be 1.]
14.387 + *
14.388 + * @return the next pseudorandom, uniformly distributed {@code float}
14.389 + * value between {@code 0.0} and {@code 1.0} from this
14.390 + * random number generator's sequence
14.391 + */
14.392 + public float nextFloat() {
14.393 + return next(24) / ((float)(1 << 24));
14.394 + }
14.395 +
14.396 + /**
14.397 + * Returns the next pseudorandom, uniformly distributed
14.398 + * {@code double} value between {@code 0.0} and
14.399 + * {@code 1.0} from this random number generator's sequence.
14.400 + *
14.401 + * <p>The general contract of {@code nextDouble} is that one
14.402 + * {@code double} value, chosen (approximately) uniformly from the
14.403 + * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
14.404 + * pseudorandomly generated and returned.
14.405 + *
14.406 + * <p>The method {@code nextDouble} is implemented by class {@code Random}
14.407 + * as if by:
14.408 + * <pre> {@code
14.409 + * public double nextDouble() {
14.410 + * return (((long)next(26) << 27) + next(27))
14.411 + * / (double)(1L << 53);
14.412 + * }}</pre>
14.413 + *
14.414 + * <p>The hedge "approximately" is used in the foregoing description only
14.415 + * because the {@code next} method is only approximately an unbiased
14.416 + * source of independently chosen bits. If it were a perfect source of
14.417 + * randomly chosen bits, then the algorithm shown would choose
14.418 + * {@code double} values from the stated range with perfect uniformity.
14.419 + * <p>[In early versions of Java, the result was incorrectly calculated as:
14.420 + * <pre> {@code
14.421 + * return (((long)next(27) << 27) + next(27))
14.422 + * / (double)(1L << 54);}</pre>
14.423 + * This might seem to be equivalent, if not better, but in fact it
14.424 + * introduced a large nonuniformity because of the bias in the rounding
14.425 + * of floating-point numbers: it was three times as likely that the
14.426 + * low-order bit of the significand would be 0 than that it would be 1!
14.427 + * This nonuniformity probably doesn't matter much in practice, but we
14.428 + * strive for perfection.]
14.429 + *
14.430 + * @return the next pseudorandom, uniformly distributed {@code double}
14.431 + * value between {@code 0.0} and {@code 1.0} from this
14.432 + * random number generator's sequence
14.433 + * @see Math#random
14.434 + */
14.435 + public double nextDouble() {
14.436 + return (((long)(next(26)) << 27) + next(27))
14.437 + / (double)(1L << 53);
14.438 + }
14.439 +
14.440 + private double nextNextGaussian;
14.441 + private boolean haveNextNextGaussian = false;
14.442 +
14.443 + /**
14.444 + * Returns the next pseudorandom, Gaussian ("normally") distributed
14.445 + * {@code double} value with mean {@code 0.0} and standard
14.446 + * deviation {@code 1.0} from this random number generator's sequence.
14.447 + * <p>
14.448 + * The general contract of {@code nextGaussian} is that one
14.449 + * {@code double} value, chosen from (approximately) the usual
14.450 + * normal distribution with mean {@code 0.0} and standard deviation
14.451 + * {@code 1.0}, is pseudorandomly generated and returned.
14.452 + *
14.453 + * <p>The method {@code nextGaussian} is implemented by class
14.454 + * {@code Random} as if by a threadsafe version of the following:
14.455 + * <pre> {@code
14.456 + * private double nextNextGaussian;
14.457 + * private boolean haveNextNextGaussian = false;
14.458 + *
14.459 + * public double nextGaussian() {
14.460 + * if (haveNextNextGaussian) {
14.461 + * haveNextNextGaussian = false;
14.462 + * return nextNextGaussian;
14.463 + * } else {
14.464 + * double v1, v2, s;
14.465 + * do {
14.466 + * v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
14.467 + * v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
14.468 + * s = v1 * v1 + v2 * v2;
14.469 + * } while (s >= 1 || s == 0);
14.470 + * double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
14.471 + * nextNextGaussian = v2 * multiplier;
14.472 + * haveNextNextGaussian = true;
14.473 + * return v1 * multiplier;
14.474 + * }
14.475 + * }}</pre>
14.476 + * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
14.477 + * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
14.478 + * Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>,
14.479 + * section 3.4.1, subsection C, algorithm P. Note that it generates two
14.480 + * independent values at the cost of only one call to {@code StrictMath.log}
14.481 + * and one call to {@code StrictMath.sqrt}.
14.482 + *
14.483 + * @return the next pseudorandom, Gaussian ("normally") distributed
14.484 + * {@code double} value with mean {@code 0.0} and
14.485 + * standard deviation {@code 1.0} from this random number
14.486 + * generator's sequence
14.487 + */
14.488 + synchronized public double nextGaussian() {
14.489 + // See Knuth, ACP, Section 3.4.1 Algorithm C.
14.490 + if (haveNextNextGaussian) {
14.491 + haveNextNextGaussian = false;
14.492 + return nextNextGaussian;
14.493 + } else {
14.494 + double v1, v2, s;
14.495 + do {
14.496 + v1 = 2 * nextDouble() - 1; // between -1 and 1
14.497 + v2 = 2 * nextDouble() - 1; // between -1 and 1
14.498 + s = v1 * v1 + v2 * v2;
14.499 + } while (s >= 1 || s == 0);
14.500 + double multiplier = Math.sqrt(-2 * Math.log(s)/s);
14.501 + nextNextGaussian = v2 * multiplier;
14.502 + haveNextNextGaussian = true;
14.503 + return v1 * multiplier;
14.504 + }
14.505 + }
14.506 +}
15.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
15.2 +++ b/emul/compact/src/main/java/java/util/SortedMap.java Mon Jan 28 18:14:00 2013 +0100
15.3 @@ -0,0 +1,284 @@
15.4 +/*
15.5 + * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
15.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
15.7 + *
15.8 + * This code is free software; you can redistribute it and/or modify it
15.9 + * under the terms of the GNU General Public License version 2 only, as
15.10 + * published by the Free Software Foundation. Oracle designates this
15.11 + * particular file as subject to the "Classpath" exception as provided
15.12 + * by Oracle in the LICENSE file that accompanied this code.
15.13 + *
15.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
15.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15.17 + * version 2 for more details (a copy is included in the LICENSE file that
15.18 + * accompanied this code).
15.19 + *
15.20 + * You should have received a copy of the GNU General Public License version
15.21 + * 2 along with this work; if not, write to the Free Software Foundation,
15.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
15.23 + *
15.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
15.25 + * or visit www.oracle.com if you need additional information or have any
15.26 + * questions.
15.27 + */
15.28 +
15.29 +package java.util;
15.30 +
15.31 +/**
15.32 + * A {@link Map} that further provides a <em>total ordering</em> on its keys.
15.33 + * The map is ordered according to the {@linkplain Comparable natural
15.34 + * ordering} of its keys, or by a {@link Comparator} typically
15.35 + * provided at sorted map creation time. This order is reflected when
15.36 + * iterating over the sorted map's collection views (returned by the
15.37 + * {@code entrySet}, {@code keySet} and {@code values} methods).
15.38 + * Several additional operations are provided to take advantage of the
15.39 + * ordering. (This interface is the map analogue of {@link SortedSet}.)
15.40 + *
15.41 + * <p>All keys inserted into a sorted map must implement the {@code Comparable}
15.42 + * interface (or be accepted by the specified comparator). Furthermore, all
15.43 + * such keys must be <em>mutually comparable</em>: {@code k1.compareTo(k2)} (or
15.44 + * {@code comparator.compare(k1, k2)}) must not throw a
15.45 + * {@code ClassCastException} for any keys {@code k1} and {@code k2} in
15.46 + * the sorted map. Attempts to violate this restriction will cause the
15.47 + * offending method or constructor invocation to throw a
15.48 + * {@code ClassCastException}.
15.49 + *
15.50 + * <p>Note that the ordering maintained by a sorted map (whether or not an
15.51 + * explicit comparator is provided) must be <em>consistent with equals</em> if
15.52 + * the sorted map is to correctly implement the {@code Map} interface. (See
15.53 + * the {@code Comparable} interface or {@code Comparator} interface for a
15.54 + * precise definition of <em>consistent with equals</em>.) This is so because
15.55 + * the {@code Map} interface is defined in terms of the {@code equals}
15.56 + * operation, but a sorted map performs all key comparisons using its
15.57 + * {@code compareTo} (or {@code compare}) method, so two keys that are
15.58 + * deemed equal by this method are, from the standpoint of the sorted map,
15.59 + * equal. The behavior of a tree map <em>is</em> well-defined even if its
15.60 + * ordering is inconsistent with equals; it just fails to obey the general
15.61 + * contract of the {@code Map} interface.
15.62 + *
15.63 + * <p>All general-purpose sorted map implementation classes should provide four
15.64 + * "standard" constructors. It is not possible to enforce this recommendation
15.65 + * though as required constructors cannot be specified by interfaces. The
15.66 + * expected "standard" constructors for all sorted map implementations are:
15.67 + * <ol>
15.68 + * <li>A void (no arguments) constructor, which creates an empty sorted map
15.69 + * sorted according to the natural ordering of its keys.</li>
15.70 + * <li>A constructor with a single argument of type {@code Comparator}, which
15.71 + * creates an empty sorted map sorted according to the specified comparator.</li>
15.72 + * <li>A constructor with a single argument of type {@code Map}, which creates
15.73 + * a new map with the same key-value mappings as its argument, sorted
15.74 + * according to the keys' natural ordering.</li>
15.75 + * <li>A constructor with a single argument of type {@code SortedMap}, which
15.76 + * creates a new sorted map with the same key-value mappings and the same
15.77 + * ordering as the input sorted map.</li>
15.78 + * </ol>
15.79 + *
15.80 + * <p><strong>Note</strong>: several methods return submaps with restricted key
15.81 + * ranges. Such ranges are <em>half-open</em>, that is, they include their low
15.82 + * endpoint but not their high endpoint (where applicable). If you need a
15.83 + * <em>closed range</em> (which includes both endpoints), and the key type
15.84 + * allows for calculation of the successor of a given key, merely request
15.85 + * the subrange from {@code lowEndpoint} to
15.86 + * {@code successor(highEndpoint)}. For example, suppose that {@code m}
15.87 + * is a map whose keys are strings. The following idiom obtains a view
15.88 + * containing all of the key-value mappings in {@code m} whose keys are
15.89 + * between {@code low} and {@code high}, inclusive:<pre>
15.90 + * SortedMap<String, V> sub = m.subMap(low, high+"\0");</pre>
15.91 + *
15.92 + * A similar technique can be used to generate an <em>open range</em>
15.93 + * (which contains neither endpoint). The following idiom obtains a
15.94 + * view containing all of the key-value mappings in {@code m} whose keys
15.95 + * are between {@code low} and {@code high}, exclusive:<pre>
15.96 + * SortedMap<String, V> sub = m.subMap(low+"\0", high);</pre>
15.97 + *
15.98 + * <p>This interface is a member of the
15.99 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
15.100 + * Java Collections Framework</a>.
15.101 + *
15.102 + * @param <K> the type of keys maintained by this map
15.103 + * @param <V> the type of mapped values
15.104 + *
15.105 + * @author Josh Bloch
15.106 + * @see Map
15.107 + * @see TreeMap
15.108 + * @see SortedSet
15.109 + * @see Comparator
15.110 + * @see Comparable
15.111 + * @see Collection
15.112 + * @see ClassCastException
15.113 + * @since 1.2
15.114 + */
15.115 +
15.116 +public interface SortedMap<K,V> extends Map<K,V> {
15.117 + /**
15.118 + * Returns the comparator used to order the keys in this map, or
15.119 + * {@code null} if this map uses the {@linkplain Comparable
15.120 + * natural ordering} of its keys.
15.121 + *
15.122 + * @return the comparator used to order the keys in this map,
15.123 + * or {@code null} if this map uses the natural ordering
15.124 + * of its keys
15.125 + */
15.126 + Comparator<? super K> comparator();
15.127 +
15.128 + /**
15.129 + * Returns a view of the portion of this map whose keys range from
15.130 + * {@code fromKey}, inclusive, to {@code toKey}, exclusive. (If
15.131 + * {@code fromKey} and {@code toKey} are equal, the returned map
15.132 + * is empty.) The returned map is backed by this map, so changes
15.133 + * in the returned map are reflected in this map, and vice-versa.
15.134 + * The returned map supports all optional map operations that this
15.135 + * map supports.
15.136 + *
15.137 + * <p>The returned map will throw an {@code IllegalArgumentException}
15.138 + * on an attempt to insert a key outside its range.
15.139 + *
15.140 + * @param fromKey low endpoint (inclusive) of the keys in the returned map
15.141 + * @param toKey high endpoint (exclusive) of the keys in the returned map
15.142 + * @return a view of the portion of this map whose keys range from
15.143 + * {@code fromKey}, inclusive, to {@code toKey}, exclusive
15.144 + * @throws ClassCastException if {@code fromKey} and {@code toKey}
15.145 + * cannot be compared to one another using this map's comparator
15.146 + * (or, if the map has no comparator, using natural ordering).
15.147 + * Implementations may, but are not required to, throw this
15.148 + * exception if {@code fromKey} or {@code toKey}
15.149 + * cannot be compared to keys currently in the map.
15.150 + * @throws NullPointerException if {@code fromKey} or {@code toKey}
15.151 + * is null and this map does not permit null keys
15.152 + * @throws IllegalArgumentException if {@code fromKey} is greater than
15.153 + * {@code toKey}; or if this map itself has a restricted
15.154 + * range, and {@code fromKey} or {@code toKey} lies
15.155 + * outside the bounds of the range
15.156 + */
15.157 + SortedMap<K,V> subMap(K fromKey, K toKey);
15.158 +
15.159 + /**
15.160 + * Returns a view of the portion of this map whose keys are
15.161 + * strictly less than {@code toKey}. The returned map is backed
15.162 + * by this map, so changes in the returned map are reflected in
15.163 + * this map, and vice-versa. The returned map supports all
15.164 + * optional map operations that this map supports.
15.165 + *
15.166 + * <p>The returned map will throw an {@code IllegalArgumentException}
15.167 + * on an attempt to insert a key outside its range.
15.168 + *
15.169 + * @param toKey high endpoint (exclusive) of the keys in the returned map
15.170 + * @return a view of the portion of this map whose keys are strictly
15.171 + * less than {@code toKey}
15.172 + * @throws ClassCastException if {@code toKey} is not compatible
15.173 + * with this map's comparator (or, if the map has no comparator,
15.174 + * if {@code toKey} does not implement {@link Comparable}).
15.175 + * Implementations may, but are not required to, throw this
15.176 + * exception if {@code toKey} cannot be compared to keys
15.177 + * currently in the map.
15.178 + * @throws NullPointerException if {@code toKey} is null and
15.179 + * this map does not permit null keys
15.180 + * @throws IllegalArgumentException if this map itself has a
15.181 + * restricted range, and {@code toKey} lies outside the
15.182 + * bounds of the range
15.183 + */
15.184 + SortedMap<K,V> headMap(K toKey);
15.185 +
15.186 + /**
15.187 + * Returns a view of the portion of this map whose keys are
15.188 + * greater than or equal to {@code fromKey}. The returned map is
15.189 + * backed by this map, so changes in the returned map are
15.190 + * reflected in this map, and vice-versa. The returned map
15.191 + * supports all optional map operations that this map supports.
15.192 + *
15.193 + * <p>The returned map will throw an {@code IllegalArgumentException}
15.194 + * on an attempt to insert a key outside its range.
15.195 + *
15.196 + * @param fromKey low endpoint (inclusive) of the keys in the returned map
15.197 + * @return a view of the portion of this map whose keys are greater
15.198 + * than or equal to {@code fromKey}
15.199 + * @throws ClassCastException if {@code fromKey} is not compatible
15.200 + * with this map's comparator (or, if the map has no comparator,
15.201 + * if {@code fromKey} does not implement {@link Comparable}).
15.202 + * Implementations may, but are not required to, throw this
15.203 + * exception if {@code fromKey} cannot be compared to keys
15.204 + * currently in the map.
15.205 + * @throws NullPointerException if {@code fromKey} is null and
15.206 + * this map does not permit null keys
15.207 + * @throws IllegalArgumentException if this map itself has a
15.208 + * restricted range, and {@code fromKey} lies outside the
15.209 + * bounds of the range
15.210 + */
15.211 + SortedMap<K,V> tailMap(K fromKey);
15.212 +
15.213 + /**
15.214 + * Returns the first (lowest) key currently in this map.
15.215 + *
15.216 + * @return the first (lowest) key currently in this map
15.217 + * @throws NoSuchElementException if this map is empty
15.218 + */
15.219 + K firstKey();
15.220 +
15.221 + /**
15.222 + * Returns the last (highest) key currently in this map.
15.223 + *
15.224 + * @return the last (highest) key currently in this map
15.225 + * @throws NoSuchElementException if this map is empty
15.226 + */
15.227 + K lastKey();
15.228 +
15.229 + /**
15.230 + * Returns a {@link Set} view of the keys contained in this map.
15.231 + * The set's iterator returns the keys in ascending order.
15.232 + * The set is backed by the map, so changes to the map are
15.233 + * reflected in the set, and vice-versa. If the map is modified
15.234 + * while an iteration over the set is in progress (except through
15.235 + * the iterator's own {@code remove} operation), the results of
15.236 + * the iteration are undefined. The set supports element removal,
15.237 + * which removes the corresponding mapping from the map, via the
15.238 + * {@code Iterator.remove}, {@code Set.remove},
15.239 + * {@code removeAll}, {@code retainAll}, and {@code clear}
15.240 + * operations. It does not support the {@code add} or {@code addAll}
15.241 + * operations.
15.242 + *
15.243 + * @return a set view of the keys contained in this map, sorted in
15.244 + * ascending order
15.245 + */
15.246 + Set<K> keySet();
15.247 +
15.248 + /**
15.249 + * Returns a {@link Collection} view of the values contained in this map.
15.250 + * The collection's iterator returns the values in ascending order
15.251 + * of the corresponding keys.
15.252 + * The collection is backed by the map, so changes to the map are
15.253 + * reflected in the collection, and vice-versa. If the map is
15.254 + * modified while an iteration over the collection is in progress
15.255 + * (except through the iterator's own {@code remove} operation),
15.256 + * the results of the iteration are undefined. The collection
15.257 + * supports element removal, which removes the corresponding
15.258 + * mapping from the map, via the {@code Iterator.remove},
15.259 + * {@code Collection.remove}, {@code removeAll},
15.260 + * {@code retainAll} and {@code clear} operations. It does not
15.261 + * support the {@code add} or {@code addAll} operations.
15.262 + *
15.263 + * @return a collection view of the values contained in this map,
15.264 + * sorted in ascending key order
15.265 + */
15.266 + Collection<V> values();
15.267 +
15.268 + /**
15.269 + * Returns a {@link Set} view of the mappings contained in this map.
15.270 + * The set's iterator returns the entries in ascending key order.
15.271 + * The set is backed by the map, so changes to the map are
15.272 + * reflected in the set, and vice-versa. If the map is modified
15.273 + * while an iteration over the set is in progress (except through
15.274 + * the iterator's own {@code remove} operation, or through the
15.275 + * {@code setValue} operation on a map entry returned by the
15.276 + * iterator) the results of the iteration are undefined. The set
15.277 + * supports element removal, which removes the corresponding
15.278 + * mapping from the map, via the {@code Iterator.remove},
15.279 + * {@code Set.remove}, {@code removeAll}, {@code retainAll} and
15.280 + * {@code clear} operations. It does not support the
15.281 + * {@code add} or {@code addAll} operations.
15.282 + *
15.283 + * @return a set view of the mappings contained in this map,
15.284 + * sorted in ascending key order
15.285 + */
15.286 + Set<Map.Entry<K, V>> entrySet();
15.287 +}
16.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
16.2 +++ b/emul/compact/src/main/java/java/util/SortedSet.java Mon Jan 28 18:14:00 2013 +0100
16.3 @@ -0,0 +1,222 @@
16.4 +/*
16.5 + * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
16.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
16.7 + *
16.8 + * This code is free software; you can redistribute it and/or modify it
16.9 + * under the terms of the GNU General Public License version 2 only, as
16.10 + * published by the Free Software Foundation. Oracle designates this
16.11 + * particular file as subject to the "Classpath" exception as provided
16.12 + * by Oracle in the LICENSE file that accompanied this code.
16.13 + *
16.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
16.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16.17 + * version 2 for more details (a copy is included in the LICENSE file that
16.18 + * accompanied this code).
16.19 + *
16.20 + * You should have received a copy of the GNU General Public License version
16.21 + * 2 along with this work; if not, write to the Free Software Foundation,
16.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
16.23 + *
16.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
16.25 + * or visit www.oracle.com if you need additional information or have any
16.26 + * questions.
16.27 + */
16.28 +
16.29 +package java.util;
16.30 +
16.31 +/**
16.32 + * A {@link Set} that further provides a <i>total ordering</i> on its elements.
16.33 + * The elements are ordered using their {@linkplain Comparable natural
16.34 + * ordering}, or by a {@link Comparator} typically provided at sorted
16.35 + * set creation time. The set's iterator will traverse the set in
16.36 + * ascending element order. Several additional operations are provided
16.37 + * to take advantage of the ordering. (This interface is the set
16.38 + * analogue of {@link SortedMap}.)
16.39 + *
16.40 + * <p>All elements inserted into a sorted set must implement the <tt>Comparable</tt>
16.41 + * interface (or be accepted by the specified comparator). Furthermore, all
16.42 + * such elements must be <i>mutually comparable</i>: <tt>e1.compareTo(e2)</tt>
16.43 + * (or <tt>comparator.compare(e1, e2)</tt>) must not throw a
16.44 + * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and <tt>e2</tt> in
16.45 + * the sorted set. Attempts to violate this restriction will cause the
16.46 + * offending method or constructor invocation to throw a
16.47 + * <tt>ClassCastException</tt>.
16.48 + *
16.49 + * <p>Note that the ordering maintained by a sorted set (whether or not an
16.50 + * explicit comparator is provided) must be <i>consistent with equals</i> if
16.51 + * the sorted set is to correctly implement the <tt>Set</tt> interface. (See
16.52 + * the <tt>Comparable</tt> interface or <tt>Comparator</tt> interface for a
16.53 + * precise definition of <i>consistent with equals</i>.) This is so because
16.54 + * the <tt>Set</tt> interface is defined in terms of the <tt>equals</tt>
16.55 + * operation, but a sorted set performs all element comparisons using its
16.56 + * <tt>compareTo</tt> (or <tt>compare</tt>) method, so two elements that are
16.57 + * deemed equal by this method are, from the standpoint of the sorted set,
16.58 + * equal. The behavior of a sorted set <i>is</i> well-defined even if its
16.59 + * ordering is inconsistent with equals; it just fails to obey the general
16.60 + * contract of the <tt>Set</tt> interface.
16.61 + *
16.62 + * <p>All general-purpose sorted set implementation classes should
16.63 + * provide four "standard" constructors: 1) A void (no arguments)
16.64 + * constructor, which creates an empty sorted set sorted according to
16.65 + * the natural ordering of its elements. 2) A constructor with a
16.66 + * single argument of type <tt>Comparator</tt>, which creates an empty
16.67 + * sorted set sorted according to the specified comparator. 3) A
16.68 + * constructor with a single argument of type <tt>Collection</tt>,
16.69 + * which creates a new sorted set with the same elements as its
16.70 + * argument, sorted according to the natural ordering of the elements.
16.71 + * 4) A constructor with a single argument of type <tt>SortedSet</tt>,
16.72 + * which creates a new sorted set with the same elements and the same
16.73 + * ordering as the input sorted set. There is no way to enforce this
16.74 + * recommendation, as interfaces cannot contain constructors.
16.75 + *
16.76 + * <p>Note: several methods return subsets with restricted ranges.
16.77 + * Such ranges are <i>half-open</i>, that is, they include their low
16.78 + * endpoint but not their high endpoint (where applicable).
16.79 + * If you need a <i>closed range</i> (which includes both endpoints), and
16.80 + * the element type allows for calculation of the successor of a given
16.81 + * value, merely request the subrange from <tt>lowEndpoint</tt> to
16.82 + * <tt>successor(highEndpoint)</tt>. For example, suppose that <tt>s</tt>
16.83 + * is a sorted set of strings. The following idiom obtains a view
16.84 + * containing all of the strings in <tt>s</tt> from <tt>low</tt> to
16.85 + * <tt>high</tt>, inclusive:<pre>
16.86 + * SortedSet<String> sub = s.subSet(low, high+"\0");</pre>
16.87 + *
16.88 + * A similar technique can be used to generate an <i>open range</i> (which
16.89 + * contains neither endpoint). The following idiom obtains a view
16.90 + * containing all of the Strings in <tt>s</tt> from <tt>low</tt> to
16.91 + * <tt>high</tt>, exclusive:<pre>
16.92 + * SortedSet<String> sub = s.subSet(low+"\0", high);</pre>
16.93 + *
16.94 + * <p>This interface is a member of the
16.95 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
16.96 + * Java Collections Framework</a>.
16.97 + *
16.98 + * @param <E> the type of elements maintained by this set
16.99 + *
16.100 + * @author Josh Bloch
16.101 + * @see Set
16.102 + * @see TreeSet
16.103 + * @see SortedMap
16.104 + * @see Collection
16.105 + * @see Comparable
16.106 + * @see Comparator
16.107 + * @see ClassCastException
16.108 + * @since 1.2
16.109 + */
16.110 +
16.111 +public interface SortedSet<E> extends Set<E> {
16.112 + /**
16.113 + * Returns the comparator used to order the elements in this set,
16.114 + * or <tt>null</tt> if this set uses the {@linkplain Comparable
16.115 + * natural ordering} of its elements.
16.116 + *
16.117 + * @return the comparator used to order the elements in this set,
16.118 + * or <tt>null</tt> if this set uses the natural ordering
16.119 + * of its elements
16.120 + */
16.121 + Comparator<? super E> comparator();
16.122 +
16.123 + /**
16.124 + * Returns a view of the portion of this set whose elements range
16.125 + * from <tt>fromElement</tt>, inclusive, to <tt>toElement</tt>,
16.126 + * exclusive. (If <tt>fromElement</tt> and <tt>toElement</tt> are
16.127 + * equal, the returned set is empty.) The returned set is backed
16.128 + * by this set, so changes in the returned set are reflected in
16.129 + * this set, and vice-versa. The returned set supports all
16.130 + * optional set operations that this set supports.
16.131 + *
16.132 + * <p>The returned set will throw an <tt>IllegalArgumentException</tt>
16.133 + * on an attempt to insert an element outside its range.
16.134 + *
16.135 + * @param fromElement low endpoint (inclusive) of the returned set
16.136 + * @param toElement high endpoint (exclusive) of the returned set
16.137 + * @return a view of the portion of this set whose elements range from
16.138 + * <tt>fromElement</tt>, inclusive, to <tt>toElement</tt>, exclusive
16.139 + * @throws ClassCastException if <tt>fromElement</tt> and
16.140 + * <tt>toElement</tt> cannot be compared to one another using this
16.141 + * set's comparator (or, if the set has no comparator, using
16.142 + * natural ordering). Implementations may, but are not required
16.143 + * to, throw this exception if <tt>fromElement</tt> or
16.144 + * <tt>toElement</tt> cannot be compared to elements currently in
16.145 + * the set.
16.146 + * @throws NullPointerException if <tt>fromElement</tt> or
16.147 + * <tt>toElement</tt> is null and this set does not permit null
16.148 + * elements
16.149 + * @throws IllegalArgumentException if <tt>fromElement</tt> is
16.150 + * greater than <tt>toElement</tt>; or if this set itself
16.151 + * has a restricted range, and <tt>fromElement</tt> or
16.152 + * <tt>toElement</tt> lies outside the bounds of the range
16.153 + */
16.154 + SortedSet<E> subSet(E fromElement, E toElement);
16.155 +
16.156 + /**
16.157 + * Returns a view of the portion of this set whose elements are
16.158 + * strictly less than <tt>toElement</tt>. The returned set is
16.159 + * backed by this set, so changes in the returned set are
16.160 + * reflected in this set, and vice-versa. The returned set
16.161 + * supports all optional set operations that this set supports.
16.162 + *
16.163 + * <p>The returned set will throw an <tt>IllegalArgumentException</tt>
16.164 + * on an attempt to insert an element outside its range.
16.165 + *
16.166 + * @param toElement high endpoint (exclusive) of the returned set
16.167 + * @return a view of the portion of this set whose elements are strictly
16.168 + * less than <tt>toElement</tt>
16.169 + * @throws ClassCastException if <tt>toElement</tt> is not compatible
16.170 + * with this set's comparator (or, if the set has no comparator,
16.171 + * if <tt>toElement</tt> does not implement {@link Comparable}).
16.172 + * Implementations may, but are not required to, throw this
16.173 + * exception if <tt>toElement</tt> cannot be compared to elements
16.174 + * currently in the set.
16.175 + * @throws NullPointerException if <tt>toElement</tt> is null and
16.176 + * this set does not permit null elements
16.177 + * @throws IllegalArgumentException if this set itself has a
16.178 + * restricted range, and <tt>toElement</tt> lies outside the
16.179 + * bounds of the range
16.180 + */
16.181 + SortedSet<E> headSet(E toElement);
16.182 +
16.183 + /**
16.184 + * Returns a view of the portion of this set whose elements are
16.185 + * greater than or equal to <tt>fromElement</tt>. The returned
16.186 + * set is backed by this set, so changes in the returned set are
16.187 + * reflected in this set, and vice-versa. The returned set
16.188 + * supports all optional set operations that this set supports.
16.189 + *
16.190 + * <p>The returned set will throw an <tt>IllegalArgumentException</tt>
16.191 + * on an attempt to insert an element outside its range.
16.192 + *
16.193 + * @param fromElement low endpoint (inclusive) of the returned set
16.194 + * @return a view of the portion of this set whose elements are greater
16.195 + * than or equal to <tt>fromElement</tt>
16.196 + * @throws ClassCastException if <tt>fromElement</tt> is not compatible
16.197 + * with this set's comparator (or, if the set has no comparator,
16.198 + * if <tt>fromElement</tt> does not implement {@link Comparable}).
16.199 + * Implementations may, but are not required to, throw this
16.200 + * exception if <tt>fromElement</tt> cannot be compared to elements
16.201 + * currently in the set.
16.202 + * @throws NullPointerException if <tt>fromElement</tt> is null
16.203 + * and this set does not permit null elements
16.204 + * @throws IllegalArgumentException if this set itself has a
16.205 + * restricted range, and <tt>fromElement</tt> lies outside the
16.206 + * bounds of the range
16.207 + */
16.208 + SortedSet<E> tailSet(E fromElement);
16.209 +
16.210 + /**
16.211 + * Returns the first (lowest) element currently in this set.
16.212 + *
16.213 + * @return the first (lowest) element currently in this set
16.214 + * @throws NoSuchElementException if this set is empty
16.215 + */
16.216 + E first();
16.217 +
16.218 + /**
16.219 + * Returns the last (highest) element currently in this set.
16.220 + *
16.221 + * @return the last (highest) element currently in this set
16.222 + * @throws NoSuchElementException if this set is empty
16.223 + */
16.224 + E last();
16.225 +}
17.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
17.2 +++ b/emul/compact/src/main/java/java/util/Stack.java Mon Jan 28 18:14:00 2013 +0100
17.3 @@ -0,0 +1,141 @@
17.4 +/*
17.5 + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
17.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
17.7 + *
17.8 + * This code is free software; you can redistribute it and/or modify it
17.9 + * under the terms of the GNU General Public License version 2 only, as
17.10 + * published by the Free Software Foundation. Oracle designates this
17.11 + * particular file as subject to the "Classpath" exception as provided
17.12 + * by Oracle in the LICENSE file that accompanied this code.
17.13 + *
17.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
17.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17.17 + * version 2 for more details (a copy is included in the LICENSE file that
17.18 + * accompanied this code).
17.19 + *
17.20 + * You should have received a copy of the GNU General Public License version
17.21 + * 2 along with this work; if not, write to the Free Software Foundation,
17.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
17.23 + *
17.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
17.25 + * or visit www.oracle.com if you need additional information or have any
17.26 + * questions.
17.27 + */
17.28 +
17.29 +package java.util;
17.30 +
17.31 +/**
17.32 + * The <code>Stack</code> class represents a last-in-first-out
17.33 + * (LIFO) stack of objects. It extends class <tt>Vector</tt> with five
17.34 + * operations that allow a vector to be treated as a stack. The usual
17.35 + * <tt>push</tt> and <tt>pop</tt> operations are provided, as well as a
17.36 + * method to <tt>peek</tt> at the top item on the stack, a method to test
17.37 + * for whether the stack is <tt>empty</tt>, and a method to <tt>search</tt>
17.38 + * the stack for an item and discover how far it is from the top.
17.39 + * <p>
17.40 + * When a stack is first created, it contains no items.
17.41 + *
17.42 + * <p>A more complete and consistent set of LIFO stack operations is
17.43 + * provided by the {@link Deque} interface and its implementations, which
17.44 + * should be used in preference to this class. For example:
17.45 + * <pre> {@code
17.46 + * Deque<Integer> stack = new ArrayDeque<Integer>();}</pre>
17.47 + *
17.48 + * @author Jonathan Payne
17.49 + * @since JDK1.0
17.50 + */
17.51 +public
17.52 +class Stack<E> extends Vector<E> {
17.53 + /**
17.54 + * Creates an empty Stack.
17.55 + */
17.56 + public Stack() {
17.57 + }
17.58 +
17.59 + /**
17.60 + * Pushes an item onto the top of this stack. This has exactly
17.61 + * the same effect as:
17.62 + * <blockquote><pre>
17.63 + * addElement(item)</pre></blockquote>
17.64 + *
17.65 + * @param item the item to be pushed onto this stack.
17.66 + * @return the <code>item</code> argument.
17.67 + * @see java.util.Vector#addElement
17.68 + */
17.69 + public E push(E item) {
17.70 + addElement(item);
17.71 +
17.72 + return item;
17.73 + }
17.74 +
17.75 + /**
17.76 + * Removes the object at the top of this stack and returns that
17.77 + * object as the value of this function.
17.78 + *
17.79 + * @return The object at the top of this stack (the last item
17.80 + * of the <tt>Vector</tt> object).
17.81 + * @throws EmptyStackException if this stack is empty.
17.82 + */
17.83 + public synchronized E pop() {
17.84 + E obj;
17.85 + int len = size();
17.86 +
17.87 + obj = peek();
17.88 + removeElementAt(len - 1);
17.89 +
17.90 + return obj;
17.91 + }
17.92 +
17.93 + /**
17.94 + * Looks at the object at the top of this stack without removing it
17.95 + * from the stack.
17.96 + *
17.97 + * @return the object at the top of this stack (the last item
17.98 + * of the <tt>Vector</tt> object).
17.99 + * @throws EmptyStackException if this stack is empty.
17.100 + */
17.101 + public synchronized E peek() {
17.102 + int len = size();
17.103 +
17.104 + if (len == 0)
17.105 + throw new EmptyStackException();
17.106 + return elementAt(len - 1);
17.107 + }
17.108 +
17.109 + /**
17.110 + * Tests if this stack is empty.
17.111 + *
17.112 + * @return <code>true</code> if and only if this stack contains
17.113 + * no items; <code>false</code> otherwise.
17.114 + */
17.115 + public boolean empty() {
17.116 + return size() == 0;
17.117 + }
17.118 +
17.119 + /**
17.120 + * Returns the 1-based position where an object is on this stack.
17.121 + * If the object <tt>o</tt> occurs as an item in this stack, this
17.122 + * method returns the distance from the top of the stack of the
17.123 + * occurrence nearest the top of the stack; the topmost item on the
17.124 + * stack is considered to be at distance <tt>1</tt>. The <tt>equals</tt>
17.125 + * method is used to compare <tt>o</tt> to the
17.126 + * items in this stack.
17.127 + *
17.128 + * @param o the desired object.
17.129 + * @return the 1-based position from the top of the stack where
17.130 + * the object is located; the return value <code>-1</code>
17.131 + * indicates that the object is not on the stack.
17.132 + */
17.133 + public synchronized int search(Object o) {
17.134 + int i = lastIndexOf(o);
17.135 +
17.136 + if (i >= 0) {
17.137 + return size() - i;
17.138 + }
17.139 + return -1;
17.140 + }
17.141 +
17.142 + /** use serialVersionUID from JDK 1.0.2 for interoperability */
17.143 + private static final long serialVersionUID = 1224463164541339165L;
17.144 +}
18.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
18.2 +++ b/emul/compact/src/main/java/java/util/StringTokenizer.java Mon Jan 28 18:14:00 2013 +0100
18.3 @@ -0,0 +1,431 @@
18.4 +/*
18.5 + * Copyright (c) 1994, 2004, Oracle and/or its affiliates. All rights reserved.
18.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
18.7 + *
18.8 + * This code is free software; you can redistribute it and/or modify it
18.9 + * under the terms of the GNU General Public License version 2 only, as
18.10 + * published by the Free Software Foundation. Oracle designates this
18.11 + * particular file as subject to the "Classpath" exception as provided
18.12 + * by Oracle in the LICENSE file that accompanied this code.
18.13 + *
18.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
18.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18.17 + * version 2 for more details (a copy is included in the LICENSE file that
18.18 + * accompanied this code).
18.19 + *
18.20 + * You should have received a copy of the GNU General Public License version
18.21 + * 2 along with this work; if not, write to the Free Software Foundation,
18.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18.23 + *
18.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
18.25 + * or visit www.oracle.com if you need additional information or have any
18.26 + * questions.
18.27 + */
18.28 +
18.29 +package java.util;
18.30 +
18.31 +import java.lang.*;
18.32 +
18.33 +/**
18.34 + * The string tokenizer class allows an application to break a
18.35 + * string into tokens. The tokenization method is much simpler than
18.36 + * the one used by the <code>StreamTokenizer</code> class. The
18.37 + * <code>StringTokenizer</code> methods do not distinguish among
18.38 + * identifiers, numbers, and quoted strings, nor do they recognize
18.39 + * and skip comments.
18.40 + * <p>
18.41 + * The set of delimiters (the characters that separate tokens) may
18.42 + * be specified either at creation time or on a per-token basis.
18.43 + * <p>
18.44 + * An instance of <code>StringTokenizer</code> behaves in one of two
18.45 + * ways, depending on whether it was created with the
18.46 + * <code>returnDelims</code> flag having the value <code>true</code>
18.47 + * or <code>false</code>:
18.48 + * <ul>
18.49 + * <li>If the flag is <code>false</code>, delimiter characters serve to
18.50 + * separate tokens. A token is a maximal sequence of consecutive
18.51 + * characters that are not delimiters.
18.52 + * <li>If the flag is <code>true</code>, delimiter characters are themselves
18.53 + * considered to be tokens. A token is thus either one delimiter
18.54 + * character, or a maximal sequence of consecutive characters that are
18.55 + * not delimiters.
18.56 + * </ul><p>
18.57 + * A <tt>StringTokenizer</tt> object internally maintains a current
18.58 + * position within the string to be tokenized. Some operations advance this
18.59 + * current position past the characters processed.<p>
18.60 + * A token is returned by taking a substring of the string that was used to
18.61 + * create the <tt>StringTokenizer</tt> object.
18.62 + * <p>
18.63 + * The following is one example of the use of the tokenizer. The code:
18.64 + * <blockquote><pre>
18.65 + * StringTokenizer st = new StringTokenizer("this is a test");
18.66 + * while (st.hasMoreTokens()) {
18.67 + * System.out.println(st.nextToken());
18.68 + * }
18.69 + * </pre></blockquote>
18.70 + * <p>
18.71 + * prints the following output:
18.72 + * <blockquote><pre>
18.73 + * this
18.74 + * is
18.75 + * a
18.76 + * test
18.77 + * </pre></blockquote>
18.78 + *
18.79 + * <p>
18.80 + * <tt>StringTokenizer</tt> is a legacy class that is retained for
18.81 + * compatibility reasons although its use is discouraged in new code. It is
18.82 + * recommended that anyone seeking this functionality use the <tt>split</tt>
18.83 + * method of <tt>String</tt> or the java.util.regex package instead.
18.84 + * <p>
18.85 + * The following example illustrates how the <tt>String.split</tt>
18.86 + * method can be used to break up a string into its basic tokens:
18.87 + * <blockquote><pre>
18.88 + * String[] result = "this is a test".split("\\s");
18.89 + * for (int x=0; x<result.length; x++)
18.90 + * System.out.println(result[x]);
18.91 + * </pre></blockquote>
18.92 + * <p>
18.93 + * prints the following output:
18.94 + * <blockquote><pre>
18.95 + * this
18.96 + * is
18.97 + * a
18.98 + * test
18.99 + * </pre></blockquote>
18.100 + *
18.101 + * @author unascribed
18.102 + * @see java.io.StreamTokenizer
18.103 + * @since JDK1.0
18.104 + */
18.105 +public
18.106 +class StringTokenizer implements Enumeration<Object> {
18.107 + private int currentPosition;
18.108 + private int newPosition;
18.109 + private int maxPosition;
18.110 + private String str;
18.111 + private String delimiters;
18.112 + private boolean retDelims;
18.113 + private boolean delimsChanged;
18.114 +
18.115 + /**
18.116 + * maxDelimCodePoint stores the value of the delimiter character with the
18.117 + * highest value. It is used to optimize the detection of delimiter
18.118 + * characters.
18.119 + *
18.120 + * It is unlikely to provide any optimization benefit in the
18.121 + * hasSurrogates case because most string characters will be
18.122 + * smaller than the limit, but we keep it so that the two code
18.123 + * paths remain similar.
18.124 + */
18.125 + private int maxDelimCodePoint;
18.126 +
18.127 + /**
18.128 + * If delimiters include any surrogates (including surrogate
18.129 + * pairs), hasSurrogates is true and the tokenizer uses the
18.130 + * different code path. This is because String.indexOf(int)
18.131 + * doesn't handle unpaired surrogates as a single character.
18.132 + */
18.133 + private boolean hasSurrogates = false;
18.134 +
18.135 + /**
18.136 + * When hasSurrogates is true, delimiters are converted to code
18.137 + * points and isDelimiter(int) is used to determine if the given
18.138 + * codepoint is a delimiter.
18.139 + */
18.140 + private int[] delimiterCodePoints;
18.141 +
18.142 + /**
18.143 + * Set maxDelimCodePoint to the highest char in the delimiter set.
18.144 + */
18.145 + private void setMaxDelimCodePoint() {
18.146 + if (delimiters == null) {
18.147 + maxDelimCodePoint = 0;
18.148 + return;
18.149 + }
18.150 +
18.151 + int m = 0;
18.152 + int c;
18.153 + int count = 0;
18.154 + for (int i = 0; i < delimiters.length(); i += Character.charCount(c)) {
18.155 + c = delimiters.charAt(i);
18.156 + if (c >= Character.MIN_HIGH_SURROGATE && c <= Character.MAX_LOW_SURROGATE) {
18.157 + c = delimiters.codePointAt(i);
18.158 + hasSurrogates = true;
18.159 + }
18.160 + if (m < c)
18.161 + m = c;
18.162 + count++;
18.163 + }
18.164 + maxDelimCodePoint = m;
18.165 +
18.166 + if (hasSurrogates) {
18.167 + delimiterCodePoints = new int[count];
18.168 + for (int i = 0, j = 0; i < count; i++, j += Character.charCount(c)) {
18.169 + c = delimiters.codePointAt(j);
18.170 + delimiterCodePoints[i] = c;
18.171 + }
18.172 + }
18.173 + }
18.174 +
18.175 + /**
18.176 + * Constructs a string tokenizer for the specified string. All
18.177 + * characters in the <code>delim</code> argument are the delimiters
18.178 + * for separating tokens.
18.179 + * <p>
18.180 + * If the <code>returnDelims</code> flag is <code>true</code>, then
18.181 + * the delimiter characters are also returned as tokens. Each
18.182 + * delimiter is returned as a string of length one. If the flag is
18.183 + * <code>false</code>, the delimiter characters are skipped and only
18.184 + * serve as separators between tokens.
18.185 + * <p>
18.186 + * Note that if <tt>delim</tt> is <tt>null</tt>, this constructor does
18.187 + * not throw an exception. However, trying to invoke other methods on the
18.188 + * resulting <tt>StringTokenizer</tt> may result in a
18.189 + * <tt>NullPointerException</tt>.
18.190 + *
18.191 + * @param str a string to be parsed.
18.192 + * @param delim the delimiters.
18.193 + * @param returnDelims flag indicating whether to return the delimiters
18.194 + * as tokens.
18.195 + * @exception NullPointerException if str is <CODE>null</CODE>
18.196 + */
18.197 + public StringTokenizer(String str, String delim, boolean returnDelims) {
18.198 + currentPosition = 0;
18.199 + newPosition = -1;
18.200 + delimsChanged = false;
18.201 + this.str = str;
18.202 + maxPosition = str.length();
18.203 + delimiters = delim;
18.204 + retDelims = returnDelims;
18.205 + setMaxDelimCodePoint();
18.206 + }
18.207 +
18.208 + /**
18.209 + * Constructs a string tokenizer for the specified string. The
18.210 + * characters in the <code>delim</code> argument are the delimiters
18.211 + * for separating tokens. Delimiter characters themselves will not
18.212 + * be treated as tokens.
18.213 + * <p>
18.214 + * Note that if <tt>delim</tt> is <tt>null</tt>, this constructor does
18.215 + * not throw an exception. However, trying to invoke other methods on the
18.216 + * resulting <tt>StringTokenizer</tt> may result in a
18.217 + * <tt>NullPointerException</tt>.
18.218 + *
18.219 + * @param str a string to be parsed.
18.220 + * @param delim the delimiters.
18.221 + * @exception NullPointerException if str is <CODE>null</CODE>
18.222 + */
18.223 + public StringTokenizer(String str, String delim) {
18.224 + this(str, delim, false);
18.225 + }
18.226 +
18.227 + /**
18.228 + * Constructs a string tokenizer for the specified string. The
18.229 + * tokenizer uses the default delimiter set, which is
18.230 + * <code>" \t\n\r\f"</code>: the space character,
18.231 + * the tab character, the newline character, the carriage-return character,
18.232 + * and the form-feed character. Delimiter characters themselves will
18.233 + * not be treated as tokens.
18.234 + *
18.235 + * @param str a string to be parsed.
18.236 + * @exception NullPointerException if str is <CODE>null</CODE>
18.237 + */
18.238 + public StringTokenizer(String str) {
18.239 + this(str, " \t\n\r\f", false);
18.240 + }
18.241 +
18.242 + /**
18.243 + * Skips delimiters starting from the specified position. If retDelims
18.244 + * is false, returns the index of the first non-delimiter character at or
18.245 + * after startPos. If retDelims is true, startPos is returned.
18.246 + */
18.247 + private int skipDelimiters(int startPos) {
18.248 + if (delimiters == null)
18.249 + throw new NullPointerException();
18.250 +
18.251 + int position = startPos;
18.252 + while (!retDelims && position < maxPosition) {
18.253 + if (!hasSurrogates) {
18.254 + char c = str.charAt(position);
18.255 + if ((c > maxDelimCodePoint) || (delimiters.indexOf(c) < 0))
18.256 + break;
18.257 + position++;
18.258 + } else {
18.259 + int c = str.codePointAt(position);
18.260 + if ((c > maxDelimCodePoint) || !isDelimiter(c)) {
18.261 + break;
18.262 + }
18.263 + position += Character.charCount(c);
18.264 + }
18.265 + }
18.266 + return position;
18.267 + }
18.268 +
18.269 + /**
18.270 + * Skips ahead from startPos and returns the index of the next delimiter
18.271 + * character encountered, or maxPosition if no such delimiter is found.
18.272 + */
18.273 + private int scanToken(int startPos) {
18.274 + int position = startPos;
18.275 + while (position < maxPosition) {
18.276 + if (!hasSurrogates) {
18.277 + char c = str.charAt(position);
18.278 + if ((c <= maxDelimCodePoint) && (delimiters.indexOf(c) >= 0))
18.279 + break;
18.280 + position++;
18.281 + } else {
18.282 + int c = str.codePointAt(position);
18.283 + if ((c <= maxDelimCodePoint) && isDelimiter(c))
18.284 + break;
18.285 + position += Character.charCount(c);
18.286 + }
18.287 + }
18.288 + if (retDelims && (startPos == position)) {
18.289 + if (!hasSurrogates) {
18.290 + char c = str.charAt(position);
18.291 + if ((c <= maxDelimCodePoint) && (delimiters.indexOf(c) >= 0))
18.292 + position++;
18.293 + } else {
18.294 + int c = str.codePointAt(position);
18.295 + if ((c <= maxDelimCodePoint) && isDelimiter(c))
18.296 + position += Character.charCount(c);
18.297 + }
18.298 + }
18.299 + return position;
18.300 + }
18.301 +
18.302 + private boolean isDelimiter(int codePoint) {
18.303 + for (int i = 0; i < delimiterCodePoints.length; i++) {
18.304 + if (delimiterCodePoints[i] == codePoint) {
18.305 + return true;
18.306 + }
18.307 + }
18.308 + return false;
18.309 + }
18.310 +
18.311 + /**
18.312 + * Tests if there are more tokens available from this tokenizer's string.
18.313 + * If this method returns <tt>true</tt>, then a subsequent call to
18.314 + * <tt>nextToken</tt> with no argument will successfully return a token.
18.315 + *
18.316 + * @return <code>true</code> if and only if there is at least one token
18.317 + * in the string after the current position; <code>false</code>
18.318 + * otherwise.
18.319 + */
18.320 + public boolean hasMoreTokens() {
18.321 + /*
18.322 + * Temporarily store this position and use it in the following
18.323 + * nextToken() method only if the delimiters haven't been changed in
18.324 + * that nextToken() invocation.
18.325 + */
18.326 + newPosition = skipDelimiters(currentPosition);
18.327 + return (newPosition < maxPosition);
18.328 + }
18.329 +
18.330 + /**
18.331 + * Returns the next token from this string tokenizer.
18.332 + *
18.333 + * @return the next token from this string tokenizer.
18.334 + * @exception NoSuchElementException if there are no more tokens in this
18.335 + * tokenizer's string.
18.336 + */
18.337 + public String nextToken() {
18.338 + /*
18.339 + * If next position already computed in hasMoreElements() and
18.340 + * delimiters have changed between the computation and this invocation,
18.341 + * then use the computed value.
18.342 + */
18.343 +
18.344 + currentPosition = (newPosition >= 0 && !delimsChanged) ?
18.345 + newPosition : skipDelimiters(currentPosition);
18.346 +
18.347 + /* Reset these anyway */
18.348 + delimsChanged = false;
18.349 + newPosition = -1;
18.350 +
18.351 + if (currentPosition >= maxPosition)
18.352 + throw new NoSuchElementException();
18.353 + int start = currentPosition;
18.354 + currentPosition = scanToken(currentPosition);
18.355 + return str.substring(start, currentPosition);
18.356 + }
18.357 +
18.358 + /**
18.359 + * Returns the next token in this string tokenizer's string. First,
18.360 + * the set of characters considered to be delimiters by this
18.361 + * <tt>StringTokenizer</tt> object is changed to be the characters in
18.362 + * the string <tt>delim</tt>. Then the next token in the string
18.363 + * after the current position is returned. The current position is
18.364 + * advanced beyond the recognized token. The new delimiter set
18.365 + * remains the default after this call.
18.366 + *
18.367 + * @param delim the new delimiters.
18.368 + * @return the next token, after switching to the new delimiter set.
18.369 + * @exception NoSuchElementException if there are no more tokens in this
18.370 + * tokenizer's string.
18.371 + * @exception NullPointerException if delim is <CODE>null</CODE>
18.372 + */
18.373 + public String nextToken(String delim) {
18.374 + delimiters = delim;
18.375 +
18.376 + /* delimiter string specified, so set the appropriate flag. */
18.377 + delimsChanged = true;
18.378 +
18.379 + setMaxDelimCodePoint();
18.380 + return nextToken();
18.381 + }
18.382 +
18.383 + /**
18.384 + * Returns the same value as the <code>hasMoreTokens</code>
18.385 + * method. It exists so that this class can implement the
18.386 + * <code>Enumeration</code> interface.
18.387 + *
18.388 + * @return <code>true</code> if there are more tokens;
18.389 + * <code>false</code> otherwise.
18.390 + * @see java.util.Enumeration
18.391 + * @see java.util.StringTokenizer#hasMoreTokens()
18.392 + */
18.393 + public boolean hasMoreElements() {
18.394 + return hasMoreTokens();
18.395 + }
18.396 +
18.397 + /**
18.398 + * Returns the same value as the <code>nextToken</code> method,
18.399 + * except that its declared return value is <code>Object</code> rather than
18.400 + * <code>String</code>. It exists so that this class can implement the
18.401 + * <code>Enumeration</code> interface.
18.402 + *
18.403 + * @return the next token in the string.
18.404 + * @exception NoSuchElementException if there are no more tokens in this
18.405 + * tokenizer's string.
18.406 + * @see java.util.Enumeration
18.407 + * @see java.util.StringTokenizer#nextToken()
18.408 + */
18.409 + public Object nextElement() {
18.410 + return nextToken();
18.411 + }
18.412 +
18.413 + /**
18.414 + * Calculates the number of times that this tokenizer's
18.415 + * <code>nextToken</code> method can be called before it generates an
18.416 + * exception. The current position is not advanced.
18.417 + *
18.418 + * @return the number of tokens remaining in the string using the current
18.419 + * delimiter set.
18.420 + * @see java.util.StringTokenizer#nextToken()
18.421 + */
18.422 + public int countTokens() {
18.423 + int count = 0;
18.424 + int currpos = currentPosition;
18.425 + while (currpos < maxPosition) {
18.426 + currpos = skipDelimiters(currpos);
18.427 + if (currpos >= maxPosition)
18.428 + break;
18.429 + currpos = scanToken(currpos);
18.430 + count++;
18.431 + }
18.432 + return count;
18.433 + }
18.434 +}
19.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
19.2 +++ b/emul/compact/src/main/java/java/util/Vector.java Mon Jan 28 18:14:00 2013 +0100
19.3 @@ -0,0 +1,1195 @@
19.4 +/*
19.5 + * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
19.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
19.7 + *
19.8 + * This code is free software; you can redistribute it and/or modify it
19.9 + * under the terms of the GNU General Public License version 2 only, as
19.10 + * published by the Free Software Foundation. Oracle designates this
19.11 + * particular file as subject to the "Classpath" exception as provided
19.12 + * by Oracle in the LICENSE file that accompanied this code.
19.13 + *
19.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
19.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19.17 + * version 2 for more details (a copy is included in the LICENSE file that
19.18 + * accompanied this code).
19.19 + *
19.20 + * You should have received a copy of the GNU General Public License version
19.21 + * 2 along with this work; if not, write to the Free Software Foundation,
19.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19.23 + *
19.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
19.25 + * or visit www.oracle.com if you need additional information or have any
19.26 + * questions.
19.27 + */
19.28 +
19.29 +package java.util;
19.30 +
19.31 +import org.apidesign.bck2brwsr.emul.lang.System;
19.32 +
19.33 +/**
19.34 + * The {@code Vector} class implements a growable array of
19.35 + * objects. Like an array, it contains components that can be
19.36 + * accessed using an integer index. However, the size of a
19.37 + * {@code Vector} can grow or shrink as needed to accommodate
19.38 + * adding and removing items after the {@code Vector} has been created.
19.39 + *
19.40 + * <p>Each vector tries to optimize storage management by maintaining a
19.41 + * {@code capacity} and a {@code capacityIncrement}. The
19.42 + * {@code capacity} is always at least as large as the vector
19.43 + * size; it is usually larger because as components are added to the
19.44 + * vector, the vector's storage increases in chunks the size of
19.45 + * {@code capacityIncrement}. An application can increase the
19.46 + * capacity of a vector before inserting a large number of
19.47 + * components; this reduces the amount of incremental reallocation.
19.48 + *
19.49 + * <p><a name="fail-fast"/>
19.50 + * The iterators returned by this class's {@link #iterator() iterator} and
19.51 + * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
19.52 + * if the vector is structurally modified at any time after the iterator is
19.53 + * created, in any way except through the iterator's own
19.54 + * {@link ListIterator#remove() remove} or
19.55 + * {@link ListIterator#add(Object) add} methods, the iterator will throw a
19.56 + * {@link ConcurrentModificationException}. Thus, in the face of
19.57 + * concurrent modification, the iterator fails quickly and cleanly, rather
19.58 + * than risking arbitrary, non-deterministic behavior at an undetermined
19.59 + * time in the future. The {@link Enumeration Enumerations} returned by
19.60 + * the {@link #elements() elements} method are <em>not</em> fail-fast.
19.61 + *
19.62 + * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
19.63 + * as it is, generally speaking, impossible to make any hard guarantees in the
19.64 + * presence of unsynchronized concurrent modification. Fail-fast iterators
19.65 + * throw {@code ConcurrentModificationException} on a best-effort basis.
19.66 + * Therefore, it would be wrong to write a program that depended on this
19.67 + * exception for its correctness: <i>the fail-fast behavior of iterators
19.68 + * should be used only to detect bugs.</i>
19.69 + *
19.70 + * <p>As of the Java 2 platform v1.2, this class was retrofitted to
19.71 + * implement the {@link List} interface, making it a member of the
19.72 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
19.73 + * Java Collections Framework</a>. Unlike the new collection
19.74 + * implementations, {@code Vector} is synchronized. If a thread-safe
19.75 + * implementation is not needed, it is recommended to use {@link
19.76 + * ArrayList} in place of {@code Vector}.
19.77 + *
19.78 + * @author Lee Boynton
19.79 + * @author Jonathan Payne
19.80 + * @see Collection
19.81 + * @see LinkedList
19.82 + * @since JDK1.0
19.83 + */
19.84 +public class Vector<E>
19.85 + extends AbstractList<E>
19.86 + implements List<E>, RandomAccess, Cloneable, java.io.Serializable
19.87 +{
19.88 + /**
19.89 + * The array buffer into which the components of the vector are
19.90 + * stored. The capacity of the vector is the length of this array buffer,
19.91 + * and is at least large enough to contain all the vector's elements.
19.92 + *
19.93 + * <p>Any array elements following the last element in the Vector are null.
19.94 + *
19.95 + * @serial
19.96 + */
19.97 + protected Object[] elementData;
19.98 +
19.99 + /**
19.100 + * The number of valid components in this {@code Vector} object.
19.101 + * Components {@code elementData[0]} through
19.102 + * {@code elementData[elementCount-1]} are the actual items.
19.103 + *
19.104 + * @serial
19.105 + */
19.106 + protected int elementCount;
19.107 +
19.108 + /**
19.109 + * The amount by which the capacity of the vector is automatically
19.110 + * incremented when its size becomes greater than its capacity. If
19.111 + * the capacity increment is less than or equal to zero, the capacity
19.112 + * of the vector is doubled each time it needs to grow.
19.113 + *
19.114 + * @serial
19.115 + */
19.116 + protected int capacityIncrement;
19.117 +
19.118 + /** use serialVersionUID from JDK 1.0.2 for interoperability */
19.119 + private static final long serialVersionUID = -2767605614048989439L;
19.120 +
19.121 + /**
19.122 + * Constructs an empty vector with the specified initial capacity and
19.123 + * capacity increment.
19.124 + *
19.125 + * @param initialCapacity the initial capacity of the vector
19.126 + * @param capacityIncrement the amount by which the capacity is
19.127 + * increased when the vector overflows
19.128 + * @throws IllegalArgumentException if the specified initial capacity
19.129 + * is negative
19.130 + */
19.131 + public Vector(int initialCapacity, int capacityIncrement) {
19.132 + super();
19.133 + if (initialCapacity < 0)
19.134 + throw new IllegalArgumentException("Illegal Capacity: "+
19.135 + initialCapacity);
19.136 + this.elementData = new Object[initialCapacity];
19.137 + this.capacityIncrement = capacityIncrement;
19.138 + }
19.139 +
19.140 + /**
19.141 + * Constructs an empty vector with the specified initial capacity and
19.142 + * with its capacity increment equal to zero.
19.143 + *
19.144 + * @param initialCapacity the initial capacity of the vector
19.145 + * @throws IllegalArgumentException if the specified initial capacity
19.146 + * is negative
19.147 + */
19.148 + public Vector(int initialCapacity) {
19.149 + this(initialCapacity, 0);
19.150 + }
19.151 +
19.152 + /**
19.153 + * Constructs an empty vector so that its internal data array
19.154 + * has size {@code 10} and its standard capacity increment is
19.155 + * zero.
19.156 + */
19.157 + public Vector() {
19.158 + this(10);
19.159 + }
19.160 +
19.161 + /**
19.162 + * Constructs a vector containing the elements of the specified
19.163 + * collection, in the order they are returned by the collection's
19.164 + * iterator.
19.165 + *
19.166 + * @param c the collection whose elements are to be placed into this
19.167 + * vector
19.168 + * @throws NullPointerException if the specified collection is null
19.169 + * @since 1.2
19.170 + */
19.171 + public Vector(Collection<? extends E> c) {
19.172 + elementData = c.toArray();
19.173 + elementCount = elementData.length;
19.174 + // c.toArray might (incorrectly) not return Object[] (see 6260652)
19.175 + if (elementData.getClass() != Object[].class)
19.176 + elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
19.177 + }
19.178 +
19.179 + /**
19.180 + * Copies the components of this vector into the specified array.
19.181 + * The item at index {@code k} in this vector is copied into
19.182 + * component {@code k} of {@code anArray}.
19.183 + *
19.184 + * @param anArray the array into which the components get copied
19.185 + * @throws NullPointerException if the given array is null
19.186 + * @throws IndexOutOfBoundsException if the specified array is not
19.187 + * large enough to hold all the components of this vector
19.188 + * @throws ArrayStoreException if a component of this vector is not of
19.189 + * a runtime type that can be stored in the specified array
19.190 + * @see #toArray(Object[])
19.191 + */
19.192 + public synchronized void copyInto(Object[] anArray) {
19.193 + System.arraycopy(elementData, 0, anArray, 0, elementCount);
19.194 + }
19.195 +
19.196 + /**
19.197 + * Trims the capacity of this vector to be the vector's current
19.198 + * size. If the capacity of this vector is larger than its current
19.199 + * size, then the capacity is changed to equal the size by replacing
19.200 + * its internal data array, kept in the field {@code elementData},
19.201 + * with a smaller one. An application can use this operation to
19.202 + * minimize the storage of a vector.
19.203 + */
19.204 + public synchronized void trimToSize() {
19.205 + modCount++;
19.206 + int oldCapacity = elementData.length;
19.207 + if (elementCount < oldCapacity) {
19.208 + elementData = Arrays.copyOf(elementData, elementCount);
19.209 + }
19.210 + }
19.211 +
19.212 + /**
19.213 + * Increases the capacity of this vector, if necessary, to ensure
19.214 + * that it can hold at least the number of components specified by
19.215 + * the minimum capacity argument.
19.216 + *
19.217 + * <p>If the current capacity of this vector is less than
19.218 + * {@code minCapacity}, then its capacity is increased by replacing its
19.219 + * internal data array, kept in the field {@code elementData}, with a
19.220 + * larger one. The size of the new data array will be the old size plus
19.221 + * {@code capacityIncrement}, unless the value of
19.222 + * {@code capacityIncrement} is less than or equal to zero, in which case
19.223 + * the new capacity will be twice the old capacity; but if this new size
19.224 + * is still smaller than {@code minCapacity}, then the new capacity will
19.225 + * be {@code minCapacity}.
19.226 + *
19.227 + * @param minCapacity the desired minimum capacity
19.228 + */
19.229 + public synchronized void ensureCapacity(int minCapacity) {
19.230 + if (minCapacity > 0) {
19.231 + modCount++;
19.232 + ensureCapacityHelper(minCapacity);
19.233 + }
19.234 + }
19.235 +
19.236 + /**
19.237 + * This implements the unsynchronized semantics of ensureCapacity.
19.238 + * Synchronized methods in this class can internally call this
19.239 + * method for ensuring capacity without incurring the cost of an
19.240 + * extra synchronization.
19.241 + *
19.242 + * @see #ensureCapacity(int)
19.243 + */
19.244 + private void ensureCapacityHelper(int minCapacity) {
19.245 + // overflow-conscious code
19.246 + if (minCapacity - elementData.length > 0)
19.247 + grow(minCapacity);
19.248 + }
19.249 +
19.250 + /**
19.251 + * The maximum size of array to allocate.
19.252 + * Some VMs reserve some header words in an array.
19.253 + * Attempts to allocate larger arrays may result in
19.254 + * OutOfMemoryError: Requested array size exceeds VM limit
19.255 + */
19.256 + private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
19.257 +
19.258 + private void grow(int minCapacity) {
19.259 + // overflow-conscious code
19.260 + int oldCapacity = elementData.length;
19.261 + int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
19.262 + capacityIncrement : oldCapacity);
19.263 + if (newCapacity - minCapacity < 0)
19.264 + newCapacity = minCapacity;
19.265 + if (newCapacity - MAX_ARRAY_SIZE > 0)
19.266 + newCapacity = hugeCapacity(minCapacity);
19.267 + elementData = Arrays.copyOf(elementData, newCapacity);
19.268 + }
19.269 +
19.270 + private static int hugeCapacity(int minCapacity) {
19.271 + if (minCapacity < 0) // overflow
19.272 + throw new OutOfMemoryError();
19.273 + return (minCapacity > MAX_ARRAY_SIZE) ?
19.274 + Integer.MAX_VALUE :
19.275 + MAX_ARRAY_SIZE;
19.276 + }
19.277 +
19.278 + /**
19.279 + * Sets the size of this vector. If the new size is greater than the
19.280 + * current size, new {@code null} items are added to the end of
19.281 + * the vector. If the new size is less than the current size, all
19.282 + * components at index {@code newSize} and greater are discarded.
19.283 + *
19.284 + * @param newSize the new size of this vector
19.285 + * @throws ArrayIndexOutOfBoundsException if the new size is negative
19.286 + */
19.287 + public synchronized void setSize(int newSize) {
19.288 + modCount++;
19.289 + if (newSize > elementCount) {
19.290 + ensureCapacityHelper(newSize);
19.291 + } else {
19.292 + for (int i = newSize ; i < elementCount ; i++) {
19.293 + elementData[i] = null;
19.294 + }
19.295 + }
19.296 + elementCount = newSize;
19.297 + }
19.298 +
19.299 + /**
19.300 + * Returns the current capacity of this vector.
19.301 + *
19.302 + * @return the current capacity (the length of its internal
19.303 + * data array, kept in the field {@code elementData}
19.304 + * of this vector)
19.305 + */
19.306 + public synchronized int capacity() {
19.307 + return elementData.length;
19.308 + }
19.309 +
19.310 + /**
19.311 + * Returns the number of components in this vector.
19.312 + *
19.313 + * @return the number of components in this vector
19.314 + */
19.315 + public synchronized int size() {
19.316 + return elementCount;
19.317 + }
19.318 +
19.319 + /**
19.320 + * Tests if this vector has no components.
19.321 + *
19.322 + * @return {@code true} if and only if this vector has
19.323 + * no components, that is, its size is zero;
19.324 + * {@code false} otherwise.
19.325 + */
19.326 + public synchronized boolean isEmpty() {
19.327 + return elementCount == 0;
19.328 + }
19.329 +
19.330 + /**
19.331 + * Returns an enumeration of the components of this vector. The
19.332 + * returned {@code Enumeration} object will generate all items in
19.333 + * this vector. The first item generated is the item at index {@code 0},
19.334 + * then the item at index {@code 1}, and so on.
19.335 + *
19.336 + * @return an enumeration of the components of this vector
19.337 + * @see Iterator
19.338 + */
19.339 + public Enumeration<E> elements() {
19.340 + return new Enumeration<E>() {
19.341 + int count = 0;
19.342 +
19.343 + public boolean hasMoreElements() {
19.344 + return count < elementCount;
19.345 + }
19.346 +
19.347 + public E nextElement() {
19.348 + synchronized (Vector.this) {
19.349 + if (count < elementCount) {
19.350 + return elementData(count++);
19.351 + }
19.352 + }
19.353 + throw new NoSuchElementException("Vector Enumeration");
19.354 + }
19.355 + };
19.356 + }
19.357 +
19.358 + /**
19.359 + * Returns {@code true} if this vector contains the specified element.
19.360 + * More formally, returns {@code true} if and only if this vector
19.361 + * contains at least one element {@code e} such that
19.362 + * <tt>(o==null ? e==null : o.equals(e))</tt>.
19.363 + *
19.364 + * @param o element whose presence in this vector is to be tested
19.365 + * @return {@code true} if this vector contains the specified element
19.366 + */
19.367 + public boolean contains(Object o) {
19.368 + return indexOf(o, 0) >= 0;
19.369 + }
19.370 +
19.371 + /**
19.372 + * Returns the index of the first occurrence of the specified element
19.373 + * in this vector, or -1 if this vector does not contain the element.
19.374 + * More formally, returns the lowest index {@code i} such that
19.375 + * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
19.376 + * or -1 if there is no such index.
19.377 + *
19.378 + * @param o element to search for
19.379 + * @return the index of the first occurrence of the specified element in
19.380 + * this vector, or -1 if this vector does not contain the element
19.381 + */
19.382 + public int indexOf(Object o) {
19.383 + return indexOf(o, 0);
19.384 + }
19.385 +
19.386 + /**
19.387 + * Returns the index of the first occurrence of the specified element in
19.388 + * this vector, searching forwards from {@code index}, or returns -1 if
19.389 + * the element is not found.
19.390 + * More formally, returns the lowest index {@code i} such that
19.391 + * <tt>(i >= index && (o==null ? get(i)==null : o.equals(get(i))))</tt>,
19.392 + * or -1 if there is no such index.
19.393 + *
19.394 + * @param o element to search for
19.395 + * @param index index to start searching from
19.396 + * @return the index of the first occurrence of the element in
19.397 + * this vector at position {@code index} or later in the vector;
19.398 + * {@code -1} if the element is not found.
19.399 + * @throws IndexOutOfBoundsException if the specified index is negative
19.400 + * @see Object#equals(Object)
19.401 + */
19.402 + public synchronized int indexOf(Object o, int index) {
19.403 + if (o == null) {
19.404 + for (int i = index ; i < elementCount ; i++)
19.405 + if (elementData[i]==null)
19.406 + return i;
19.407 + } else {
19.408 + for (int i = index ; i < elementCount ; i++)
19.409 + if (o.equals(elementData[i]))
19.410 + return i;
19.411 + }
19.412 + return -1;
19.413 + }
19.414 +
19.415 + /**
19.416 + * Returns the index of the last occurrence of the specified element
19.417 + * in this vector, or -1 if this vector does not contain the element.
19.418 + * More formally, returns the highest index {@code i} such that
19.419 + * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
19.420 + * or -1 if there is no such index.
19.421 + *
19.422 + * @param o element to search for
19.423 + * @return the index of the last occurrence of the specified element in
19.424 + * this vector, or -1 if this vector does not contain the element
19.425 + */
19.426 + public synchronized int lastIndexOf(Object o) {
19.427 + return lastIndexOf(o, elementCount-1);
19.428 + }
19.429 +
19.430 + /**
19.431 + * Returns the index of the last occurrence of the specified element in
19.432 + * this vector, searching backwards from {@code index}, or returns -1 if
19.433 + * the element is not found.
19.434 + * More formally, returns the highest index {@code i} such that
19.435 + * <tt>(i <= index && (o==null ? get(i)==null : o.equals(get(i))))</tt>,
19.436 + * or -1 if there is no such index.
19.437 + *
19.438 + * @param o element to search for
19.439 + * @param index index to start searching backwards from
19.440 + * @return the index of the last occurrence of the element at position
19.441 + * less than or equal to {@code index} in this vector;
19.442 + * -1 if the element is not found.
19.443 + * @throws IndexOutOfBoundsException if the specified index is greater
19.444 + * than or equal to the current size of this vector
19.445 + */
19.446 + public synchronized int lastIndexOf(Object o, int index) {
19.447 + if (index >= elementCount)
19.448 + throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
19.449 +
19.450 + if (o == null) {
19.451 + for (int i = index; i >= 0; i--)
19.452 + if (elementData[i]==null)
19.453 + return i;
19.454 + } else {
19.455 + for (int i = index; i >= 0; i--)
19.456 + if (o.equals(elementData[i]))
19.457 + return i;
19.458 + }
19.459 + return -1;
19.460 + }
19.461 +
19.462 + /**
19.463 + * Returns the component at the specified index.
19.464 + *
19.465 + * <p>This method is identical in functionality to the {@link #get(int)}
19.466 + * method (which is part of the {@link List} interface).
19.467 + *
19.468 + * @param index an index into this vector
19.469 + * @return the component at the specified index
19.470 + * @throws ArrayIndexOutOfBoundsException if the index is out of range
19.471 + * ({@code index < 0 || index >= size()})
19.472 + */
19.473 + public synchronized E elementAt(int index) {
19.474 + if (index >= elementCount) {
19.475 + throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
19.476 + }
19.477 +
19.478 + return elementData(index);
19.479 + }
19.480 +
19.481 + /**
19.482 + * Returns the first component (the item at index {@code 0}) of
19.483 + * this vector.
19.484 + *
19.485 + * @return the first component of this vector
19.486 + * @throws NoSuchElementException if this vector has no components
19.487 + */
19.488 + public synchronized E firstElement() {
19.489 + if (elementCount == 0) {
19.490 + throw new NoSuchElementException();
19.491 + }
19.492 + return elementData(0);
19.493 + }
19.494 +
19.495 + /**
19.496 + * Returns the last component of the vector.
19.497 + *
19.498 + * @return the last component of the vector, i.e., the component at index
19.499 + * <code>size() - 1</code>.
19.500 + * @throws NoSuchElementException if this vector is empty
19.501 + */
19.502 + public synchronized E lastElement() {
19.503 + if (elementCount == 0) {
19.504 + throw new NoSuchElementException();
19.505 + }
19.506 + return elementData(elementCount - 1);
19.507 + }
19.508 +
19.509 + /**
19.510 + * Sets the component at the specified {@code index} of this
19.511 + * vector to be the specified object. The previous component at that
19.512 + * position is discarded.
19.513 + *
19.514 + * <p>The index must be a value greater than or equal to {@code 0}
19.515 + * and less than the current size of the vector.
19.516 + *
19.517 + * <p>This method is identical in functionality to the
19.518 + * {@link #set(int, Object) set(int, E)}
19.519 + * method (which is part of the {@link List} interface). Note that the
19.520 + * {@code set} method reverses the order of the parameters, to more closely
19.521 + * match array usage. Note also that the {@code set} method returns the
19.522 + * old value that was stored at the specified position.
19.523 + *
19.524 + * @param obj what the component is to be set to
19.525 + * @param index the specified index
19.526 + * @throws ArrayIndexOutOfBoundsException if the index is out of range
19.527 + * ({@code index < 0 || index >= size()})
19.528 + */
19.529 + public synchronized void setElementAt(E obj, int index) {
19.530 + if (index >= elementCount) {
19.531 + throw new ArrayIndexOutOfBoundsException(index + " >= " +
19.532 + elementCount);
19.533 + }
19.534 + elementData[index] = obj;
19.535 + }
19.536 +
19.537 + /**
19.538 + * Deletes the component at the specified index. Each component in
19.539 + * this vector with an index greater or equal to the specified
19.540 + * {@code index} is shifted downward to have an index one
19.541 + * smaller than the value it had previously. The size of this vector
19.542 + * is decreased by {@code 1}.
19.543 + *
19.544 + * <p>The index must be a value greater than or equal to {@code 0}
19.545 + * and less than the current size of the vector.
19.546 + *
19.547 + * <p>This method is identical in functionality to the {@link #remove(int)}
19.548 + * method (which is part of the {@link List} interface). Note that the
19.549 + * {@code remove} method returns the old value that was stored at the
19.550 + * specified position.
19.551 + *
19.552 + * @param index the index of the object to remove
19.553 + * @throws ArrayIndexOutOfBoundsException if the index is out of range
19.554 + * ({@code index < 0 || index >= size()})
19.555 + */
19.556 + public synchronized void removeElementAt(int index) {
19.557 + modCount++;
19.558 + if (index >= elementCount) {
19.559 + throw new ArrayIndexOutOfBoundsException(index + " >= " +
19.560 + elementCount);
19.561 + }
19.562 + else if (index < 0) {
19.563 + throw new ArrayIndexOutOfBoundsException(index);
19.564 + }
19.565 + int j = elementCount - index - 1;
19.566 + if (j > 0) {
19.567 + System.arraycopy(elementData, index + 1, elementData, index, j);
19.568 + }
19.569 + elementCount--;
19.570 + elementData[elementCount] = null; /* to let gc do its work */
19.571 + }
19.572 +
19.573 + /**
19.574 + * Inserts the specified object as a component in this vector at the
19.575 + * specified {@code index}. Each component in this vector with
19.576 + * an index greater or equal to the specified {@code index} is
19.577 + * shifted upward to have an index one greater than the value it had
19.578 + * previously.
19.579 + *
19.580 + * <p>The index must be a value greater than or equal to {@code 0}
19.581 + * and less than or equal to the current size of the vector. (If the
19.582 + * index is equal to the current size of the vector, the new element
19.583 + * is appended to the Vector.)
19.584 + *
19.585 + * <p>This method is identical in functionality to the
19.586 + * {@link #add(int, Object) add(int, E)}
19.587 + * method (which is part of the {@link List} interface). Note that the
19.588 + * {@code add} method reverses the order of the parameters, to more closely
19.589 + * match array usage.
19.590 + *
19.591 + * @param obj the component to insert
19.592 + * @param index where to insert the new component
19.593 + * @throws ArrayIndexOutOfBoundsException if the index is out of range
19.594 + * ({@code index < 0 || index > size()})
19.595 + */
19.596 + public synchronized void insertElementAt(E obj, int index) {
19.597 + modCount++;
19.598 + if (index > elementCount) {
19.599 + throw new ArrayIndexOutOfBoundsException(index
19.600 + + " > " + elementCount);
19.601 + }
19.602 + ensureCapacityHelper(elementCount + 1);
19.603 + System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
19.604 + elementData[index] = obj;
19.605 + elementCount++;
19.606 + }
19.607 +
19.608 + /**
19.609 + * Adds the specified component to the end of this vector,
19.610 + * increasing its size by one. The capacity of this vector is
19.611 + * increased if its size becomes greater than its capacity.
19.612 + *
19.613 + * <p>This method is identical in functionality to the
19.614 + * {@link #add(Object) add(E)}
19.615 + * method (which is part of the {@link List} interface).
19.616 + *
19.617 + * @param obj the component to be added
19.618 + */
19.619 + public synchronized void addElement(E obj) {
19.620 + modCount++;
19.621 + ensureCapacityHelper(elementCount + 1);
19.622 + elementData[elementCount++] = obj;
19.623 + }
19.624 +
19.625 + /**
19.626 + * Removes the first (lowest-indexed) occurrence of the argument
19.627 + * from this vector. If the object is found in this vector, each
19.628 + * component in the vector with an index greater or equal to the
19.629 + * object's index is shifted downward to have an index one smaller
19.630 + * than the value it had previously.
19.631 + *
19.632 + * <p>This method is identical in functionality to the
19.633 + * {@link #remove(Object)} method (which is part of the
19.634 + * {@link List} interface).
19.635 + *
19.636 + * @param obj the component to be removed
19.637 + * @return {@code true} if the argument was a component of this
19.638 + * vector; {@code false} otherwise.
19.639 + */
19.640 + public synchronized boolean removeElement(Object obj) {
19.641 + modCount++;
19.642 + int i = indexOf(obj);
19.643 + if (i >= 0) {
19.644 + removeElementAt(i);
19.645 + return true;
19.646 + }
19.647 + return false;
19.648 + }
19.649 +
19.650 + /**
19.651 + * Removes all components from this vector and sets its size to zero.
19.652 + *
19.653 + * <p>This method is identical in functionality to the {@link #clear}
19.654 + * method (which is part of the {@link List} interface).
19.655 + */
19.656 + public synchronized void removeAllElements() {
19.657 + modCount++;
19.658 + // Let gc do its work
19.659 + for (int i = 0; i < elementCount; i++)
19.660 + elementData[i] = null;
19.661 +
19.662 + elementCount = 0;
19.663 + }
19.664 +
19.665 + /**
19.666 + * Returns a clone of this vector. The copy will contain a
19.667 + * reference to a clone of the internal data array, not a reference
19.668 + * to the original internal data array of this {@code Vector} object.
19.669 + *
19.670 + * @return a clone of this vector
19.671 + */
19.672 + public synchronized Object clone() {
19.673 + try {
19.674 + @SuppressWarnings("unchecked")
19.675 + Vector<E> v = (Vector<E>) super.clone();
19.676 + v.elementData = Arrays.copyOf(elementData, elementCount);
19.677 + v.modCount = 0;
19.678 + return v;
19.679 + } catch (CloneNotSupportedException e) {
19.680 + // this shouldn't happen, since we are Cloneable
19.681 + throw new InternalError();
19.682 + }
19.683 + }
19.684 +
19.685 + /**
19.686 + * Returns an array containing all of the elements in this Vector
19.687 + * in the correct order.
19.688 + *
19.689 + * @since 1.2
19.690 + */
19.691 + public synchronized Object[] toArray() {
19.692 + return Arrays.copyOf(elementData, elementCount);
19.693 + }
19.694 +
19.695 + /**
19.696 + * Returns an array containing all of the elements in this Vector in the
19.697 + * correct order; the runtime type of the returned array is that of the
19.698 + * specified array. If the Vector fits in the specified array, it is
19.699 + * returned therein. Otherwise, a new array is allocated with the runtime
19.700 + * type of the specified array and the size of this Vector.
19.701 + *
19.702 + * <p>If the Vector fits in the specified array with room to spare
19.703 + * (i.e., the array has more elements than the Vector),
19.704 + * the element in the array immediately following the end of the
19.705 + * Vector is set to null. (This is useful in determining the length
19.706 + * of the Vector <em>only</em> if the caller knows that the Vector
19.707 + * does not contain any null elements.)
19.708 + *
19.709 + * @param a the array into which the elements of the Vector are to
19.710 + * be stored, if it is big enough; otherwise, a new array of the
19.711 + * same runtime type is allocated for this purpose.
19.712 + * @return an array containing the elements of the Vector
19.713 + * @throws ArrayStoreException if the runtime type of a is not a supertype
19.714 + * of the runtime type of every element in this Vector
19.715 + * @throws NullPointerException if the given array is null
19.716 + * @since 1.2
19.717 + */
19.718 + @SuppressWarnings("unchecked")
19.719 + public synchronized <T> T[] toArray(T[] a) {
19.720 + if (a.length < elementCount)
19.721 + return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
19.722 +
19.723 + System.arraycopy(elementData, 0, a, 0, elementCount);
19.724 +
19.725 + if (a.length > elementCount)
19.726 + a[elementCount] = null;
19.727 +
19.728 + return a;
19.729 + }
19.730 +
19.731 + // Positional Access Operations
19.732 +
19.733 + @SuppressWarnings("unchecked")
19.734 + E elementData(int index) {
19.735 + return (E) elementData[index];
19.736 + }
19.737 +
19.738 + /**
19.739 + * Returns the element at the specified position in this Vector.
19.740 + *
19.741 + * @param index index of the element to return
19.742 + * @return object at the specified index
19.743 + * @throws ArrayIndexOutOfBoundsException if the index is out of range
19.744 + * ({@code index < 0 || index >= size()})
19.745 + * @since 1.2
19.746 + */
19.747 + public synchronized E get(int index) {
19.748 + if (index >= elementCount)
19.749 + throw new ArrayIndexOutOfBoundsException(index);
19.750 +
19.751 + return elementData(index);
19.752 + }
19.753 +
19.754 + /**
19.755 + * Replaces the element at the specified position in this Vector with the
19.756 + * specified element.
19.757 + *
19.758 + * @param index index of the element to replace
19.759 + * @param element element to be stored at the specified position
19.760 + * @return the element previously at the specified position
19.761 + * @throws ArrayIndexOutOfBoundsException if the index is out of range
19.762 + * ({@code index < 0 || index >= size()})
19.763 + * @since 1.2
19.764 + */
19.765 + public synchronized E set(int index, E element) {
19.766 + if (index >= elementCount)
19.767 + throw new ArrayIndexOutOfBoundsException(index);
19.768 +
19.769 + E oldValue = elementData(index);
19.770 + elementData[index] = element;
19.771 + return oldValue;
19.772 + }
19.773 +
19.774 + /**
19.775 + * Appends the specified element to the end of this Vector.
19.776 + *
19.777 + * @param e element to be appended to this Vector
19.778 + * @return {@code true} (as specified by {@link Collection#add})
19.779 + * @since 1.2
19.780 + */
19.781 + public synchronized boolean add(E e) {
19.782 + modCount++;
19.783 + ensureCapacityHelper(elementCount + 1);
19.784 + elementData[elementCount++] = e;
19.785 + return true;
19.786 + }
19.787 +
19.788 + /**
19.789 + * Removes the first occurrence of the specified element in this Vector
19.790 + * If the Vector does not contain the element, it is unchanged. More
19.791 + * formally, removes the element with the lowest index i such that
19.792 + * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such
19.793 + * an element exists).
19.794 + *
19.795 + * @param o element to be removed from this Vector, if present
19.796 + * @return true if the Vector contained the specified element
19.797 + * @since 1.2
19.798 + */
19.799 + public boolean remove(Object o) {
19.800 + return removeElement(o);
19.801 + }
19.802 +
19.803 + /**
19.804 + * Inserts the specified element at the specified position in this Vector.
19.805 + * Shifts the element currently at that position (if any) and any
19.806 + * subsequent elements to the right (adds one to their indices).
19.807 + *
19.808 + * @param index index at which the specified element is to be inserted
19.809 + * @param element element to be inserted
19.810 + * @throws ArrayIndexOutOfBoundsException if the index is out of range
19.811 + * ({@code index < 0 || index > size()})
19.812 + * @since 1.2
19.813 + */
19.814 + public void add(int index, E element) {
19.815 + insertElementAt(element, index);
19.816 + }
19.817 +
19.818 + /**
19.819 + * Removes the element at the specified position in this Vector.
19.820 + * Shifts any subsequent elements to the left (subtracts one from their
19.821 + * indices). Returns the element that was removed from the Vector.
19.822 + *
19.823 + * @throws ArrayIndexOutOfBoundsException if the index is out of range
19.824 + * ({@code index < 0 || index >= size()})
19.825 + * @param index the index of the element to be removed
19.826 + * @return element that was removed
19.827 + * @since 1.2
19.828 + */
19.829 + public synchronized E remove(int index) {
19.830 + modCount++;
19.831 + if (index >= elementCount)
19.832 + throw new ArrayIndexOutOfBoundsException(index);
19.833 + E oldValue = elementData(index);
19.834 +
19.835 + int numMoved = elementCount - index - 1;
19.836 + if (numMoved > 0)
19.837 + System.arraycopy(elementData, index+1, elementData, index,
19.838 + numMoved);
19.839 + elementData[--elementCount] = null; // Let gc do its work
19.840 +
19.841 + return oldValue;
19.842 + }
19.843 +
19.844 + /**
19.845 + * Removes all of the elements from this Vector. The Vector will
19.846 + * be empty after this call returns (unless it throws an exception).
19.847 + *
19.848 + * @since 1.2
19.849 + */
19.850 + public void clear() {
19.851 + removeAllElements();
19.852 + }
19.853 +
19.854 + // Bulk Operations
19.855 +
19.856 + /**
19.857 + * Returns true if this Vector contains all of the elements in the
19.858 + * specified Collection.
19.859 + *
19.860 + * @param c a collection whose elements will be tested for containment
19.861 + * in this Vector
19.862 + * @return true if this Vector contains all of the elements in the
19.863 + * specified collection
19.864 + * @throws NullPointerException if the specified collection is null
19.865 + */
19.866 + public synchronized boolean containsAll(Collection<?> c) {
19.867 + return super.containsAll(c);
19.868 + }
19.869 +
19.870 + /**
19.871 + * Appends all of the elements in the specified Collection to the end of
19.872 + * this Vector, in the order that they are returned by the specified
19.873 + * Collection's Iterator. The behavior of this operation is undefined if
19.874 + * the specified Collection is modified while the operation is in progress.
19.875 + * (This implies that the behavior of this call is undefined if the
19.876 + * specified Collection is this Vector, and this Vector is nonempty.)
19.877 + *
19.878 + * @param c elements to be inserted into this Vector
19.879 + * @return {@code true} if this Vector changed as a result of the call
19.880 + * @throws NullPointerException if the specified collection is null
19.881 + * @since 1.2
19.882 + */
19.883 + public synchronized boolean addAll(Collection<? extends E> c) {
19.884 + modCount++;
19.885 + Object[] a = c.toArray();
19.886 + int numNew = a.length;
19.887 + ensureCapacityHelper(elementCount + numNew);
19.888 + System.arraycopy(a, 0, elementData, elementCount, numNew);
19.889 + elementCount += numNew;
19.890 + return numNew != 0;
19.891 + }
19.892 +
19.893 + /**
19.894 + * Removes from this Vector all of its elements that are contained in the
19.895 + * specified Collection.
19.896 + *
19.897 + * @param c a collection of elements to be removed from the Vector
19.898 + * @return true if this Vector changed as a result of the call
19.899 + * @throws ClassCastException if the types of one or more elements
19.900 + * in this vector are incompatible with the specified
19.901 + * collection
19.902 + * (<a href="Collection.html#optional-restrictions">optional</a>)
19.903 + * @throws NullPointerException if this vector contains one or more null
19.904 + * elements and the specified collection does not support null
19.905 + * elements
19.906 + * (<a href="Collection.html#optional-restrictions">optional</a>),
19.907 + * or if the specified collection is null
19.908 + * @since 1.2
19.909 + */
19.910 + public synchronized boolean removeAll(Collection<?> c) {
19.911 + return super.removeAll(c);
19.912 + }
19.913 +
19.914 + /**
19.915 + * Retains only the elements in this Vector that are contained in the
19.916 + * specified Collection. In other words, removes from this Vector all
19.917 + * of its elements that are not contained in the specified Collection.
19.918 + *
19.919 + * @param c a collection of elements to be retained in this Vector
19.920 + * (all other elements are removed)
19.921 + * @return true if this Vector changed as a result of the call
19.922 + * @throws ClassCastException if the types of one or more elements
19.923 + * in this vector are incompatible with the specified
19.924 + * collection
19.925 + * (<a href="Collection.html#optional-restrictions">optional</a>)
19.926 + * @throws NullPointerException if this vector contains one or more null
19.927 + * elements and the specified collection does not support null
19.928 + * elements
19.929 + * (<a href="Collection.html#optional-restrictions">optional</a>),
19.930 + * or if the specified collection is null
19.931 + * @since 1.2
19.932 + */
19.933 + public synchronized boolean retainAll(Collection<?> c) {
19.934 + return super.retainAll(c);
19.935 + }
19.936 +
19.937 + /**
19.938 + * Inserts all of the elements in the specified Collection into this
19.939 + * Vector at the specified position. Shifts the element currently at
19.940 + * that position (if any) and any subsequent elements to the right
19.941 + * (increases their indices). The new elements will appear in the Vector
19.942 + * in the order that they are returned by the specified Collection's
19.943 + * iterator.
19.944 + *
19.945 + * @param index index at which to insert the first element from the
19.946 + * specified collection
19.947 + * @param c elements to be inserted into this Vector
19.948 + * @return {@code true} if this Vector changed as a result of the call
19.949 + * @throws ArrayIndexOutOfBoundsException if the index is out of range
19.950 + * ({@code index < 0 || index > size()})
19.951 + * @throws NullPointerException if the specified collection is null
19.952 + * @since 1.2
19.953 + */
19.954 + public synchronized boolean addAll(int index, Collection<? extends E> c) {
19.955 + modCount++;
19.956 + if (index < 0 || index > elementCount)
19.957 + throw new ArrayIndexOutOfBoundsException(index);
19.958 +
19.959 + Object[] a = c.toArray();
19.960 + int numNew = a.length;
19.961 + ensureCapacityHelper(elementCount + numNew);
19.962 +
19.963 + int numMoved = elementCount - index;
19.964 + if (numMoved > 0)
19.965 + System.arraycopy(elementData, index, elementData, index + numNew,
19.966 + numMoved);
19.967 +
19.968 + System.arraycopy(a, 0, elementData, index, numNew);
19.969 + elementCount += numNew;
19.970 + return numNew != 0;
19.971 + }
19.972 +
19.973 + /**
19.974 + * Compares the specified Object with this Vector for equality. Returns
19.975 + * true if and only if the specified Object is also a List, both Lists
19.976 + * have the same size, and all corresponding pairs of elements in the two
19.977 + * Lists are <em>equal</em>. (Two elements {@code e1} and
19.978 + * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :
19.979 + * e1.equals(e2))}.) In other words, two Lists are defined to be
19.980 + * equal if they contain the same elements in the same order.
19.981 + *
19.982 + * @param o the Object to be compared for equality with this Vector
19.983 + * @return true if the specified Object is equal to this Vector
19.984 + */
19.985 + public synchronized boolean equals(Object o) {
19.986 + return super.equals(o);
19.987 + }
19.988 +
19.989 + /**
19.990 + * Returns the hash code value for this Vector.
19.991 + */
19.992 + public synchronized int hashCode() {
19.993 + return super.hashCode();
19.994 + }
19.995 +
19.996 + /**
19.997 + * Returns a string representation of this Vector, containing
19.998 + * the String representation of each element.
19.999 + */
19.1000 + public synchronized String toString() {
19.1001 + return super.toString();
19.1002 + }
19.1003 +
19.1004 + /**
19.1005 + * Returns a view of the portion of this List between fromIndex,
19.1006 + * inclusive, and toIndex, exclusive. (If fromIndex and toIndex are
19.1007 + * equal, the returned List is empty.) The returned List is backed by this
19.1008 + * List, so changes in the returned List are reflected in this List, and
19.1009 + * vice-versa. The returned List supports all of the optional List
19.1010 + * operations supported by this List.
19.1011 + *
19.1012 + * <p>This method eliminates the need for explicit range operations (of
19.1013 + * the sort that commonly exist for arrays). Any operation that expects
19.1014 + * a List can be used as a range operation by operating on a subList view
19.1015 + * instead of a whole List. For example, the following idiom
19.1016 + * removes a range of elements from a List:
19.1017 + * <pre>
19.1018 + * list.subList(from, to).clear();
19.1019 + * </pre>
19.1020 + * Similar idioms may be constructed for indexOf and lastIndexOf,
19.1021 + * and all of the algorithms in the Collections class can be applied to
19.1022 + * a subList.
19.1023 + *
19.1024 + * <p>The semantics of the List returned by this method become undefined if
19.1025 + * the backing list (i.e., this List) is <i>structurally modified</i> in
19.1026 + * any way other than via the returned List. (Structural modifications are
19.1027 + * those that change the size of the List, or otherwise perturb it in such
19.1028 + * a fashion that iterations in progress may yield incorrect results.)
19.1029 + *
19.1030 + * @param fromIndex low endpoint (inclusive) of the subList
19.1031 + * @param toIndex high endpoint (exclusive) of the subList
19.1032 + * @return a view of the specified range within this List
19.1033 + * @throws IndexOutOfBoundsException if an endpoint index value is out of range
19.1034 + * {@code (fromIndex < 0 || toIndex > size)}
19.1035 + * @throws IllegalArgumentException if the endpoint indices are out of order
19.1036 + * {@code (fromIndex > toIndex)}
19.1037 + */
19.1038 + public synchronized List<E> subList(int fromIndex, int toIndex) {
19.1039 + return Collections.synchronizedList(super.subList(fromIndex, toIndex),
19.1040 + this);
19.1041 + }
19.1042 +
19.1043 + /**
19.1044 + * Removes from this list all of the elements whose index is between
19.1045 + * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
19.1046 + * Shifts any succeeding elements to the left (reduces their index).
19.1047 + * This call shortens the list by {@code (toIndex - fromIndex)} elements.
19.1048 + * (If {@code toIndex==fromIndex}, this operation has no effect.)
19.1049 + */
19.1050 + protected synchronized void removeRange(int fromIndex, int toIndex) {
19.1051 + modCount++;
19.1052 + int numMoved = elementCount - toIndex;
19.1053 + System.arraycopy(elementData, toIndex, elementData, fromIndex,
19.1054 + numMoved);
19.1055 +
19.1056 + // Let gc do its work
19.1057 + int newElementCount = elementCount - (toIndex-fromIndex);
19.1058 + while (elementCount != newElementCount)
19.1059 + elementData[--elementCount] = null;
19.1060 + }
19.1061 +
19.1062 + /**
19.1063 + * Returns a list iterator over the elements in this list (in proper
19.1064 + * sequence), starting at the specified position in the list.
19.1065 + * The specified index indicates the first element that would be
19.1066 + * returned by an initial call to {@link ListIterator#next next}.
19.1067 + * An initial call to {@link ListIterator#previous previous} would
19.1068 + * return the element with the specified index minus one.
19.1069 + *
19.1070 + * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
19.1071 + *
19.1072 + * @throws IndexOutOfBoundsException {@inheritDoc}
19.1073 + */
19.1074 + public synchronized ListIterator<E> listIterator(int index) {
19.1075 + if (index < 0 || index > elementCount)
19.1076 + throw new IndexOutOfBoundsException("Index: "+index);
19.1077 + return new ListItr(index);
19.1078 + }
19.1079 +
19.1080 + /**
19.1081 + * Returns a list iterator over the elements in this list (in proper
19.1082 + * sequence).
19.1083 + *
19.1084 + * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
19.1085 + *
19.1086 + * @see #listIterator(int)
19.1087 + */
19.1088 + public synchronized ListIterator<E> listIterator() {
19.1089 + return new ListItr(0);
19.1090 + }
19.1091 +
19.1092 + /**
19.1093 + * Returns an iterator over the elements in this list in proper sequence.
19.1094 + *
19.1095 + * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
19.1096 + *
19.1097 + * @return an iterator over the elements in this list in proper sequence
19.1098 + */
19.1099 + public synchronized Iterator<E> iterator() {
19.1100 + return new Itr();
19.1101 + }
19.1102 +
19.1103 + /**
19.1104 + * An optimized version of AbstractList.Itr
19.1105 + */
19.1106 + private class Itr implements Iterator<E> {
19.1107 + int cursor; // index of next element to return
19.1108 + int lastRet = -1; // index of last element returned; -1 if no such
19.1109 + int expectedModCount = modCount;
19.1110 +
19.1111 + public boolean hasNext() {
19.1112 + // Racy but within spec, since modifications are checked
19.1113 + // within or after synchronization in next/previous
19.1114 + return cursor != elementCount;
19.1115 + }
19.1116 +
19.1117 + public E next() {
19.1118 + synchronized (Vector.this) {
19.1119 + checkForComodification();
19.1120 + int i = cursor;
19.1121 + if (i >= elementCount)
19.1122 + throw new NoSuchElementException();
19.1123 + cursor = i + 1;
19.1124 + return elementData(lastRet = i);
19.1125 + }
19.1126 + }
19.1127 +
19.1128 + public void remove() {
19.1129 + if (lastRet == -1)
19.1130 + throw new IllegalStateException();
19.1131 + synchronized (Vector.this) {
19.1132 + checkForComodification();
19.1133 + Vector.this.remove(lastRet);
19.1134 + expectedModCount = modCount;
19.1135 + }
19.1136 + cursor = lastRet;
19.1137 + lastRet = -1;
19.1138 + }
19.1139 +
19.1140 + final void checkForComodification() {
19.1141 + if (modCount != expectedModCount)
19.1142 + throw new ConcurrentModificationException();
19.1143 + }
19.1144 + }
19.1145 +
19.1146 + /**
19.1147 + * An optimized version of AbstractList.ListItr
19.1148 + */
19.1149 + final class ListItr extends Itr implements ListIterator<E> {
19.1150 + ListItr(int index) {
19.1151 + super();
19.1152 + cursor = index;
19.1153 + }
19.1154 +
19.1155 + public boolean hasPrevious() {
19.1156 + return cursor != 0;
19.1157 + }
19.1158 +
19.1159 + public int nextIndex() {
19.1160 + return cursor;
19.1161 + }
19.1162 +
19.1163 + public int previousIndex() {
19.1164 + return cursor - 1;
19.1165 + }
19.1166 +
19.1167 + public E previous() {
19.1168 + synchronized (Vector.this) {
19.1169 + checkForComodification();
19.1170 + int i = cursor - 1;
19.1171 + if (i < 0)
19.1172 + throw new NoSuchElementException();
19.1173 + cursor = i;
19.1174 + return elementData(lastRet = i);
19.1175 + }
19.1176 + }
19.1177 +
19.1178 + public void set(E e) {
19.1179 + if (lastRet == -1)
19.1180 + throw new IllegalStateException();
19.1181 + synchronized (Vector.this) {
19.1182 + checkForComodification();
19.1183 + Vector.this.set(lastRet, e);
19.1184 + }
19.1185 + }
19.1186 +
19.1187 + public void add(E e) {
19.1188 + int i = cursor;
19.1189 + synchronized (Vector.this) {
19.1190 + checkForComodification();
19.1191 + Vector.this.add(i, e);
19.1192 + expectedModCount = modCount;
19.1193 + }
19.1194 + cursor = i + 1;
19.1195 + lastRet = -1;
19.1196 + }
19.1197 + }
19.1198 +}
20.1 --- a/emul/compact/src/test/java/org/apidesign/bck2brwsr/compact/tck/CollectionsTest.java Fri Jan 25 16:46:14 2013 +0100
20.2 +++ b/emul/compact/src/test/java/org/apidesign/bck2brwsr/compact/tck/CollectionsTest.java Mon Jan 28 18:14:00 2013 +0100
20.3 @@ -25,6 +25,8 @@
20.4 import java.util.HashSet;
20.5 import java.util.List;
20.6 import java.util.Map;
20.7 +import java.util.Map.Entry;
20.8 +import java.util.Vector;
20.9 import org.apidesign.bck2brwsr.vmtest.Compare;
20.10 import org.apidesign.bck2brwsr.vmtest.VMTest;
20.11 import org.testng.annotations.Factory;
20.12 @@ -92,10 +94,9 @@
20.13 map.put("nine", 9);
20.14 map.put("ten", 10);
20.15
20.16 - Map.Entry<String,Integer>[] arr = map.entrySet().toArray(new Map.Entry[map.size()]);
20.17 - Arrays.sort(arr, new C());
20.18 -
20.19 - return Arrays.asList(arr).toString();
20.20 + List<Entry<String,Integer>> arr = new Vector<>();
20.21 + arr.addAll(map.entrySet());
20.22 + return arr.toString();
20.23 }
20.24
20.25 @Factory
21.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
21.2 +++ b/emul/compact/src/test/java/org/apidesign/bck2brwsr/compact/tck/RandomTest.java Mon Jan 28 18:14:00 2013 +0100
21.3 @@ -0,0 +1,40 @@
21.4 +/**
21.5 + * Back 2 Browser Bytecode Translator
21.6 + * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
21.7 + *
21.8 + * This program is free software: you can redistribute it and/or modify
21.9 + * it under the terms of the GNU General Public License as published by
21.10 + * the Free Software Foundation, version 2 of the License.
21.11 + *
21.12 + * This program is distributed in the hope that it will be useful,
21.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
21.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21.15 + * GNU General Public License for more details.
21.16 + *
21.17 + * You should have received a copy of the GNU General Public License
21.18 + * along with this program. Look for COPYING file in the top folder.
21.19 + * If not, see http://opensource.org/licenses/GPL-2.0.
21.20 + */
21.21 +package org.apidesign.bck2brwsr.compact.tck;
21.22 +
21.23 +import java.util.Random;
21.24 +import org.apidesign.bck2brwsr.vmtest.Compare;
21.25 +import org.apidesign.bck2brwsr.vmtest.VMTest;
21.26 +import org.testng.annotations.Factory;
21.27 +
21.28 +/**
21.29 + *
21.30 + * @author Jaroslav Tulach <jtulach@netbeans.org>
21.31 + */
21.32 +public class RandomTest {
21.33 + @Compare public boolean canInstantiateRandom() {
21.34 + Random r = new Random();
21.35 + r.nextInt();
21.36 + return r != null;
21.37 + }
21.38 +
21.39 +
21.40 + @Factory public static Object[] create() {
21.41 + return VMTest.create(RandomTest.class);
21.42 + }
21.43 +}
22.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
22.2 +++ b/emul/compact/src/test/java/org/apidesign/bck2brwsr/compact/tck/ReaderTest.java Mon Jan 28 18:14:00 2013 +0100
22.3 @@ -0,0 +1,60 @@
22.4 +/**
22.5 + * Back 2 Browser Bytecode Translator
22.6 + * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
22.7 + *
22.8 + * This program is free software: you can redistribute it and/or modify
22.9 + * it under the terms of the GNU General Public License as published by
22.10 + * the Free Software Foundation, version 2 of the License.
22.11 + *
22.12 + * This program is distributed in the hope that it will be useful,
22.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
22.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22.15 + * GNU General Public License for more details.
22.16 + *
22.17 + * You should have received a copy of the GNU General Public License
22.18 + * along with this program. Look for COPYING file in the top folder.
22.19 + * If not, see http://opensource.org/licenses/GPL-2.0.
22.20 + */
22.21 +package org.apidesign.bck2brwsr.compact.tck;
22.22 +
22.23 +import java.io.ByteArrayInputStream;
22.24 +import java.io.IOException;
22.25 +import java.io.InputStreamReader;
22.26 +import java.util.Arrays;
22.27 +import org.apidesign.bck2brwsr.vmtest.Compare;
22.28 +import org.apidesign.bck2brwsr.vmtest.VMTest;
22.29 +import org.testng.annotations.Factory;
22.30 +
22.31 +/**
22.32 + *
22.33 + * @author Jaroslav Tulach <jtulach@netbeans.org>
22.34 + */
22.35 +public class ReaderTest {
22.36 + @Compare public String readUTFString() throws IOException {
22.37 + byte[] arr = {
22.38 + (byte)-59, (byte)-67, (byte)108, (byte)117, (byte)-59, (byte)-91,
22.39 + (byte)111, (byte)117, (byte)-60, (byte)-115, (byte)107, (byte)-61,
22.40 + (byte)-67, (byte)32, (byte)107, (byte)-59, (byte)-81, (byte)-59,
22.41 + (byte)-120
22.42 + };
22.43 + ByteArrayInputStream is = new ByteArrayInputStream(arr);
22.44 + InputStreamReader r = new InputStreamReader(is);
22.45 +
22.46 + StringBuilder sb = new StringBuilder();
22.47 + for (;;) {
22.48 + int ch = r.read();
22.49 + if (ch == -1) {
22.50 + break;
22.51 + }
22.52 + sb.append((char)ch);
22.53 + }
22.54 + return sb.toString().toString();
22.55 + }
22.56 + @Compare public String stringToBytes() {
22.57 + return Arrays.toString("Žluťoučký kůň".getBytes());
22.58 + }
22.59 +
22.60 + @Factory public static Object[] create() {
22.61 + return VMTest.create(ReaderTest.class);
22.62 + }
22.63 +}
23.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
23.2 +++ b/emul/mini/src/main/java/java/lang/ArrayStoreException.java Mon Jan 28 18:14:00 2013 +0100
23.3 @@ -0,0 +1,60 @@
23.4 +/*
23.5 + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
23.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
23.7 + *
23.8 + * This code is free software; you can redistribute it and/or modify it
23.9 + * under the terms of the GNU General Public License version 2 only, as
23.10 + * published by the Free Software Foundation. Oracle designates this
23.11 + * particular file as subject to the "Classpath" exception as provided
23.12 + * by Oracle in the LICENSE file that accompanied this code.
23.13 + *
23.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
23.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
23.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
23.17 + * version 2 for more details (a copy is included in the LICENSE file that
23.18 + * accompanied this code).
23.19 + *
23.20 + * You should have received a copy of the GNU General Public License version
23.21 + * 2 along with this work; if not, write to the Free Software Foundation,
23.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
23.23 + *
23.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23.25 + * or visit www.oracle.com if you need additional information or have any
23.26 + * questions.
23.27 + */
23.28 +
23.29 +package java.lang;
23.30 +
23.31 +/**
23.32 + * Thrown to indicate that an attempt has been made to store the
23.33 + * wrong type of object into an array of objects. For example, the
23.34 + * following code generates an <code>ArrayStoreException</code>:
23.35 + * <p><blockquote><pre>
23.36 + * Object x[] = new String[3];
23.37 + * x[0] = new Integer(0);
23.38 + * </pre></blockquote>
23.39 + *
23.40 + * @author unascribed
23.41 + * @since JDK1.0
23.42 + */
23.43 +public
23.44 +class ArrayStoreException extends RuntimeException {
23.45 + private static final long serialVersionUID = -4522193890499838241L;
23.46 +
23.47 + /**
23.48 + * Constructs an <code>ArrayStoreException</code> with no detail message.
23.49 + */
23.50 + public ArrayStoreException() {
23.51 + super();
23.52 + }
23.53 +
23.54 + /**
23.55 + * Constructs an <code>ArrayStoreException</code> with the specified
23.56 + * detail message.
23.57 + *
23.58 + * @param s the detail message.
23.59 + */
23.60 + public ArrayStoreException(String s) {
23.61 + super(s);
23.62 + }
23.63 +}
24.1 --- a/emul/mini/src/main/java/java/lang/Math.java Fri Jan 25 16:46:14 2013 +0100
24.2 +++ b/emul/mini/src/main/java/java/lang/Math.java Mon Jan 28 18:14:00 2013 +0100
24.3 @@ -375,6 +375,68 @@
24.4 public static double floor(double a) {
24.5 throw new UnsupportedOperationException();
24.6 }
24.7 + /**
24.8 + * Computes the remainder operation on two arguments as prescribed
24.9 + * by the IEEE 754 standard.
24.10 + * The remainder value is mathematically equal to
24.11 + * <code>f1 - f2</code> × <i>n</i>,
24.12 + * where <i>n</i> is the mathematical integer closest to the exact
24.13 + * mathematical value of the quotient {@code f1/f2}, and if two
24.14 + * mathematical integers are equally close to {@code f1/f2},
24.15 + * then <i>n</i> is the integer that is even. If the remainder is
24.16 + * zero, its sign is the same as the sign of the first argument.
24.17 + * Special cases:
24.18 + * <ul><li>If either argument is NaN, or the first argument is infinite,
24.19 + * or the second argument is positive zero or negative zero, then the
24.20 + * result is NaN.
24.21 + * <li>If the first argument is finite and the second argument is
24.22 + * infinite, then the result is the same as the first argument.</ul>
24.23 + *
24.24 + * @param f1 the dividend.
24.25 + * @param f2 the divisor.
24.26 + * @return the remainder when {@code f1} is divided by
24.27 + * {@code f2}.
24.28 + */
24.29 +// public static double IEEEremainder(double f1, double f2) {
24.30 +// return f1 % f2;
24.31 +// }
24.32 +
24.33 + /**
24.34 + * Returns the {@code double} value that is closest in value
24.35 + * to the argument and is equal to a mathematical integer. If two
24.36 + * {@code double} values that are mathematical integers are
24.37 + * equally close, the result is the integer value that is
24.38 + * even. Special cases:
24.39 + * <ul><li>If the argument value is already equal to a mathematical
24.40 + * integer, then the result is the same as the argument.
24.41 + * <li>If the argument is NaN or an infinity or positive zero or negative
24.42 + * zero, then the result is the same as the argument.</ul>
24.43 + *
24.44 + * @param a a {@code double} value.
24.45 + * @return the closest floating-point value to {@code a} that is
24.46 + * equal to a mathematical integer.
24.47 + */
24.48 + public static double rint(double a) {
24.49 + double ceil = ceil(a);
24.50 + double floor = floor(a);
24.51 +
24.52 + double dc = ceil - a;
24.53 + double df = a - floor;
24.54 +
24.55 + if (dc < df) {
24.56 + return ceil;
24.57 + } else if (dc > df) {
24.58 + return floor;
24.59 + }
24.60 +
24.61 + int tenC = (int) (ceil % 10.0);
24.62 +
24.63 + if (tenC % 2 == 0) {
24.64 + return ceil;
24.65 + } else {
24.66 + return floor;
24.67 + }
24.68 + }
24.69
24.70 /**
24.71 * Returns the angle <i>theta</i> from the conversion of rectangular
25.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
25.2 +++ b/emul/mini/src/main/java/java/lang/Override.java Mon Jan 28 18:14:00 2013 +0100
25.3 @@ -0,0 +1,52 @@
25.4 +/*
25.5 + * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
25.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
25.7 + *
25.8 + * This code is free software; you can redistribute it and/or modify it
25.9 + * under the terms of the GNU General Public License version 2 only, as
25.10 + * published by the Free Software Foundation. Oracle designates this
25.11 + * particular file as subject to the "Classpath" exception as provided
25.12 + * by Oracle in the LICENSE file that accompanied this code.
25.13 + *
25.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
25.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
25.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
25.17 + * version 2 for more details (a copy is included in the LICENSE file that
25.18 + * accompanied this code).
25.19 + *
25.20 + * You should have received a copy of the GNU General Public License version
25.21 + * 2 along with this work; if not, write to the Free Software Foundation,
25.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
25.23 + *
25.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
25.25 + * or visit www.oracle.com if you need additional information or have any
25.26 + * questions.
25.27 + */
25.28 +
25.29 +package java.lang;
25.30 +
25.31 +import java.lang.annotation.*;
25.32 +
25.33 +/**
25.34 + * Indicates that a method declaration is intended to override a
25.35 + * method declaration in a supertype. If a method is annotated with
25.36 + * this annotation type compilers are required to generate an error
25.37 + * message unless at least one of the following conditions hold:
25.38 + *
25.39 + * <ul><li>
25.40 + * The method does override or implement a method declared in a
25.41 + * supertype.
25.42 + * </li><li>
25.43 + * The method has a signature that is override-equivalent to that of
25.44 + * any public method declared in {@linkplain Object}.
25.45 + * </li></ul>
25.46 + *
25.47 + * @author Peter von der Ahé
25.48 + * @author Joshua Bloch
25.49 + * @jls 9.6.1.4 Override
25.50 + * @since 1.5
25.51 + */
25.52 +@Target(ElementType.METHOD)
25.53 +@Retention(RetentionPolicy.SOURCE)
25.54 +public @interface Override {
25.55 +}
26.1 --- a/emul/mini/src/main/java/java/lang/String.java Fri Jan 25 16:46:14 2013 +0100
26.2 +++ b/emul/mini/src/main/java/java/lang/String.java Mon Jan 28 18:14:00 2013 +0100
26.3 @@ -115,7 +115,7 @@
26.4 /** use serialVersionUID from JDK 1.0.2 for interoperability */
26.5 private static final long serialVersionUID = -6849794470754667710L;
26.6
26.7 - @JavaScriptOnly(name="toString", value="function() { return this.fld_r; }")
26.8 + @JavaScriptOnly(name="toString", value="String.prototype._r")
26.9 private static void jsToString() {
26.10 }
26.11
26.12 @@ -174,7 +174,7 @@
26.13 "for (var i = 0; i < charArr.length; i++) {\n"
26.14 + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n"
26.15 + "}\n"
26.16 - + "this.fld_r = charArr.join('');\n"
26.17 + + "this._r(charArr.join(''));\n"
26.18 )
26.19 public String(char value[]) {
26.20 }
26.21 @@ -205,7 +205,7 @@
26.22 "for (var i = off; i < up; i++) {\n" +
26.23 " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" +
26.24 "}\n" +
26.25 - "this.fld_r = charArr.slice(off, up).join(\"\");\n"
26.26 + "this._r(charArr.slice(off, up).join(\"\"));\n"
26.27 )
26.28 public String(char value[], int offset, int count) {
26.29 }
26.30 @@ -971,10 +971,24 @@
26.31 * @since JDK1.1
26.32 */
26.33 public byte[] getBytes() {
26.34 - byte[] arr = new byte[length()];
26.35 - for (int i = 0; i < arr.length; i++) {
26.36 - final char v = charAt(i);
26.37 - arr[i] = (byte)v;
26.38 + int len = length();
26.39 + byte[] arr = new byte[len];
26.40 + for (int i = 0, j = 0; j < len; j++) {
26.41 + final int v = charAt(j);
26.42 + if (v < 128) {
26.43 + arr[i++] = (byte) v;
26.44 + continue;
26.45 + }
26.46 + if (v < 0x0800) {
26.47 + arr = System.expandArray(arr, i + 1);
26.48 + arr[i++] = (byte) (0xC0 | (v >> 6));
26.49 + arr[i++] = (byte) (0x80 | (0x3F & v));
26.50 + continue;
26.51 + }
26.52 + arr = System.expandArray(arr, i + 2);
26.53 + arr[i++] = (byte) (0xE0 | (v >> 12));
26.54 + arr[i++] = (byte) (0x80 | ((v >> 6) & 0x7F));
26.55 + arr[i++] = (byte) (0x80 | (0x3F & v));
26.56 }
26.57 return arr;
26.58 }
27.1 --- a/emul/mini/src/main/java/java/lang/reflect/Method.java Fri Jan 25 16:46:14 2013 +0100
27.2 +++ b/emul/mini/src/main/java/java/lang/reflect/Method.java Mon Jan 28 18:14:00 2013 +0100
27.3 @@ -533,7 +533,7 @@
27.4 + "} else {\n"
27.5 + " p = args;\n"
27.6 + "}\n"
27.7 - + "return method.fld_data.apply(self, p);\n"
27.8 + + "return method._data().apply(self, p);\n"
27.9 )
27.10 private static native Object invoke0(boolean isStatic, Method m, Object self, Object[] args);
27.11
27.12 @@ -648,8 +648,9 @@
27.13
27.14 @JavaScriptBody(args = { "ac" },
27.15 body =
27.16 - "if (this.fld_data.anno) {"
27.17 - + " return this.fld_data.anno['L' + ac.jvmName + ';'];"
27.18 + "var a = this._data().anno;"
27.19 + + "if (a) {"
27.20 + + " return a['L' + ac.jvmName + ';'];"
27.21 + "} else return null;"
27.22 )
27.23 private Object getAnnotationData(Class<?> annotationClass) {
28.1 --- a/emul/mini/src/main/java/org/apidesign/bck2brwsr/emul/lang/System.java Fri Jan 25 16:46:14 2013 +0100
28.2 +++ b/emul/mini/src/main/java/org/apidesign/bck2brwsr/emul/lang/System.java Mon Jan 28 18:14:00 2013 +0100
28.3 @@ -39,4 +39,12 @@
28.4 "}"
28.5 )
28.6 public static native void arraycopy(Object value, int srcBegin, Object dst, int dstBegin, int count);
28.7 +
28.8 + @JavaScriptBody(args = { "arr", "expectedSize" }, body =
28.9 + "while (expectedSize-- > arr.length) { arr.push(0); }; return arr;"
28.10 + )
28.11 + public static native byte[] expandArray(byte[] arr, int expectedSize);
28.12 +
28.13 + @JavaScriptBody(args = {}, body = "new Date().getMilliseconds() * 1000;")
28.14 + public static native long nanoTime();
28.15 }
29.1 --- a/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/Canvas.java Fri Jan 25 16:46:14 2013 +0100
29.2 +++ b/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/Canvas.java Mon Jan 28 18:14:00 2013 +0100
29.3 @@ -47,7 +47,7 @@
29.4
29.5 @JavaScriptBody(
29.6 args = {"el"},
29.7 - body = "var e = window.document.getElementById(el.fld_id);\n"
29.8 + body = "var e = window.document.getElementById(el._id());\n"
29.9 + "return e.getContext('2d');\n")
29.10 private native static Object getContextImpl(Canvas el);
29.11
30.1 --- a/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/Element.java Fri Jan 25 16:46:14 2013 +0100
30.2 +++ b/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/Element.java Mon Jan 28 18:14:00 2013 +0100
30.3 @@ -41,21 +41,21 @@
30.4
30.5 @JavaScriptBody(
30.6 args={"el", "property", "value"},
30.7 - body="var e = window.document.getElementById(el.fld_id);\n"
30.8 + body="var e = window.document.getElementById(el._id());\n"
30.9 + "e[property] = value;\n"
30.10 )
30.11 static native void setAttribute(Element el, String property, Object value);
30.12
30.13 @JavaScriptBody(
30.14 args={"el", "property"},
30.15 - body="var e = window.document.getElementById(el.fld_id);\n"
30.16 + body="var e = window.document.getElementById(el._id());\n"
30.17 + "return e[property];\n"
30.18 )
30.19 static native Object getAttribute(Element el, String property);
30.20
30.21 @JavaScriptBody(
30.22 args={"el"},
30.23 - body="return window.document.getElementById(el.fld_id);"
30.24 + body="return window.document.getElementById(el._id());"
30.25 )
30.26 static native Object getElementById(Element el);
30.27
30.28 @@ -65,8 +65,8 @@
30.29 */
30.30 @JavaScriptBody(
30.31 args={ "ev", "r" },
30.32 - body="var e = window.document.getElementById(this.fld_id);\n"
30.33 - + "e[ev.fld_id] = function() { r.run__V(); };\n"
30.34 + body="var e = window.document.getElementById(this._id());\n"
30.35 + + "e[ev._id()] = function() { r.run__V(); };\n"
30.36 )
30.37 final void on(OnEvent ev, Runnable r) {
30.38 }
31.1 --- a/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/GraphicsContext.java Fri Jan 25 16:46:14 2013 +0100
31.2 +++ b/javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/api/GraphicsContext.java Mon Jan 28 18:14:00 2013 +0100
31.3 @@ -32,7 +32,7 @@
31.4 }
31.5
31.6 @JavaScriptBody(args = {"centerx", "centery", "radius", "startangle", "endangle", "ccw"},
31.7 - body = "this.fld_context.arc(centerx,centery, radius, startangle, endangle,ccw);")
31.8 + body = "this._context().arc(centerx,centery, radius, startangle, endangle,ccw);")
31.9 public native void arc(double centerX,
31.10 double centerY,
31.11 double startAngle,
31.12 @@ -41,7 +41,7 @@
31.13 boolean ccw);
31.14
31.15 @JavaScriptBody(args = {"x1", "y1", "x2", "y2", "r"},
31.16 - body = "this.fld_context.arcTo(x1,y1,x2,y2,r);")
31.17 + body = "this._context().arcTo(x1,y1,x2,y2,r);")
31.18 public native void arcTo(double x1,
31.19 double y1,
31.20 double x2,
31.21 @@ -49,68 +49,68 @@
31.22 double r);
31.23
31.24 @JavaScriptBody(args = {"x", "y"},
31.25 - body = "return this.fld_context.isPointInPath(x,y);")
31.26 + body = "return this._context().isPointInPath(x,y);")
31.27 public native boolean isPointInPath(double x, double y);
31.28
31.29 - @JavaScriptBody(args = {}, body = "this.fld_context.fill();")
31.30 + @JavaScriptBody(args = {}, body = "this._context().fill();")
31.31 public native void fill();
31.32
31.33 - @JavaScriptBody(args = {}, body = "this.fld_context.stroke();")
31.34 + @JavaScriptBody(args = {}, body = "this._context().stroke();")
31.35 public native void stroke();
31.36
31.37 - @JavaScriptBody(args = {}, body = "this.fld_context.beginPath();")
31.38 + @JavaScriptBody(args = {}, body = "this._context().beginPath();")
31.39 public native void beginPath();
31.40
31.41 - @JavaScriptBody(args = {}, body = "this.fld_context.closePath();")
31.42 + @JavaScriptBody(args = {}, body = "this._context().closePath();")
31.43 public native void closePath();
31.44
31.45 - @JavaScriptBody(args = {}, body = "this.fld_context.clip();")
31.46 + @JavaScriptBody(args = {}, body = "this._context().clip();")
31.47 public native void clip();
31.48
31.49 - @JavaScriptBody(args = {"x", "y"}, body = "this.fld_context.moveTo(x,y);")
31.50 + @JavaScriptBody(args = {"x", "y"}, body = "this._context().moveTo(x,y);")
31.51 public native void moveTo(double x, double y);
31.52
31.53 - @JavaScriptBody(args = {"x", "y"}, body = "this.fld_context.lineTo(x,y);")
31.54 + @JavaScriptBody(args = {"x", "y"}, body = "this._context().lineTo(x,y);")
31.55 public native void lineTo(double x, double y);
31.56
31.57 - @JavaScriptBody(args = {"cpx", "cpy", "x", "y"}, body = "this.fld_context.quadraticCurveTo(cpx,cpy,x,y);")
31.58 + @JavaScriptBody(args = {"cpx", "cpy", "x", "y"}, body = "this._context().quadraticCurveTo(cpx,cpy,x,y);")
31.59 public native void quadraticCurveTo(double cpx, double cpy, double x, double y);
31.60
31.61 @JavaScriptBody(args = {"cp1x", "cp1y", "cp2x", "cp2y", "x", "y"},
31.62 - body = "this.fld_context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y);")
31.63 + body = "this._context().bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y);")
31.64 public native void bezierCurveTo(double cp1x, double cp1y, double cp2x, double cp2y, double x, double y);
31.65
31.66 - @JavaScriptBody(args = {"x", "y", "width", "height"}, body = "this.fld_context.fillRect(x,y,width,height);")
31.67 + @JavaScriptBody(args = {"x", "y", "width", "height"}, body = "this._context().fillRect(x,y,width,height);")
31.68 public native void fillRect(double x, double y, double width, double height);
31.69
31.70 - @JavaScriptBody(args = {"x", "y", "width", "height"}, body = "this.fld_context.strokeRect(x,y,width,height);")
31.71 + @JavaScriptBody(args = {"x", "y", "width", "height"}, body = "this._context().strokeRect(x,y,width,height);")
31.72 public native void strokeRect(double x, double y, double width, double height);
31.73
31.74 - @JavaScriptBody(args = {"x", "y", "width", "height"}, body = "this.fld_context.clearRect(x,y,width,height);")
31.75 + @JavaScriptBody(args = {"x", "y", "width", "height"}, body = "this._context().clearRect(x,y,width,height);")
31.76 public native void clearRect(double x, double y, double width, double height);
31.77
31.78 - @JavaScriptBody(args = {"x", "y", "width", "height"}, body = "this.fld_context.rectect(x,y,width,height);")
31.79 + @JavaScriptBody(args = {"x", "y", "width", "height"}, body = "this._context().rectect(x,y,width,height);")
31.80 public native void rect(double x, double y, double width, double height);
31.81
31.82 - @JavaScriptBody(args = {}, body = "this.fld_context.save();")
31.83 + @JavaScriptBody(args = {}, body = "this._context().save();")
31.84 public native void save();
31.85
31.86 - @JavaScriptBody(args = {}, body = "this.fld_context.restore();")
31.87 + @JavaScriptBody(args = {}, body = "this._context().restore();")
31.88 public native void restore();
31.89
31.90 - @JavaScriptBody(args = {"angle"}, body = "this.fld_context.rotate(angle);")
31.91 + @JavaScriptBody(args = {"angle"}, body = "this._context().rotate(angle);")
31.92 public native void rotate(double angle);
31.93
31.94 - @JavaScriptBody(args = {"a", "b", "c", "d", "e", "f"}, body = "this.fld_context.transform(a,b,c,d,e,f);")
31.95 + @JavaScriptBody(args = {"a", "b", "c", "d", "e", "f"}, body = "this._context().transform(a,b,c,d,e,f);")
31.96 public native void transform(double a, double b, double c, double d, double e, double f);
31.97
31.98 - @JavaScriptBody(args = {"a", "b", "c", "d", "e", "f"}, body = "this.fld_context.setTransform(a,b,c,d,e,f);")
31.99 + @JavaScriptBody(args = {"a", "b", "c", "d", "e", "f"}, body = "this._context().setTransform(a,b,c,d,e,f);")
31.100 public native void setTransform(double a, double b, double c, double d, double e, double f);
31.101
31.102 - @JavaScriptBody(args = {"x", "y"}, body = "this.fld_context.translate(x,y);")
31.103 + @JavaScriptBody(args = {"x", "y"}, body = "this._context().translate(x,y);")
31.104 public native void translate(double x, double y);
31.105
31.106 - @JavaScriptBody(args = {"x", "y"}, body = "this.fld_context.scale(x,y);")
31.107 + @JavaScriptBody(args = {"x", "y"}, body = "this._context().scale(x,y);")
31.108 public native void scale(double x, double y);
31.109
31.110 public void drawImage(Image image, double x, double y) {
31.111 @@ -134,10 +134,10 @@
31.112 @JavaScriptBody(args = {"ctx", "img", "x", "y"}, body = "ctx.drawImage(img,x,y);")
31.113 private native static void drawImageImpl(Object ctx, Object img, double x, double y);
31.114
31.115 - @JavaScriptBody(args = {"style"}, body = "this.fld_context.fillStyle=style;")
31.116 + @JavaScriptBody(args = {"style"}, body = "this._context().fillStyle=style;")
31.117 public native void setFillStyle(String style);
31.118
31.119 - @JavaScriptBody(args = {}, body = "return this.fld_context.fillStyle;")
31.120 + @JavaScriptBody(args = {}, body = "return this._context().fillStyle;")
31.121 public native String getFillStyle();
31.122
31.123 public void setFillStyle(LinearGradient style) {
31.124 @@ -155,7 +155,7 @@
31.125 @JavaScriptBody(args = {"context","obj"}, body = "context.fillStyle=obj;")
31.126 private native void setFillStyleImpl(Object context, Object obj);
31.127
31.128 - @JavaScriptBody(args = {"style"}, body = "this.fld_context.strokeStyle=style;")
31.129 + @JavaScriptBody(args = {"style"}, body = "this._context().strokeStyle=style;")
31.130 public native void setStrokeStyle(String style);
31.131
31.132 public void setStrokeStyle(LinearGradient style) {
31.133 @@ -166,7 +166,7 @@
31.134 setStrokeStyleImpl(context, style.object());
31.135 }
31.136
31.137 - @JavaScriptBody(args = {"style"}, body = "this.fld_context.fillStyle=style;")
31.138 + @JavaScriptBody(args = {"style"}, body = "this._context().fillStyle=style;")
31.139 public void setStrokeStyle(Pattern style) {
31.140 setStrokeStyleImpl(context, style.object());
31.141 }
31.142 @@ -174,79 +174,79 @@
31.143 @JavaScriptBody(args = {"context","obj"}, body = "context.strokeStyle=obj;")
31.144 private native void setStrokeStyleImpl(Object context, Object obj);
31.145
31.146 - @JavaScriptBody(args = {"color"}, body = "this.fld_context.shadowColor=color;")
31.147 + @JavaScriptBody(args = {"color"}, body = "this._context().shadowColor=color;")
31.148 public native void setShadowColor(String color);
31.149
31.150 - @JavaScriptBody(args = {"blur"}, body = "this.fld_context.shadowBlur=blur;")
31.151 + @JavaScriptBody(args = {"blur"}, body = "this._context().shadowBlur=blur;")
31.152 public native void setShadowBlur(double blur);
31.153
31.154 - @JavaScriptBody(args = {"x"}, body = "this.fld_context.shadowOffsetX=x;")
31.155 + @JavaScriptBody(args = {"x"}, body = "this._context().shadowOffsetX=x;")
31.156 public native void setShadowOffsetX(double x);
31.157
31.158 - @JavaScriptBody(args = {"y"}, body = "this.fld_context.shadowOffsetY=y;")
31.159 + @JavaScriptBody(args = {"y"}, body = "this._context().shadowOffsetY=y;")
31.160 public native void setShadowOffsetY(double y);
31.161
31.162 - @JavaScriptBody(args = {}, body = "return this.fld_context.strokeStyle;")
31.163 + @JavaScriptBody(args = {}, body = "return this._context().strokeStyle;")
31.164 public native String getStrokeStyle();
31.165
31.166 - @JavaScriptBody(args = {}, body = "return this.fld_context.shadowColor;")
31.167 + @JavaScriptBody(args = {}, body = "return this._context().shadowColor;")
31.168 public native String getShadowColor();
31.169
31.170 - @JavaScriptBody(args = {}, body = "return this.fld_context.shadowBlur;")
31.171 + @JavaScriptBody(args = {}, body = "return this._context().shadowBlur;")
31.172 public native double getShadowBlur();
31.173
31.174 - @JavaScriptBody(args = {}, body = "return this.fld_context.shadowOffsetX;")
31.175 + @JavaScriptBody(args = {}, body = "return this._context().shadowOffsetX;")
31.176 public native double getShadowOffsetX();
31.177
31.178 - @JavaScriptBody(args = {}, body = "return this.fld_context.shadowOffsetY;")
31.179 + @JavaScriptBody(args = {}, body = "return this._context().shadowOffsetY;")
31.180 public native double getShadowOffsetY();
31.181
31.182 - @JavaScriptBody(args = {}, body = "return this.fld_context.lineCap;")
31.183 + @JavaScriptBody(args = {}, body = "return this._context().lineCap;")
31.184 public native String getLineCap();
31.185
31.186 - @JavaScriptBody(args = {"style"}, body = "this.fld_context.lineCap=style;")
31.187 + @JavaScriptBody(args = {"style"}, body = "this._context().lineCap=style;")
31.188 public native void setLineCap(String style);
31.189
31.190 - @JavaScriptBody(args = {}, body = "return this.fld_context.lineJoin;")
31.191 + @JavaScriptBody(args = {}, body = "return this._context().lineJoin;")
31.192 public native String getLineJoin();
31.193
31.194 - @JavaScriptBody(args = {"style"}, body = "this.fld_context.lineJoin=style;")
31.195 + @JavaScriptBody(args = {"style"}, body = "this._context().lineJoin=style;")
31.196 public native void setLineJoin(String style) ;
31.197
31.198 - @JavaScriptBody(args = {}, body = "return this.fld_context.lineWidth;")
31.199 + @JavaScriptBody(args = {}, body = "return this._context().lineWidth;")
31.200 public native double getLineWidth();
31.201
31.202 - @JavaScriptBody(args = {"width"}, body = "this.fld_context.lineJoin=width;")
31.203 + @JavaScriptBody(args = {"width"}, body = "this._context().lineJoin=width;")
31.204 public native void setLineWidth(double width);
31.205
31.206 - @JavaScriptBody(args = {}, body = "return this.fld_context.miterLimit;")
31.207 + @JavaScriptBody(args = {}, body = "return this._context().miterLimit;")
31.208 public native double getMiterLimit();
31.209
31.210 - @JavaScriptBody(args = {"limit"}, body = "this.fld_context.miterLimit=limit;")
31.211 + @JavaScriptBody(args = {"limit"}, body = "this._context().miterLimit=limit;")
31.212 public native void setMiterLimit(double limit);
31.213
31.214 - @JavaScriptBody(args = {}, body = "return this.fld_context.font;")
31.215 + @JavaScriptBody(args = {}, body = "return this._context().font;")
31.216 public native String getFont();
31.217
31.218 - @JavaScriptBody(args = {"font"}, body = "this.fld_context.font=font;")
31.219 + @JavaScriptBody(args = {"font"}, body = "this._context().font=font;")
31.220 public native void setFont(String font);
31.221
31.222 - @JavaScriptBody(args = {}, body = "return this.fld_context.textAlign;")
31.223 + @JavaScriptBody(args = {}, body = "return this._context().textAlign;")
31.224 public native String getTextAlign();
31.225
31.226 - @JavaScriptBody(args = {"textalign"}, body = "this.fld_context.textAlign=textalign;")
31.227 + @JavaScriptBody(args = {"textalign"}, body = "this._context().textAlign=textalign;")
31.228 public native void setTextAlign(String textAlign);
31.229
31.230 - @JavaScriptBody(args = {}, body = "return this.fld_context.textBaseline;")
31.231 + @JavaScriptBody(args = {}, body = "return this._context().textBaseline;")
31.232 public native String getTextBaseline();
31.233
31.234 - @JavaScriptBody(args = {"textbaseline"}, body = "this.fld_context.textBaseline=textbaseline;")
31.235 + @JavaScriptBody(args = {"textbaseline"}, body = "this._context().textBaseline=textbaseline;")
31.236 public native void setTextBaseline(String textbaseline);
31.237
31.238 - @JavaScriptBody(args = {"text", "x", "y"}, body = "this.fld_context.fillText(text,x,y);")
31.239 + @JavaScriptBody(args = {"text", "x", "y"}, body = "this._context().fillText(text,x,y);")
31.240 public native void fillText(String text, double x, double y);
31.241
31.242 - @JavaScriptBody(args = {"text", "x", "y", "maxwidth"}, body = "this.fld_context.fillText(text,x,y,maxwidth);")
31.243 + @JavaScriptBody(args = {"text", "x", "y", "maxwidth"}, body = "this._context().fillText(text,x,y,maxwidth);")
31.244 public void fillText(String text, double x, double y, double maxWidth) {
31.245 }
31.246
31.247 @@ -255,13 +255,13 @@
31.248 }
31.249
31.250 @JavaScriptBody(args = {"text"},
31.251 - body = "return this.fld_context.measureText(text);")
31.252 + body = "return this._context().measureText(text);")
31.253 private native Object measureTextImpl(String text);
31.254
31.255 - @JavaScriptBody(args = {"text", "x", "y"}, body = "this.fld_context.strokeText(text,x,y);")
31.256 + @JavaScriptBody(args = {"text", "x", "y"}, body = "this._context().strokeText(text,x,y);")
31.257 public native void strokeText(String text, double x, double y);
31.258
31.259 - @JavaScriptBody(args = {"text", "x", "y", "maxWidth"}, body = "this.fld_context.strokeText(text,x,y,maxWidth);")
31.260 + @JavaScriptBody(args = {"text", "x", "y", "maxWidth"}, body = "this._context().strokeText(text,x,y,maxWidth);")
31.261 public native void strokeText(String text, double x, double y, double maxWidth) ;
31.262
31.263 public ImageData createImageData(double x, double y) {
31.264 @@ -269,7 +269,7 @@
31.265 }
31.266
31.267 @JavaScriptBody(args = {"x", "y"},
31.268 - body = "return this.fld_context.createImageData(x,y);")
31.269 + body = "return this._context().createImageData(x,y);")
31.270 private native Object createImageDataImpl(double x, double y);
31.271
31.272 public ImageData createImageData(ImageData imageData) {
31.273 @@ -281,7 +281,7 @@
31.274 }
31.275
31.276 @JavaScriptBody(args = {"x", "y", "width", "height"},
31.277 - body = "return this.fld_context.getImageData(x,y,width,height);")
31.278 + body = "return this._context().getImageData(x,y,width,height);")
31.279 private native Object getImageDataImpl(double x, double y, double width, double height);
31.280
31.281 public void putImageData(ImageData imageData, double x, double y) {
31.282 @@ -289,7 +289,7 @@
31.283 }
31.284
31.285 @JavaScriptBody(args = {"imageData", "x", "y"},
31.286 - body = "this.fld_context.putImageData(imageData,x,y);")
31.287 + body = "this._context().putImageData(imageData,x,y);")
31.288 private native void putImageDataImpl(Object imageData, double x, double y);
31.289
31.290 public void putImageData(ImageData imageData, double x, double y, double dirtyx, double dirtyy, double dirtywidth, double dirtyheight) {
31.291 @@ -297,19 +297,19 @@
31.292 }
31.293
31.294 @JavaScriptBody(args = {"imageData", "x", "y", "dirtyx", "dirtyy", "dirtywidth", "dirtyheight"},
31.295 - body = "this.fld_context.putImageData(imageData,x,y, dirtyx, dirtyy, dirtywidth,dirtyheight);")
31.296 + body = "this._context().putImageData(imageData,x,y, dirtyx, dirtyy, dirtywidth,dirtyheight);")
31.297 private native void putImageDataImpl(Object imageData, double x, double y, double dirtyx, double dirtyy, double dirtywidth, double dirtyheight);
31.298
31.299 - @JavaScriptBody(args = {"alpha"}, body = "this.fld_context.globalAlpha=alpha;")
31.300 + @JavaScriptBody(args = {"alpha"}, body = "this._context().globalAlpha=alpha;")
31.301 public native void setGlobalAlpha(double alpha) ;
31.302
31.303 - @JavaScriptBody(args = {}, body = "return this.fld_context.globalAlpha;")
31.304 + @JavaScriptBody(args = {}, body = "return this._context().globalAlpha;")
31.305 public native double getGlobalAlpha();
31.306
31.307 - @JavaScriptBody(args = {"operation"}, body = "this.fld_context.globalCompositeOperation=operation;")
31.308 + @JavaScriptBody(args = {"operation"}, body = "this._context().globalCompositeOperation=operation;")
31.309 public native void setGlobalCompositeOperation(double alpha);
31.310
31.311 - @JavaScriptBody(args = {}, body = "return this.fld_context.globalCompositeOperation;")
31.312 + @JavaScriptBody(args = {}, body = "return this._context().globalCompositeOperation;")
31.313 public native double getGlobalCompositeOperation();
31.314
31.315 public LinearGradient createLinearGradient(double x0, double y0, double x1, double y1) {
32.1 --- a/launcher/src/main/java/org/apidesign/bck2brwsr/launcher/JSLauncher.java Fri Jan 25 16:46:14 2013 +0100
32.2 +++ b/launcher/src/main/java/org/apidesign/bck2brwsr/launcher/JSLauncher.java Mon Jan 28 18:14:00 2013 +0100
32.3 @@ -23,6 +23,7 @@
32.4 import java.util.Enumeration;
32.5 import java.util.LinkedHashSet;
32.6 import java.util.Set;
32.7 +import java.util.logging.Level;
32.8 import java.util.logging.Logger;
32.9 import javax.script.Invocable;
32.10 import javax.script.ScriptEngine;
32.11 @@ -46,10 +47,15 @@
32.12 loaders.add(clazz.getClassLoader());
32.13 MethodInvocation mi = new MethodInvocation(clazz.getName(), method, html);
32.14 try {
32.15 - mi.result(code.invokeMethod(
32.16 + long time = System.currentTimeMillis();
32.17 + LOG.log(Level.FINE, "Invoking {0}.{1}", new Object[]{mi.className, mi.methodName});
32.18 + String res = code.invokeMethod(
32.19 console,
32.20 "invoke__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2",
32.21 - mi.className, mi.methodName).toString(), null);
32.22 + mi.className, mi.methodName).toString();
32.23 + time = System.currentTimeMillis() - time;
32.24 + LOG.log(Level.FINE, "Resut of {0}.{1} = {2} in {3} ms", new Object[]{mi.className, mi.methodName, res, time});
32.25 + mi.result(res, null);
32.26 } catch (ScriptException | NoSuchMethodException ex) {
32.27 mi.result(null, ex);
32.28 }
33.1 --- a/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java Fri Jan 25 16:46:14 2013 +0100
33.2 +++ b/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java Mon Jan 28 18:14:00 2013 +0100
33.3 @@ -114,11 +114,6 @@
33.4 out.append("\n\n").append(assignClass(className));
33.5 out.append("function CLS() {");
33.6 out.append("\n if (!CLS.prototype.$instOf_").append(className).append(") {");
33.7 - for (FieldData v : jc.getFields()) {
33.8 - if (v.isStatic()) {
33.9 - out.append("\n CLS.").append(v.getName()).append(initField(v));
33.10 - }
33.11 - }
33.12 if (proto == null) {
33.13 String sc = jc.getSuperClassName(); // with _
33.14 out.append("\n var pp = ").
33.15 @@ -134,6 +129,18 @@
33.16 out.append("\n var c = ").append(proto[0]).append(";");
33.17 out.append("\n var sprcls = null;");
33.18 }
33.19 + for (FieldData v : jc.getFields()) {
33.20 + if (v.isStatic()) {
33.21 + out.append("\n CLS.").append(v.getName()).append(initField(v));
33.22 + } else {
33.23 + out.append("\n c._").append(v.getName()).append(" = function (v) {")
33.24 + .append(" if (arguments.length == 1) this.fld_").
33.25 + append(className).append('_').append(v.getName())
33.26 + .append(" = v; return this.fld_").
33.27 + append(className).append('_').append(v.getName())
33.28 + .append("; };");
33.29 + }
33.30 + }
33.31 for (MethodData m : jc.getMethods()) {
33.32 byte[] onlyArr = m.findAnnotationData(true);
33.33 String[] only = findAnnotation(onlyArr, jc,
33.34 @@ -206,6 +213,7 @@
33.35 }
33.36 if (!v.isStatic()) {
33.37 out.append("\n this.fld_").
33.38 + append(className).append('_').
33.39 append(v.getName()).append(initField(v));
33.40 }
33.41 }
33.42 @@ -1197,8 +1205,26 @@
33.43 int indx = readIntArg(byteCodes, i);
33.44 String[] fi = jc.getFieldInfoName(indx);
33.45 final int type = VarType.fromFieldType(fi[2].charAt(0));
33.46 - emit(out, "var @2 = @1.fld_@3;",
33.47 - smapper.popA(), smapper.pushT(type), fi[1]);
33.48 + final String mangleClass = mangleSig(fi[0]);
33.49 + final String mangleClassAccess = accessClass(mangleClass);
33.50 + emit(out, "var @2 = @4(false)._@3.call(@1);",
33.51 + smapper.popA(),
33.52 + smapper.pushT(type), fi[1], mangleClassAccess
33.53 + );
33.54 + i += 2;
33.55 + break;
33.56 + }
33.57 + case opc_putfield: {
33.58 + int indx = readIntArg(byteCodes, i);
33.59 + String[] fi = jc.getFieldInfoName(indx);
33.60 + final int type = VarType.fromFieldType(fi[2].charAt(0));
33.61 + final String mangleClass = mangleSig(fi[0]);
33.62 + final String mangleClassAccess = accessClass(mangleClass);
33.63 + emit(out, "@4(false)._@3.call(@2, @1);",
33.64 + smapper.popT(type),
33.65 + smapper.popA(), fi[1],
33.66 + mangleClassAccess
33.67 + );
33.68 i += 2;
33.69 break;
33.70 }
33.71 @@ -1213,15 +1239,6 @@
33.72 addReference(fi[0]);
33.73 break;
33.74 }
33.75 - case opc_putfield: {
33.76 - int indx = readIntArg(byteCodes, i);
33.77 - String[] fi = jc.getFieldInfoName(indx);
33.78 - final int type = VarType.fromFieldType(fi[2].charAt(0));
33.79 - emit(out, "@2.fld_@3 = @1;",
33.80 - smapper.popT(type), smapper.popA(), fi[1]);
33.81 - i += 2;
33.82 - break;
33.83 - }
33.84 case opc_putstatic: {
33.85 int indx = readIntArg(byteCodes, i);
33.86 String[] fi = jc.getFieldInfoName(indx);
33.87 @@ -1420,6 +1437,10 @@
33.88 }
33.89 }
33.90
33.91 + static String mangleSig(String sig) {
33.92 + return mangleSig(sig, 0, sig.length());
33.93 + }
33.94 +
33.95 private static String mangleSig(String txt, int first, int last) {
33.96 StringBuilder sb = new StringBuilder();
33.97 for (int i = first; i < last; i++) {
34.1 --- a/vm/src/main/java/org/apidesign/vm4brwsr/VMLazy.java Fri Jan 25 16:46:14 2013 +0100
34.2 +++ b/vm/src/main/java/org/apidesign/vm4brwsr/VMLazy.java Mon Jan 28 18:14:00 2013 +0100
34.3 @@ -117,8 +117,8 @@
34.4 body =
34.5 "var cls = n.replace__Ljava_lang_String_2CC('/','_').toString();"
34.6 + "\nvar dot = n.replace__Ljava_lang_String_2CC('/','.').toString();"
34.7 - + "\nvar lazy = this.fld_lazy;"
34.8 - + "\nvar loader = lazy.fld_loader;"
34.9 + + "\nvar lazy = this._lazy();"
34.10 + + "\nvar loader = lazy._loader();"
34.11 + "\nvar vm = loader.vm;"
34.12 + "\nif (vm[cls]) return false;"
34.13 + "\nvm[cls] = function() {"
35.1 --- a/vm/src/test/java/org/apidesign/vm4brwsr/StaticMethodTest.java Fri Jan 25 16:46:14 2013 +0100
35.2 +++ b/vm/src/test/java/org/apidesign/vm4brwsr/StaticMethodTest.java Mon Jan 28 18:14:00 2013 +0100
35.3 @@ -78,6 +78,73 @@
35.4 3.0d, 1l
35.5 );
35.6 }
35.7 +
35.8 + @Test public void rintNegativeUp() throws Exception {
35.9 + final double cnts = -453904.634;
35.10 + assertExec(
35.11 + "Should round up to end with 5",
35.12 + Math.class, "rint__DD",
35.13 + -453905.0, cnts
35.14 + );
35.15 + }
35.16 +
35.17 + @Test public void rintNegativeDown() throws Exception {
35.18 + final double cnts = -453904.434;
35.19 + assertExec(
35.20 + "Should round up to end with 4",
35.21 + Math.class, "rint__DD",
35.22 + -453904.0, cnts
35.23 + );
35.24 + }
35.25 +
35.26 + @Test public void rintPositiveUp() throws Exception {
35.27 + final double cnts = 453904.634;
35.28 + assertExec(
35.29 + "Should round up to end with 5",
35.30 + Math.class, "rint__DD",
35.31 + 453905.0, cnts
35.32 + );
35.33 + }
35.34 + @Test public void rintPositiveDown() throws Exception {
35.35 + final double cnts = 453904.434;
35.36 + assertExec(
35.37 + "Should round up to end with 4",
35.38 + Math.class, "rint__DD",
35.39 + 453904.0, cnts
35.40 + );
35.41 + }
35.42 + @Test public void rintOneHalf() throws Exception {
35.43 + final double cnts = 1.5;
35.44 + assertExec(
35.45 + "Should round up to end with 2",
35.46 + Math.class, "rint__DD",
35.47 + 2.0, cnts
35.48 + );
35.49 + }
35.50 + @Test public void rintNegativeOneHalf() throws Exception {
35.51 + final double cnts = -1.5;
35.52 + assertExec(
35.53 + "Should round up to end with 2",
35.54 + Math.class, "rint__DD",
35.55 + -2.0, cnts
35.56 + );
35.57 + }
35.58 + @Test public void rintTwoAndHalf() throws Exception {
35.59 + final double cnts = 2.5;
35.60 + assertExec(
35.61 + "Should round up to end with 2",
35.62 + Math.class, "rint__DD",
35.63 + 2.0, cnts
35.64 + );
35.65 + }
35.66 + @Test public void rintNegativeTwoOneHalf() throws Exception {
35.67 + final double cnts = -2.5;
35.68 + assertExec(
35.69 + "Should round up to end with 2",
35.70 + Math.class, "rint__DD",
35.71 + -2.0, cnts
35.72 + );
35.73 + }
35.74
35.75 @Test public void divAndRound() throws Exception {
35.76 assertExec(
36.1 --- a/vm/src/test/java/org/apidesign/vm4brwsr/StringSample.java Fri Jan 25 16:46:14 2013 +0100
36.2 +++ b/vm/src/test/java/org/apidesign/vm4brwsr/StringSample.java Mon Jan 28 18:14:00 2013 +0100
36.3 @@ -68,6 +68,15 @@
36.4 return chars('a', (char)30, 'b') instanceof String;
36.5 }
36.6
36.7 + public static String getBytes(String s) {
36.8 + byte[] arr = s.getBytes();
36.9 + StringBuilder sb = new StringBuilder();
36.10 + for (int i = 0; i < arr.length; i++) {
36.11 + sb.append(arr[i]).append(" ");
36.12 + }
36.13 + return sb.toString().toString();
36.14 + }
36.15 +
36.16 public static String insertBuffer() {
36.17 StringBuilder sb = new StringBuilder();
36.18 sb.append("Jardo!");
37.1 --- a/vm/src/test/java/org/apidesign/vm4brwsr/StringTest.java Fri Jan 25 16:46:14 2013 +0100
37.2 +++ b/vm/src/test/java/org/apidesign/vm4brwsr/StringTest.java Mon Jan 28 18:14:00 2013 +0100
37.3 @@ -75,6 +75,16 @@
37.4 );
37.5 }
37.6
37.7 + @Test public void getBytes() throws Exception {
37.8 + final String horse = "Žluťoučký kůň";
37.9 + final String expected = StringSample.getBytes(horse);
37.10 + assertExec(
37.11 + "Bytes look simplar",
37.12 + StringSample.class, "getBytes__Ljava_lang_String_2Ljava_lang_String_2",
37.13 + expected, horse
37.14 + );
37.15 + }
37.16 +
37.17 @Test(timeOut=10000) public void toStringConcatenation() throws Exception {
37.18 assertExec(
37.19 "Five executions should generate 5Hello World!",
38.1 --- a/vmtest/src/main/java/org/apidesign/bck2brwsr/vmtest/impl/Bck2BrwsrCase.java Fri Jan 25 16:46:14 2013 +0100
38.2 +++ b/vmtest/src/main/java/org/apidesign/bck2brwsr/vmtest/impl/Bck2BrwsrCase.java Mon Jan 28 18:14:00 2013 +0100
38.3 @@ -23,8 +23,6 @@
38.4 import java.lang.reflect.Constructor;
38.5 import java.lang.reflect.InvocationTargetException;
38.6 import java.lang.reflect.Method;
38.7 -import java.util.Map;
38.8 -import java.util.WeakHashMap;
38.9 import org.apidesign.bck2brwsr.launcher.Launcher;
38.10 import org.apidesign.bck2brwsr.launcher.MethodInvocation;
38.11 import org.testng.ITest;
39.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
39.2 +++ b/vmtest/src/test/java/org/apidesign/bck2brwsr/tck/InheritanceA.java Mon Jan 28 18:14:00 2013 +0100
39.3 @@ -0,0 +1,34 @@
39.4 +/**
39.5 + * Back 2 Browser Bytecode Translator
39.6 + * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
39.7 + *
39.8 + * This program is free software: you can redistribute it and/or modify
39.9 + * it under the terms of the GNU General Public License as published by
39.10 + * the Free Software Foundation, version 2 of the License.
39.11 + *
39.12 + * This program is distributed in the hope that it will be useful,
39.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
39.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39.15 + * GNU General Public License for more details.
39.16 + *
39.17 + * You should have received a copy of the GNU General Public License
39.18 + * along with this program. Look for COPYING file in the top folder.
39.19 + * If not, see http://opensource.org/licenses/GPL-2.0.
39.20 + */
39.21 +package org.apidesign.bck2brwsr.tck;
39.22 +
39.23 +/**
39.24 + *
39.25 + * @author Jaroslav Tulach <jtulach@netbeans.org>
39.26 + */
39.27 +public class InheritanceA {
39.28 + private String name;
39.29 +
39.30 + public void setA(String n) {
39.31 + this.name = n;
39.32 + }
39.33 +
39.34 + public String getA() {
39.35 + return name;
39.36 + }
39.37 +}
40.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
40.2 +++ b/vmtest/src/test/java/org/apidesign/bck2brwsr/tck/InheritanceB.java Mon Jan 28 18:14:00 2013 +0100
40.3 @@ -0,0 +1,34 @@
40.4 +/**
40.5 + * Back 2 Browser Bytecode Translator
40.6 + * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
40.7 + *
40.8 + * This program is free software: you can redistribute it and/or modify
40.9 + * it under the terms of the GNU General Public License as published by
40.10 + * the Free Software Foundation, version 2 of the License.
40.11 + *
40.12 + * This program is distributed in the hope that it will be useful,
40.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
40.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
40.15 + * GNU General Public License for more details.
40.16 + *
40.17 + * You should have received a copy of the GNU General Public License
40.18 + * along with this program. Look for COPYING file in the top folder.
40.19 + * If not, see http://opensource.org/licenses/GPL-2.0.
40.20 + */
40.21 +package org.apidesign.bck2brwsr.tck;
40.22 +
40.23 +/**
40.24 + *
40.25 + * @author Jaroslav Tulach <jtulach@netbeans.org>
40.26 + */
40.27 +public class InheritanceB extends InheritanceA {
40.28 + private String name;
40.29 +
40.30 + public void setB(String n) {
40.31 + this.name = n;
40.32 + }
40.33 +
40.34 + public String getB() {
40.35 + return name;
40.36 + }
40.37 +}
41.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
41.2 +++ b/vmtest/src/test/java/org/apidesign/bck2brwsr/tck/InheritanceTest.java Mon Jan 28 18:14:00 2013 +0100
41.3 @@ -0,0 +1,41 @@
41.4 +/**
41.5 + * Back 2 Browser Bytecode Translator
41.6 + * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
41.7 + *
41.8 + * This program is free software: you can redistribute it and/or modify
41.9 + * it under the terms of the GNU General Public License as published by
41.10 + * the Free Software Foundation, version 2 of the License.
41.11 + *
41.12 + * This program is distributed in the hope that it will be useful,
41.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
41.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41.15 + * GNU General Public License for more details.
41.16 + *
41.17 + * You should have received a copy of the GNU General Public License
41.18 + * along with this program. Look for COPYING file in the top folder.
41.19 + * If not, see http://opensource.org/licenses/GPL-2.0.
41.20 + */
41.21 +package org.apidesign.bck2brwsr.tck;
41.22 +
41.23 +import org.apidesign.bck2brwsr.vmtest.Compare;
41.24 +import org.apidesign.bck2brwsr.vmtest.VMTest;
41.25 +import org.testng.annotations.Factory;
41.26 +
41.27 +/**
41.28 + *
41.29 + * @author Jaroslav Tulach <jtulach@netbeans.org>
41.30 + */
41.31 +public class InheritanceTest {
41.32 +
41.33 + @Compare public String checkFieldsIndependent() throws ClassNotFoundException {
41.34 + InheritanceB ib = new InheritanceB();
41.35 + ib.setA("A");
41.36 + ib.setB("B");
41.37 + return "A: " + ib.getA() + " B: " + ib.getB();
41.38 + }
41.39 +
41.40 + @Factory
41.41 + public static Object[] create() {
41.42 + return VMTest.create(InheritanceTest.class);
41.43 + }
41.44 +}