1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/emul/compact/src/main/java/java/io/BufferedReader.java Wed Jan 23 22:33:45 2013 +0100
1.3 @@ -0,0 +1,522 @@
1.4 +/*
1.5 + * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1.7 + *
1.8 + * This code is free software; you can redistribute it and/or modify it
1.9 + * under the terms of the GNU General Public License version 2 only, as
1.10 + * published by the Free Software Foundation. Oracle designates this
1.11 + * particular file as subject to the "Classpath" exception as provided
1.12 + * by Oracle in the LICENSE file that accompanied this code.
1.13 + *
1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1.17 + * version 2 for more details (a copy is included in the LICENSE file that
1.18 + * accompanied this code).
1.19 + *
1.20 + * You should have received a copy of the GNU General Public License version
1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1.23 + *
1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1.25 + * or visit www.oracle.com if you need additional information or have any
1.26 + * questions.
1.27 + */
1.28 +
1.29 +package java.io;
1.30 +
1.31 +
1.32 +/**
1.33 + * Reads text from a character-input stream, buffering characters so as to
1.34 + * provide for the efficient reading of characters, arrays, and lines.
1.35 + *
1.36 + * <p> The buffer size may be specified, or the default size may be used. The
1.37 + * default is large enough for most purposes.
1.38 + *
1.39 + * <p> In general, each read request made of a Reader causes a corresponding
1.40 + * read request to be made of the underlying character or byte stream. It is
1.41 + * therefore advisable to wrap a BufferedReader around any Reader whose read()
1.42 + * operations may be costly, such as FileReaders and InputStreamReaders. For
1.43 + * example,
1.44 + *
1.45 + * <pre>
1.46 + * BufferedReader in
1.47 + * = new BufferedReader(new FileReader("foo.in"));
1.48 + * </pre>
1.49 + *
1.50 + * will buffer the input from the specified file. Without buffering, each
1.51 + * invocation of read() or readLine() could cause bytes to be read from the
1.52 + * file, converted into characters, and then returned, which can be very
1.53 + * inefficient.
1.54 + *
1.55 + * <p> Programs that use DataInputStreams for textual input can be localized by
1.56 + * replacing each DataInputStream with an appropriate BufferedReader.
1.57 + *
1.58 + * @see FileReader
1.59 + * @see InputStreamReader
1.60 + * @see java.nio.file.Files#newBufferedReader
1.61 + *
1.62 + * @author Mark Reinhold
1.63 + * @since JDK1.1
1.64 + */
1.65 +
1.66 +public class BufferedReader extends Reader {
1.67 +
1.68 + private Reader in;
1.69 +
1.70 + private char cb[];
1.71 + private int nChars, nextChar;
1.72 +
1.73 + private static final int INVALIDATED = -2;
1.74 + private static final int UNMARKED = -1;
1.75 + private int markedChar = UNMARKED;
1.76 + private int readAheadLimit = 0; /* Valid only when markedChar > 0 */
1.77 +
1.78 + /** If the next character is a line feed, skip it */
1.79 + private boolean skipLF = false;
1.80 +
1.81 + /** The skipLF flag when the mark was set */
1.82 + private boolean markedSkipLF = false;
1.83 +
1.84 + private static int defaultCharBufferSize = 8192;
1.85 + private static int defaultExpectedLineLength = 80;
1.86 +
1.87 + /**
1.88 + * Creates a buffering character-input stream that uses an input buffer of
1.89 + * the specified size.
1.90 + *
1.91 + * @param in A Reader
1.92 + * @param sz Input-buffer size
1.93 + *
1.94 + * @exception IllegalArgumentException If sz is <= 0
1.95 + */
1.96 + public BufferedReader(Reader in, int sz) {
1.97 + super(in);
1.98 + if (sz <= 0)
1.99 + throw new IllegalArgumentException("Buffer size <= 0");
1.100 + this.in = in;
1.101 + cb = new char[sz];
1.102 + nextChar = nChars = 0;
1.103 + }
1.104 +
1.105 + /**
1.106 + * Creates a buffering character-input stream that uses a default-sized
1.107 + * input buffer.
1.108 + *
1.109 + * @param in A Reader
1.110 + */
1.111 + public BufferedReader(Reader in) {
1.112 + this(in, defaultCharBufferSize);
1.113 + }
1.114 +
1.115 + /** Checks to make sure that the stream has not been closed */
1.116 + private void ensureOpen() throws IOException {
1.117 + if (in == null)
1.118 + throw new IOException("Stream closed");
1.119 + }
1.120 +
1.121 + /**
1.122 + * Fills the input buffer, taking the mark into account if it is valid.
1.123 + */
1.124 + private void fill() throws IOException {
1.125 + int dst;
1.126 + if (markedChar <= UNMARKED) {
1.127 + /* No mark */
1.128 + dst = 0;
1.129 + } else {
1.130 + /* Marked */
1.131 + int delta = nextChar - markedChar;
1.132 + if (delta >= readAheadLimit) {
1.133 + /* Gone past read-ahead limit: Invalidate mark */
1.134 + markedChar = INVALIDATED;
1.135 + readAheadLimit = 0;
1.136 + dst = 0;
1.137 + } else {
1.138 + if (readAheadLimit <= cb.length) {
1.139 + /* Shuffle in the current buffer */
1.140 + System.arraycopy(cb, markedChar, cb, 0, delta);
1.141 + markedChar = 0;
1.142 + dst = delta;
1.143 + } else {
1.144 + /* Reallocate buffer to accommodate read-ahead limit */
1.145 + char ncb[] = new char[readAheadLimit];
1.146 + System.arraycopy(cb, markedChar, ncb, 0, delta);
1.147 + cb = ncb;
1.148 + markedChar = 0;
1.149 + dst = delta;
1.150 + }
1.151 + nextChar = nChars = delta;
1.152 + }
1.153 + }
1.154 +
1.155 + int n;
1.156 + do {
1.157 + n = in.read(cb, dst, cb.length - dst);
1.158 + } while (n == 0);
1.159 + if (n > 0) {
1.160 + nChars = dst + n;
1.161 + nextChar = dst;
1.162 + }
1.163 + }
1.164 +
1.165 + /**
1.166 + * Reads a single character.
1.167 + *
1.168 + * @return The character read, as an integer in the range
1.169 + * 0 to 65535 (<tt>0x00-0xffff</tt>), or -1 if the
1.170 + * end of the stream has been reached
1.171 + * @exception IOException If an I/O error occurs
1.172 + */
1.173 + public int read() throws IOException {
1.174 + synchronized (lock) {
1.175 + ensureOpen();
1.176 + for (;;) {
1.177 + if (nextChar >= nChars) {
1.178 + fill();
1.179 + if (nextChar >= nChars)
1.180 + return -1;
1.181 + }
1.182 + if (skipLF) {
1.183 + skipLF = false;
1.184 + if (cb[nextChar] == '\n') {
1.185 + nextChar++;
1.186 + continue;
1.187 + }
1.188 + }
1.189 + return cb[nextChar++];
1.190 + }
1.191 + }
1.192 + }
1.193 +
1.194 + /**
1.195 + * Reads characters into a portion of an array, reading from the underlying
1.196 + * stream if necessary.
1.197 + */
1.198 + private int read1(char[] cbuf, int off, int len) throws IOException {
1.199 + if (nextChar >= nChars) {
1.200 + /* If the requested length is at least as large as the buffer, and
1.201 + if there is no mark/reset activity, and if line feeds are not
1.202 + being skipped, do not bother to copy the characters into the
1.203 + local buffer. In this way buffered streams will cascade
1.204 + harmlessly. */
1.205 + if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
1.206 + return in.read(cbuf, off, len);
1.207 + }
1.208 + fill();
1.209 + }
1.210 + if (nextChar >= nChars) return -1;
1.211 + if (skipLF) {
1.212 + skipLF = false;
1.213 + if (cb[nextChar] == '\n') {
1.214 + nextChar++;
1.215 + if (nextChar >= nChars)
1.216 + fill();
1.217 + if (nextChar >= nChars)
1.218 + return -1;
1.219 + }
1.220 + }
1.221 + int n = Math.min(len, nChars - nextChar);
1.222 + System.arraycopy(cb, nextChar, cbuf, off, n);
1.223 + nextChar += n;
1.224 + return n;
1.225 + }
1.226 +
1.227 + /**
1.228 + * Reads characters into a portion of an array.
1.229 + *
1.230 + * <p> This method implements the general contract of the corresponding
1.231 + * <code>{@link Reader#read(char[], int, int) read}</code> method of the
1.232 + * <code>{@link Reader}</code> class. As an additional convenience, it
1.233 + * attempts to read as many characters as possible by repeatedly invoking
1.234 + * the <code>read</code> method of the underlying stream. This iterated
1.235 + * <code>read</code> continues until one of the following conditions becomes
1.236 + * true: <ul>
1.237 + *
1.238 + * <li> The specified number of characters have been read,
1.239 + *
1.240 + * <li> The <code>read</code> method of the underlying stream returns
1.241 + * <code>-1</code>, indicating end-of-file, or
1.242 + *
1.243 + * <li> The <code>ready</code> method of the underlying stream
1.244 + * returns <code>false</code>, indicating that further input requests
1.245 + * would block.
1.246 + *
1.247 + * </ul> If the first <code>read</code> on the underlying stream returns
1.248 + * <code>-1</code> to indicate end-of-file then this method returns
1.249 + * <code>-1</code>. Otherwise this method returns the number of characters
1.250 + * actually read.
1.251 + *
1.252 + * <p> Subclasses of this class are encouraged, but not required, to
1.253 + * attempt to read as many characters as possible in the same fashion.
1.254 + *
1.255 + * <p> Ordinarily this method takes characters from this stream's character
1.256 + * buffer, filling it from the underlying stream as necessary. If,
1.257 + * however, the buffer is empty, the mark is not valid, and the requested
1.258 + * length is at least as large as the buffer, then this method will read
1.259 + * characters directly from the underlying stream into the given array.
1.260 + * Thus redundant <code>BufferedReader</code>s will not copy data
1.261 + * unnecessarily.
1.262 + *
1.263 + * @param cbuf Destination buffer
1.264 + * @param off Offset at which to start storing characters
1.265 + * @param len Maximum number of characters to read
1.266 + *
1.267 + * @return The number of characters read, or -1 if the end of the
1.268 + * stream has been reached
1.269 + *
1.270 + * @exception IOException If an I/O error occurs
1.271 + */
1.272 + public int read(char cbuf[], int off, int len) throws IOException {
1.273 + synchronized (lock) {
1.274 + ensureOpen();
1.275 + if ((off < 0) || (off > cbuf.length) || (len < 0) ||
1.276 + ((off + len) > cbuf.length) || ((off + len) < 0)) {
1.277 + throw new IndexOutOfBoundsException();
1.278 + } else if (len == 0) {
1.279 + return 0;
1.280 + }
1.281 +
1.282 + int n = read1(cbuf, off, len);
1.283 + if (n <= 0) return n;
1.284 + while ((n < len) && in.ready()) {
1.285 + int n1 = read1(cbuf, off + n, len - n);
1.286 + if (n1 <= 0) break;
1.287 + n += n1;
1.288 + }
1.289 + return n;
1.290 + }
1.291 + }
1.292 +
1.293 + /**
1.294 + * Reads a line of text. A line is considered to be terminated by any one
1.295 + * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
1.296 + * followed immediately by a linefeed.
1.297 + *
1.298 + * @param ignoreLF If true, the next '\n' will be skipped
1.299 + *
1.300 + * @return A String containing the contents of the line, not including
1.301 + * any line-termination characters, or null if the end of the
1.302 + * stream has been reached
1.303 + *
1.304 + * @see java.io.LineNumberReader#readLine()
1.305 + *
1.306 + * @exception IOException If an I/O error occurs
1.307 + */
1.308 + String readLine(boolean ignoreLF) throws IOException {
1.309 + StringBuffer s = null;
1.310 + int startChar;
1.311 +
1.312 + synchronized (lock) {
1.313 + ensureOpen();
1.314 + boolean omitLF = ignoreLF || skipLF;
1.315 +
1.316 + bufferLoop:
1.317 + for (;;) {
1.318 +
1.319 + if (nextChar >= nChars)
1.320 + fill();
1.321 + if (nextChar >= nChars) { /* EOF */
1.322 + if (s != null && s.length() > 0)
1.323 + return s.toString();
1.324 + else
1.325 + return null;
1.326 + }
1.327 + boolean eol = false;
1.328 + char c = 0;
1.329 + int i;
1.330 +
1.331 + /* Skip a leftover '\n', if necessary */
1.332 + if (omitLF && (cb[nextChar] == '\n'))
1.333 + nextChar++;
1.334 + skipLF = false;
1.335 + omitLF = false;
1.336 +
1.337 + charLoop:
1.338 + for (i = nextChar; i < nChars; i++) {
1.339 + c = cb[i];
1.340 + if ((c == '\n') || (c == '\r')) {
1.341 + eol = true;
1.342 + break charLoop;
1.343 + }
1.344 + }
1.345 +
1.346 + startChar = nextChar;
1.347 + nextChar = i;
1.348 +
1.349 + if (eol) {
1.350 + String str;
1.351 + if (s == null) {
1.352 + str = new String(cb, startChar, i - startChar);
1.353 + } else {
1.354 + s.append(cb, startChar, i - startChar);
1.355 + str = s.toString();
1.356 + }
1.357 + nextChar++;
1.358 + if (c == '\r') {
1.359 + skipLF = true;
1.360 + }
1.361 + return str;
1.362 + }
1.363 +
1.364 + if (s == null)
1.365 + s = new StringBuffer(defaultExpectedLineLength);
1.366 + s.append(cb, startChar, i - startChar);
1.367 + }
1.368 + }
1.369 + }
1.370 +
1.371 + /**
1.372 + * Reads a line of text. A line is considered to be terminated by any one
1.373 + * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
1.374 + * followed immediately by a linefeed.
1.375 + *
1.376 + * @return A String containing the contents of the line, not including
1.377 + * any line-termination characters, or null if the end of the
1.378 + * stream has been reached
1.379 + *
1.380 + * @exception IOException If an I/O error occurs
1.381 + *
1.382 + * @see java.nio.file.Files#readAllLines
1.383 + */
1.384 + public String readLine() throws IOException {
1.385 + return readLine(false);
1.386 + }
1.387 +
1.388 + /**
1.389 + * Skips characters.
1.390 + *
1.391 + * @param n The number of characters to skip
1.392 + *
1.393 + * @return The number of characters actually skipped
1.394 + *
1.395 + * @exception IllegalArgumentException If <code>n</code> is negative.
1.396 + * @exception IOException If an I/O error occurs
1.397 + */
1.398 + public long skip(long n) throws IOException {
1.399 + if (n < 0L) {
1.400 + throw new IllegalArgumentException("skip value is negative");
1.401 + }
1.402 + synchronized (lock) {
1.403 + ensureOpen();
1.404 + long r = n;
1.405 + while (r > 0) {
1.406 + if (nextChar >= nChars)
1.407 + fill();
1.408 + if (nextChar >= nChars) /* EOF */
1.409 + break;
1.410 + if (skipLF) {
1.411 + skipLF = false;
1.412 + if (cb[nextChar] == '\n') {
1.413 + nextChar++;
1.414 + }
1.415 + }
1.416 + long d = nChars - nextChar;
1.417 + if (r <= d) {
1.418 + nextChar += r;
1.419 + r = 0;
1.420 + break;
1.421 + }
1.422 + else {
1.423 + r -= d;
1.424 + nextChar = nChars;
1.425 + }
1.426 + }
1.427 + return n - r;
1.428 + }
1.429 + }
1.430 +
1.431 + /**
1.432 + * Tells whether this stream is ready to be read. A buffered character
1.433 + * stream is ready if the buffer is not empty, or if the underlying
1.434 + * character stream is ready.
1.435 + *
1.436 + * @exception IOException If an I/O error occurs
1.437 + */
1.438 + public boolean ready() throws IOException {
1.439 + synchronized (lock) {
1.440 + ensureOpen();
1.441 +
1.442 + /*
1.443 + * If newline needs to be skipped and the next char to be read
1.444 + * is a newline character, then just skip it right away.
1.445 + */
1.446 + if (skipLF) {
1.447 + /* Note that in.ready() will return true if and only if the next
1.448 + * read on the stream will not block.
1.449 + */
1.450 + if (nextChar >= nChars && in.ready()) {
1.451 + fill();
1.452 + }
1.453 + if (nextChar < nChars) {
1.454 + if (cb[nextChar] == '\n')
1.455 + nextChar++;
1.456 + skipLF = false;
1.457 + }
1.458 + }
1.459 + return (nextChar < nChars) || in.ready();
1.460 + }
1.461 + }
1.462 +
1.463 + /**
1.464 + * Tells whether this stream supports the mark() operation, which it does.
1.465 + */
1.466 + public boolean markSupported() {
1.467 + return true;
1.468 + }
1.469 +
1.470 + /**
1.471 + * Marks the present position in the stream. Subsequent calls to reset()
1.472 + * will attempt to reposition the stream to this point.
1.473 + *
1.474 + * @param readAheadLimit Limit on the number of characters that may be
1.475 + * read while still preserving the mark. An attempt
1.476 + * to reset the stream after reading characters
1.477 + * up to this limit or beyond may fail.
1.478 + * A limit value larger than the size of the input
1.479 + * buffer will cause a new buffer to be allocated
1.480 + * whose size is no smaller than limit.
1.481 + * Therefore large values should be used with care.
1.482 + *
1.483 + * @exception IllegalArgumentException If readAheadLimit is < 0
1.484 + * @exception IOException If an I/O error occurs
1.485 + */
1.486 + public void mark(int readAheadLimit) throws IOException {
1.487 + if (readAheadLimit < 0) {
1.488 + throw new IllegalArgumentException("Read-ahead limit < 0");
1.489 + }
1.490 + synchronized (lock) {
1.491 + ensureOpen();
1.492 + this.readAheadLimit = readAheadLimit;
1.493 + markedChar = nextChar;
1.494 + markedSkipLF = skipLF;
1.495 + }
1.496 + }
1.497 +
1.498 + /**
1.499 + * Resets the stream to the most recent mark.
1.500 + *
1.501 + * @exception IOException If the stream has never been marked,
1.502 + * or if the mark has been invalidated
1.503 + */
1.504 + public void reset() throws IOException {
1.505 + synchronized (lock) {
1.506 + ensureOpen();
1.507 + if (markedChar < 0)
1.508 + throw new IOException((markedChar == INVALIDATED)
1.509 + ? "Mark invalid"
1.510 + : "Stream not marked");
1.511 + nextChar = markedChar;
1.512 + skipLF = markedSkipLF;
1.513 + }
1.514 + }
1.515 +
1.516 + public void close() throws IOException {
1.517 + synchronized (lock) {
1.518 + if (in == null)
1.519 + return;
1.520 + in.close();
1.521 + in = null;
1.522 + cb = null;
1.523 + }
1.524 + }
1.525 +}
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/emul/compact/src/main/java/java/io/InputStreamReader.java Wed Jan 23 22:33:45 2013 +0100
2.3 @@ -0,0 +1,201 @@
2.4 +/*
2.5 + * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
2.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
2.7 + *
2.8 + * This code is free software; you can redistribute it and/or modify it
2.9 + * under the terms of the GNU General Public License version 2 only, as
2.10 + * published by the Free Software Foundation. Oracle designates this
2.11 + * particular file as subject to the "Classpath" exception as provided
2.12 + * by Oracle in the LICENSE file that accompanied this code.
2.13 + *
2.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
2.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
2.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
2.17 + * version 2 for more details (a copy is included in the LICENSE file that
2.18 + * accompanied this code).
2.19 + *
2.20 + * You should have received a copy of the GNU General Public License version
2.21 + * 2 along with this work; if not, write to the Free Software Foundation,
2.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
2.23 + *
2.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2.25 + * or visit www.oracle.com if you need additional information or have any
2.26 + * questions.
2.27 + */
2.28 +
2.29 +package java.io;
2.30 +
2.31 +import java.nio.charset.Charset;
2.32 +import java.nio.charset.CharsetDecoder;
2.33 +import sun.nio.cs.StreamDecoder;
2.34 +
2.35 +
2.36 +/**
2.37 + * An InputStreamReader is a bridge from byte streams to character streams: It
2.38 + * reads bytes and decodes them into characters using a specified {@link
2.39 + * java.nio.charset.Charset <code>charset</code>}. The charset that it uses
2.40 + * may be specified by name or may be given explicitly, or the platform's
2.41 + * default charset may be accepted.
2.42 + *
2.43 + * <p> Each invocation of one of an InputStreamReader's read() methods may
2.44 + * cause one or more bytes to be read from the underlying byte-input stream.
2.45 + * To enable the efficient conversion of bytes to characters, more bytes may
2.46 + * be read ahead from the underlying stream than are necessary to satisfy the
2.47 + * current read operation.
2.48 + *
2.49 + * <p> For top efficiency, consider wrapping an InputStreamReader within a
2.50 + * BufferedReader. For example:
2.51 + *
2.52 + * <pre>
2.53 + * BufferedReader in
2.54 + * = new BufferedReader(new InputStreamReader(System.in));
2.55 + * </pre>
2.56 + *
2.57 + * @see BufferedReader
2.58 + * @see InputStream
2.59 + * @see java.nio.charset.Charset
2.60 + *
2.61 + * @author Mark Reinhold
2.62 + * @since JDK1.1
2.63 + */
2.64 +
2.65 +public class InputStreamReader extends Reader {
2.66 +
2.67 + private final StreamDecoder sd;
2.68 +
2.69 + /**
2.70 + * Creates an InputStreamReader that uses the default charset.
2.71 + *
2.72 + * @param in An InputStream
2.73 + */
2.74 + public InputStreamReader(InputStream in) {
2.75 + super(in);
2.76 + try {
2.77 + sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## check lock object
2.78 + } catch (UnsupportedEncodingException e) {
2.79 + // The default encoding should always be available
2.80 + throw new Error(e);
2.81 + }
2.82 + }
2.83 +
2.84 + /**
2.85 + * Creates an InputStreamReader that uses the named charset.
2.86 + *
2.87 + * @param in
2.88 + * An InputStream
2.89 + *
2.90 + * @param charsetName
2.91 + * The name of a supported
2.92 + * {@link java.nio.charset.Charset </code>charset<code>}
2.93 + *
2.94 + * @exception UnsupportedEncodingException
2.95 + * If the named charset is not supported
2.96 + */
2.97 + public InputStreamReader(InputStream in, String charsetName)
2.98 + throws UnsupportedEncodingException
2.99 + {
2.100 + super(in);
2.101 + if (charsetName == null)
2.102 + throw new NullPointerException("charsetName");
2.103 + sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
2.104 + }
2.105 +
2.106 + /**
2.107 + * Creates an InputStreamReader that uses the given charset. </p>
2.108 + *
2.109 + * @param in An InputStream
2.110 + * @param cs A charset
2.111 + *
2.112 + * @since 1.4
2.113 + * @spec JSR-51
2.114 + */
2.115 + public InputStreamReader(InputStream in, Charset cs) {
2.116 + super(in);
2.117 + if (cs == null)
2.118 + throw new NullPointerException("charset");
2.119 + sd = StreamDecoder.forInputStreamReader(in, this, cs);
2.120 + }
2.121 +
2.122 + /**
2.123 + * Creates an InputStreamReader that uses the given charset decoder. </p>
2.124 + *
2.125 + * @param in An InputStream
2.126 + * @param dec A charset decoder
2.127 + *
2.128 + * @since 1.4
2.129 + * @spec JSR-51
2.130 + */
2.131 + public InputStreamReader(InputStream in, CharsetDecoder dec) {
2.132 + super(in);
2.133 + if (dec == null)
2.134 + throw new NullPointerException("charset decoder");
2.135 + sd = StreamDecoder.forInputStreamReader(in, this, dec);
2.136 + }
2.137 +
2.138 + /**
2.139 + * Returns the name of the character encoding being used by this stream.
2.140 + *
2.141 + * <p> If the encoding has an historical name then that name is returned;
2.142 + * otherwise the encoding's canonical name is returned.
2.143 + *
2.144 + * <p> If this instance was created with the {@link
2.145 + * #InputStreamReader(InputStream, String)} constructor then the returned
2.146 + * name, being unique for the encoding, may differ from the name passed to
2.147 + * the constructor. This method will return <code>null</code> if the
2.148 + * stream has been closed.
2.149 + * </p>
2.150 + * @return The historical name of this encoding, or
2.151 + * <code>null</code> if the stream has been closed
2.152 + *
2.153 + * @see java.nio.charset.Charset
2.154 + *
2.155 + * @revised 1.4
2.156 + * @spec JSR-51
2.157 + */
2.158 + public String getEncoding() {
2.159 + return sd.getEncoding();
2.160 + }
2.161 +
2.162 + /**
2.163 + * Reads a single character.
2.164 + *
2.165 + * @return The character read, or -1 if the end of the stream has been
2.166 + * reached
2.167 + *
2.168 + * @exception IOException If an I/O error occurs
2.169 + */
2.170 + public int read() throws IOException {
2.171 + return sd.read();
2.172 + }
2.173 +
2.174 + /**
2.175 + * Reads characters into a portion of an array.
2.176 + *
2.177 + * @param cbuf Destination buffer
2.178 + * @param offset Offset at which to start storing characters
2.179 + * @param length Maximum number of characters to read
2.180 + *
2.181 + * @return The number of characters read, or -1 if the end of the
2.182 + * stream has been reached
2.183 + *
2.184 + * @exception IOException If an I/O error occurs
2.185 + */
2.186 + public int read(char cbuf[], int offset, int length) throws IOException {
2.187 + return sd.read(cbuf, offset, length);
2.188 + }
2.189 +
2.190 + /**
2.191 + * Tells whether this stream is ready to be read. An InputStreamReader is
2.192 + * ready if its input buffer is not empty, or if bytes are available to be
2.193 + * read from the underlying byte stream.
2.194 + *
2.195 + * @exception IOException If an I/O error occurs
2.196 + */
2.197 + public boolean ready() throws IOException {
2.198 + return sd.ready();
2.199 + }
2.200 +
2.201 + public void close() throws IOException {
2.202 + sd.close();
2.203 + }
2.204 +}
3.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3.2 +++ b/emul/compact/src/main/java/java/io/Reader.java Wed Jan 23 22:33:45 2013 +0100
3.3 @@ -0,0 +1,262 @@
3.4 +/*
3.5 + * Copyright (c) 1996, 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.io;
3.30 +
3.31 +
3.32 +/**
3.33 + * Abstract class for reading character streams. The only methods that a
3.34 + * subclass must implement are read(char[], int, int) and close(). Most
3.35 + * subclasses, however, will override some of the methods defined here in order
3.36 + * to provide higher efficiency, additional functionality, or both.
3.37 + *
3.38 + *
3.39 + * @see BufferedReader
3.40 + * @see LineNumberReader
3.41 + * @see CharArrayReader
3.42 + * @see InputStreamReader
3.43 + * @see FileReader
3.44 + * @see FilterReader
3.45 + * @see PushbackReader
3.46 + * @see PipedReader
3.47 + * @see StringReader
3.48 + * @see Writer
3.49 + *
3.50 + * @author Mark Reinhold
3.51 + * @since JDK1.1
3.52 + */
3.53 +
3.54 +public abstract class Reader implements Readable, Closeable {
3.55 +
3.56 + /**
3.57 + * The object used to synchronize operations on this stream. For
3.58 + * efficiency, a character-stream object may use an object other than
3.59 + * itself to protect critical sections. A subclass should therefore use
3.60 + * the object in this field rather than <tt>this</tt> or a synchronized
3.61 + * method.
3.62 + */
3.63 + protected Object lock;
3.64 +
3.65 + /**
3.66 + * Creates a new character-stream reader whose critical sections will
3.67 + * synchronize on the reader itself.
3.68 + */
3.69 + protected Reader() {
3.70 + this.lock = this;
3.71 + }
3.72 +
3.73 + /**
3.74 + * Creates a new character-stream reader whose critical sections will
3.75 + * synchronize on the given object.
3.76 + *
3.77 + * @param lock The Object to synchronize on.
3.78 + */
3.79 + protected Reader(Object lock) {
3.80 + if (lock == null) {
3.81 + throw new NullPointerException();
3.82 + }
3.83 + this.lock = lock;
3.84 + }
3.85 +
3.86 + /**
3.87 + * Attempts to read characters into the specified character buffer.
3.88 + * The buffer is used as a repository of characters as-is: the only
3.89 + * changes made are the results of a put operation. No flipping or
3.90 + * rewinding of the buffer is performed.
3.91 + *
3.92 + * @param target the buffer to read characters into
3.93 + * @return The number of characters added to the buffer, or
3.94 + * -1 if this source of characters is at its end
3.95 + * @throws IOException if an I/O error occurs
3.96 + * @throws NullPointerException if target is null
3.97 + * @throws ReadOnlyBufferException if target is a read only buffer
3.98 + * @since 1.5
3.99 + */
3.100 + public int read(java.nio.CharBuffer target) throws IOException {
3.101 + int len = target.remaining();
3.102 + char[] cbuf = new char[len];
3.103 + int n = read(cbuf, 0, len);
3.104 + if (n > 0)
3.105 + target.put(cbuf, 0, n);
3.106 + return n;
3.107 + }
3.108 +
3.109 + /**
3.110 + * Reads a single character. This method will block until a character is
3.111 + * available, an I/O error occurs, or the end of the stream is reached.
3.112 + *
3.113 + * <p> Subclasses that intend to support efficient single-character input
3.114 + * should override this method.
3.115 + *
3.116 + * @return The character read, as an integer in the range 0 to 65535
3.117 + * (<tt>0x00-0xffff</tt>), or -1 if the end of the stream has
3.118 + * been reached
3.119 + *
3.120 + * @exception IOException If an I/O error occurs
3.121 + */
3.122 + public int read() throws IOException {
3.123 + char cb[] = new char[1];
3.124 + if (read(cb, 0, 1) == -1)
3.125 + return -1;
3.126 + else
3.127 + return cb[0];
3.128 + }
3.129 +
3.130 + /**
3.131 + * Reads characters into an array. This method will block until some input
3.132 + * is available, an I/O error occurs, or the end of the stream is reached.
3.133 + *
3.134 + * @param cbuf Destination buffer
3.135 + *
3.136 + * @return The number of characters read, or -1
3.137 + * if the end of the stream
3.138 + * has been reached
3.139 + *
3.140 + * @exception IOException If an I/O error occurs
3.141 + */
3.142 + public int read(char cbuf[]) throws IOException {
3.143 + return read(cbuf, 0, cbuf.length);
3.144 + }
3.145 +
3.146 + /**
3.147 + * Reads characters into a portion of an array. This method will block
3.148 + * until some input is available, an I/O error occurs, or the end of the
3.149 + * stream is reached.
3.150 + *
3.151 + * @param cbuf Destination buffer
3.152 + * @param off Offset at which to start storing characters
3.153 + * @param len Maximum number of characters to read
3.154 + *
3.155 + * @return The number of characters read, or -1 if the end of the
3.156 + * stream has been reached
3.157 + *
3.158 + * @exception IOException If an I/O error occurs
3.159 + */
3.160 + abstract public int read(char cbuf[], int off, int len) throws IOException;
3.161 +
3.162 + /** Maximum skip-buffer size */
3.163 + private static final int maxSkipBufferSize = 8192;
3.164 +
3.165 + /** Skip buffer, null until allocated */
3.166 + private char skipBuffer[] = null;
3.167 +
3.168 + /**
3.169 + * Skips characters. This method will block until some characters are
3.170 + * available, an I/O error occurs, or the end of the stream is reached.
3.171 + *
3.172 + * @param n The number of characters to skip
3.173 + *
3.174 + * @return The number of characters actually skipped
3.175 + *
3.176 + * @exception IllegalArgumentException If <code>n</code> is negative.
3.177 + * @exception IOException If an I/O error occurs
3.178 + */
3.179 + public long skip(long n) throws IOException {
3.180 + if (n < 0L)
3.181 + throw new IllegalArgumentException("skip value is negative");
3.182 + int nn = (int) Math.min(n, maxSkipBufferSize);
3.183 + synchronized (lock) {
3.184 + if ((skipBuffer == null) || (skipBuffer.length < nn))
3.185 + skipBuffer = new char[nn];
3.186 + long r = n;
3.187 + while (r > 0) {
3.188 + int nc = read(skipBuffer, 0, (int)Math.min(r, nn));
3.189 + if (nc == -1)
3.190 + break;
3.191 + r -= nc;
3.192 + }
3.193 + return n - r;
3.194 + }
3.195 + }
3.196 +
3.197 + /**
3.198 + * Tells whether this stream is ready to be read.
3.199 + *
3.200 + * @return True if the next read() is guaranteed not to block for input,
3.201 + * false otherwise. Note that returning false does not guarantee that the
3.202 + * next read will block.
3.203 + *
3.204 + * @exception IOException If an I/O error occurs
3.205 + */
3.206 + public boolean ready() throws IOException {
3.207 + return false;
3.208 + }
3.209 +
3.210 + /**
3.211 + * Tells whether this stream supports the mark() operation. The default
3.212 + * implementation always returns false. Subclasses should override this
3.213 + * method.
3.214 + *
3.215 + * @return true if and only if this stream supports the mark operation.
3.216 + */
3.217 + public boolean markSupported() {
3.218 + return false;
3.219 + }
3.220 +
3.221 + /**
3.222 + * Marks the present position in the stream. Subsequent calls to reset()
3.223 + * will attempt to reposition the stream to this point. Not all
3.224 + * character-input streams support the mark() operation.
3.225 + *
3.226 + * @param readAheadLimit Limit on the number of characters that may be
3.227 + * read while still preserving the mark. After
3.228 + * reading this many characters, attempting to
3.229 + * reset the stream may fail.
3.230 + *
3.231 + * @exception IOException If the stream does not support mark(),
3.232 + * or if some other I/O error occurs
3.233 + */
3.234 + public void mark(int readAheadLimit) throws IOException {
3.235 + throw new IOException("mark() not supported");
3.236 + }
3.237 +
3.238 + /**
3.239 + * Resets the stream. If the stream has been marked, then attempt to
3.240 + * reposition it at the mark. If the stream has not been marked, then
3.241 + * attempt to reset it in some way appropriate to the particular stream,
3.242 + * for example by repositioning it to its starting point. Not all
3.243 + * character-input streams support the reset() operation, and some support
3.244 + * reset() without supporting mark().
3.245 + *
3.246 + * @exception IOException If the stream has not been marked,
3.247 + * or if the mark has been invalidated,
3.248 + * or if the stream does not support reset(),
3.249 + * or if some other I/O error occurs
3.250 + */
3.251 + public void reset() throws IOException {
3.252 + throw new IOException("reset() not supported");
3.253 + }
3.254 +
3.255 + /**
3.256 + * Closes the stream and releases any system resources associated with
3.257 + * it. Once the stream has been closed, further read(), ready(),
3.258 + * mark(), reset(), or skip() invocations will throw an IOException.
3.259 + * Closing a previously closed stream has no effect.
3.260 + *
3.261 + * @exception IOException If an I/O error occurs
3.262 + */
3.263 + abstract public void close() throws IOException;
3.264 +
3.265 +}
4.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
4.2 +++ b/emul/compact/src/main/java/java/lang/Cloneable.java Wed Jan 23 22:33:45 2013 +0100
4.3 @@ -0,0 +1,54 @@
4.4 +/*
4.5 + * Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved.
4.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4.7 + *
4.8 + * This code is free software; you can redistribute it and/or modify it
4.9 + * under the terms of the GNU General Public License version 2 only, as
4.10 + * published by the Free Software Foundation. Oracle designates this
4.11 + * particular file as subject to the "Classpath" exception as provided
4.12 + * by Oracle in the LICENSE file that accompanied this code.
4.13 + *
4.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
4.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
4.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
4.17 + * version 2 for more details (a copy is included in the LICENSE file that
4.18 + * accompanied this code).
4.19 + *
4.20 + * You should have received a copy of the GNU General Public License version
4.21 + * 2 along with this work; if not, write to the Free Software Foundation,
4.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
4.23 + *
4.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
4.25 + * or visit www.oracle.com if you need additional information or have any
4.26 + * questions.
4.27 + */
4.28 +
4.29 +package java.lang;
4.30 +
4.31 +/**
4.32 + * A class implements the <code>Cloneable</code> interface to
4.33 + * indicate to the {@link java.lang.Object#clone()} method that it
4.34 + * is legal for that method to make a
4.35 + * field-for-field copy of instances of that class.
4.36 + * <p>
4.37 + * Invoking Object's clone method on an instance that does not implement the
4.38 + * <code>Cloneable</code> interface results in the exception
4.39 + * <code>CloneNotSupportedException</code> being thrown.
4.40 + * <p>
4.41 + * By convention, classes that implement this interface should override
4.42 + * <tt>Object.clone</tt> (which is protected) with a public method.
4.43 + * See {@link java.lang.Object#clone()} for details on overriding this
4.44 + * method.
4.45 + * <p>
4.46 + * Note that this interface does <i>not</i> contain the <tt>clone</tt> method.
4.47 + * Therefore, it is not possible to clone an object merely by virtue of the
4.48 + * fact that it implements this interface. Even if the clone method is invoked
4.49 + * reflectively, there is no guarantee that it will succeed.
4.50 + *
4.51 + * @author unascribed
4.52 + * @see java.lang.CloneNotSupportedException
4.53 + * @see java.lang.Object#clone()
4.54 + * @since JDK1.0
4.55 + */
4.56 +public interface Cloneable {
4.57 +}
5.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
5.2 +++ b/emul/compact/src/main/java/java/lang/InternalError.java Wed Jan 23 22:33:45 2013 +0100
5.3 @@ -0,0 +1,55 @@
5.4 +/*
5.5 + * Copyright (c) 1994, 2008, 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.lang;
5.30 +
5.31 +/**
5.32 + * Thrown to indicate some unexpected internal error has occurred in
5.33 + * the Java Virtual Machine.
5.34 + *
5.35 + * @author unascribed
5.36 + * @since JDK1.0
5.37 + */
5.38 +public
5.39 +class InternalError extends VirtualMachineError {
5.40 + private static final long serialVersionUID = -9062593416125562365L;
5.41 +
5.42 + /**
5.43 + * Constructs an <code>InternalError</code> with no detail message.
5.44 + */
5.45 + public InternalError() {
5.46 + super();
5.47 + }
5.48 +
5.49 + /**
5.50 + * Constructs an <code>InternalError</code> with the specified
5.51 + * detail message.
5.52 + *
5.53 + * @param s the detail message.
5.54 + */
5.55 + public InternalError(String s) {
5.56 + super(s);
5.57 + }
5.58 +}
6.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
6.2 +++ b/emul/compact/src/main/java/java/lang/Iterable.java Wed Jan 23 22:33:45 2013 +0100
6.3 @@ -0,0 +1,46 @@
6.4 +/*
6.5 + * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
6.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6.7 + *
6.8 + * This code is free software; you can redistribute it and/or modify it
6.9 + * under the terms of the GNU General Public License version 2 only, as
6.10 + * published by the Free Software Foundation. Oracle designates this
6.11 + * particular file as subject to the "Classpath" exception as provided
6.12 + * by Oracle in the LICENSE file that accompanied this code.
6.13 + *
6.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
6.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
6.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
6.17 + * version 2 for more details (a copy is included in the LICENSE file that
6.18 + * accompanied this code).
6.19 + *
6.20 + * You should have received a copy of the GNU General Public License version
6.21 + * 2 along with this work; if not, write to the Free Software Foundation,
6.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
6.23 + *
6.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
6.25 + * or visit www.oracle.com if you need additional information or have any
6.26 + * questions.
6.27 + */
6.28 +
6.29 +package java.lang;
6.30 +
6.31 +import java.util.Iterator;
6.32 +
6.33 +/**
6.34 + * Implementing this interface allows an object to be the target of
6.35 + * the "foreach" statement.
6.36 + *
6.37 + * @param <T> the type of elements returned by the iterator
6.38 + *
6.39 + * @since 1.5
6.40 + */
6.41 +public interface Iterable<T> {
6.42 +
6.43 + /**
6.44 + * Returns an iterator over a set of elements of type T.
6.45 + *
6.46 + * @return an Iterator.
6.47 + */
6.48 + Iterator<T> iterator();
6.49 +}
7.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
7.2 +++ b/emul/compact/src/main/java/java/lang/Readable.java Wed Jan 23 22:33:45 2013 +0100
7.3 @@ -0,0 +1,55 @@
7.4 +/*
7.5 + * Copyright (c) 2003, 2010, 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.lang;
7.30 +
7.31 +import java.io.IOException;
7.32 +
7.33 +/**
7.34 + * A <tt>Readable</tt> is a source of characters. Characters from
7.35 + * a <tt>Readable</tt> are made available to callers of the read
7.36 + * method via a {@link java.nio.CharBuffer CharBuffer}.
7.37 + *
7.38 + * @since 1.5
7.39 + */
7.40 +
7.41 +public interface Readable {
7.42 +
7.43 + /**
7.44 + * Attempts to read characters into the specified character buffer.
7.45 + * The buffer is used as a repository of characters as-is: the only
7.46 + * changes made are the results of a put operation. No flipping or
7.47 + * rewinding of the buffer is performed.
7.48 + *
7.49 + * @param cb the buffer to read characters into
7.50 + * @return The number of {@code char} values added to the buffer,
7.51 + * or -1 if this source of characters is at its end
7.52 + * @throws IOException if an I/O error occurs
7.53 + * @throws NullPointerException if cb is null
7.54 + * @throws java.nio.ReadOnlyBufferException if cb is a read only buffer
7.55 + */
7.56 + public int read(java.nio.CharBuffer cb) throws IOException;
7.57 +
7.58 +}
8.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
8.2 +++ b/emul/compact/src/main/java/java/lang/SuppressWarnings.java Wed Jan 23 22:33:45 2013 +0100
8.3 @@ -0,0 +1,64 @@
8.4 +/*
8.5 + * Copyright (c) 2004, 2011, 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.lang;
8.30 +
8.31 +import java.lang.annotation.*;
8.32 +import static java.lang.annotation.ElementType.*;
8.33 +
8.34 +/**
8.35 + * Indicates that the named compiler warnings should be suppressed in the
8.36 + * annotated element (and in all program elements contained in the annotated
8.37 + * element). Note that the set of warnings suppressed in a given element is
8.38 + * a superset of the warnings suppressed in all containing elements. For
8.39 + * example, if you annotate a class to suppress one warning and annotate a
8.40 + * method to suppress another, both warnings will be suppressed in the method.
8.41 + *
8.42 + * <p>As a matter of style, programmers should always use this annotation
8.43 + * on the most deeply nested element where it is effective. If you want to
8.44 + * suppress a warning in a particular method, you should annotate that
8.45 + * method rather than its class.
8.46 + *
8.47 + * @since 1.5
8.48 + * @author Josh Bloch
8.49 + */
8.50 +@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
8.51 +@Retention(RetentionPolicy.SOURCE)
8.52 +public @interface SuppressWarnings {
8.53 + /**
8.54 + * The set of warnings that are to be suppressed by the compiler in the
8.55 + * annotated element. Duplicate names are permitted. The second and
8.56 + * successive occurrences of a name are ignored. The presence of
8.57 + * unrecognized warning names is <i>not</i> an error: Compilers must
8.58 + * ignore any warning names they do not recognize. They are, however,
8.59 + * free to emit a warning if an annotation contains an unrecognized
8.60 + * warning name.
8.61 + *
8.62 + * <p>Compiler vendors should document the warning names they support in
8.63 + * conjunction with this annotation type. They are encouraged to cooperate
8.64 + * to ensure that the same names work across multiple compilers.
8.65 + */
8.66 + String[] value();
8.67 +}
9.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
9.2 +++ b/emul/compact/src/main/java/java/util/AbstractCollection.java Wed Jan 23 22:33:45 2013 +0100
9.3 @@ -0,0 +1,457 @@
9.4 +/*
9.5 + * Copyright (c) 1997, 2010, 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 + * This class provides a skeletal implementation of the <tt>Collection</tt>
9.33 + * interface, to minimize the effort required to implement this interface. <p>
9.34 + *
9.35 + * To implement an unmodifiable collection, the programmer needs only to
9.36 + * extend this class and provide implementations for the <tt>iterator</tt> and
9.37 + * <tt>size</tt> methods. (The iterator returned by the <tt>iterator</tt>
9.38 + * method must implement <tt>hasNext</tt> and <tt>next</tt>.)<p>
9.39 + *
9.40 + * To implement a modifiable collection, the programmer must additionally
9.41 + * override this class's <tt>add</tt> method (which otherwise throws an
9.42 + * <tt>UnsupportedOperationException</tt>), and the iterator returned by the
9.43 + * <tt>iterator</tt> method must additionally implement its <tt>remove</tt>
9.44 + * method.<p>
9.45 + *
9.46 + * The programmer should generally provide a void (no argument) and
9.47 + * <tt>Collection</tt> constructor, as per the recommendation in the
9.48 + * <tt>Collection</tt> interface specification.<p>
9.49 + *
9.50 + * The documentation for each non-abstract method in this class describes its
9.51 + * implementation in detail. Each of these methods may be overridden if
9.52 + * the collection being implemented admits a more efficient implementation.<p>
9.53 + *
9.54 + * This class is a member of the
9.55 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
9.56 + * Java Collections Framework</a>.
9.57 + *
9.58 + * @author Josh Bloch
9.59 + * @author Neal Gafter
9.60 + * @see Collection
9.61 + * @since 1.2
9.62 + */
9.63 +
9.64 +public abstract class AbstractCollection<E> implements Collection<E> {
9.65 + /**
9.66 + * Sole constructor. (For invocation by subclass constructors, typically
9.67 + * implicit.)
9.68 + */
9.69 + protected AbstractCollection() {
9.70 + }
9.71 +
9.72 + // Query Operations
9.73 +
9.74 + /**
9.75 + * Returns an iterator over the elements contained in this collection.
9.76 + *
9.77 + * @return an iterator over the elements contained in this collection
9.78 + */
9.79 + public abstract Iterator<E> iterator();
9.80 +
9.81 + public abstract int size();
9.82 +
9.83 + /**
9.84 + * {@inheritDoc}
9.85 + *
9.86 + * <p>This implementation returns <tt>size() == 0</tt>.
9.87 + */
9.88 + public boolean isEmpty() {
9.89 + return size() == 0;
9.90 + }
9.91 +
9.92 + /**
9.93 + * {@inheritDoc}
9.94 + *
9.95 + * <p>This implementation iterates over the elements in the collection,
9.96 + * checking each element in turn for equality with the specified element.
9.97 + *
9.98 + * @throws ClassCastException {@inheritDoc}
9.99 + * @throws NullPointerException {@inheritDoc}
9.100 + */
9.101 + public boolean contains(Object o) {
9.102 + Iterator<E> it = iterator();
9.103 + if (o==null) {
9.104 + while (it.hasNext())
9.105 + if (it.next()==null)
9.106 + return true;
9.107 + } else {
9.108 + while (it.hasNext())
9.109 + if (o.equals(it.next()))
9.110 + return true;
9.111 + }
9.112 + return false;
9.113 + }
9.114 +
9.115 + /**
9.116 + * {@inheritDoc}
9.117 + *
9.118 + * <p>This implementation returns an array containing all the elements
9.119 + * returned by this collection's iterator, in the same order, stored in
9.120 + * consecutive elements of the array, starting with index {@code 0}.
9.121 + * The length of the returned array is equal to the number of elements
9.122 + * returned by the iterator, even if the size of this collection changes
9.123 + * during iteration, as might happen if the collection permits
9.124 + * concurrent modification during iteration. The {@code size} method is
9.125 + * called only as an optimization hint; the correct result is returned
9.126 + * even if the iterator returns a different number of elements.
9.127 + *
9.128 + * <p>This method is equivalent to:
9.129 + *
9.130 + * <pre> {@code
9.131 + * List<E> list = new ArrayList<E>(size());
9.132 + * for (E e : this)
9.133 + * list.add(e);
9.134 + * return list.toArray();
9.135 + * }</pre>
9.136 + */
9.137 + public Object[] toArray() {
9.138 + // Estimate size of array; be prepared to see more or fewer elements
9.139 + Object[] r = new Object[size()];
9.140 + Iterator<E> it = iterator();
9.141 + for (int i = 0; i < r.length; i++) {
9.142 + if (! it.hasNext()) // fewer elements than expected
9.143 + return Arrays.copyOf(r, i);
9.144 + r[i] = it.next();
9.145 + }
9.146 + return it.hasNext() ? finishToArray(r, it) : r;
9.147 + }
9.148 +
9.149 + /**
9.150 + * {@inheritDoc}
9.151 + *
9.152 + * <p>This implementation returns an array containing all the elements
9.153 + * returned by this collection's iterator in the same order, stored in
9.154 + * consecutive elements of the array, starting with index {@code 0}.
9.155 + * If the number of elements returned by the iterator is too large to
9.156 + * fit into the specified array, then the elements are returned in a
9.157 + * newly allocated array with length equal to the number of elements
9.158 + * returned by the iterator, even if the size of this collection
9.159 + * changes during iteration, as might happen if the collection permits
9.160 + * concurrent modification during iteration. The {@code size} method is
9.161 + * called only as an optimization hint; the correct result is returned
9.162 + * even if the iterator returns a different number of elements.
9.163 + *
9.164 + * <p>This method is equivalent to:
9.165 + *
9.166 + * <pre> {@code
9.167 + * List<E> list = new ArrayList<E>(size());
9.168 + * for (E e : this)
9.169 + * list.add(e);
9.170 + * return list.toArray(a);
9.171 + * }</pre>
9.172 + *
9.173 + * @throws ArrayStoreException {@inheritDoc}
9.174 + * @throws NullPointerException {@inheritDoc}
9.175 + */
9.176 + public <T> T[] toArray(T[] a) {
9.177 + // Estimate size of array; be prepared to see more or fewer elements
9.178 + int size = size();
9.179 + T[] r = a.length >= size ? a :
9.180 + (T[])java.lang.reflect.Array
9.181 + .newInstance(a.getClass().getComponentType(), size);
9.182 + Iterator<E> it = iterator();
9.183 +
9.184 + for (int i = 0; i < r.length; i++) {
9.185 + if (! it.hasNext()) { // fewer elements than expected
9.186 + if (a != r)
9.187 + return Arrays.copyOf(r, i);
9.188 + r[i] = null; // null-terminate
9.189 + return r;
9.190 + }
9.191 + r[i] = (T)it.next();
9.192 + }
9.193 + return it.hasNext() ? finishToArray(r, it) : r;
9.194 + }
9.195 +
9.196 + /**
9.197 + * The maximum size of array to allocate.
9.198 + * Some VMs reserve some header words in an array.
9.199 + * Attempts to allocate larger arrays may result in
9.200 + * OutOfMemoryError: Requested array size exceeds VM limit
9.201 + */
9.202 + private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
9.203 +
9.204 + /**
9.205 + * Reallocates the array being used within toArray when the iterator
9.206 + * returned more elements than expected, and finishes filling it from
9.207 + * the iterator.
9.208 + *
9.209 + * @param r the array, replete with previously stored elements
9.210 + * @param it the in-progress iterator over this collection
9.211 + * @return array containing the elements in the given array, plus any
9.212 + * further elements returned by the iterator, trimmed to size
9.213 + */
9.214 + private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
9.215 + int i = r.length;
9.216 + while (it.hasNext()) {
9.217 + int cap = r.length;
9.218 + if (i == cap) {
9.219 + int newCap = cap + (cap >> 1) + 1;
9.220 + // overflow-conscious code
9.221 + if (newCap - MAX_ARRAY_SIZE > 0)
9.222 + newCap = hugeCapacity(cap + 1);
9.223 + r = Arrays.copyOf(r, newCap);
9.224 + }
9.225 + r[i++] = (T)it.next();
9.226 + }
9.227 + // trim if overallocated
9.228 + return (i == r.length) ? r : Arrays.copyOf(r, i);
9.229 + }
9.230 +
9.231 + private static int hugeCapacity(int minCapacity) {
9.232 + if (minCapacity < 0) // overflow
9.233 + throw new OutOfMemoryError
9.234 + ("Required array size too large");
9.235 + return (minCapacity > MAX_ARRAY_SIZE) ?
9.236 + Integer.MAX_VALUE :
9.237 + MAX_ARRAY_SIZE;
9.238 + }
9.239 +
9.240 + // Modification Operations
9.241 +
9.242 + /**
9.243 + * {@inheritDoc}
9.244 + *
9.245 + * <p>This implementation always throws an
9.246 + * <tt>UnsupportedOperationException</tt>.
9.247 + *
9.248 + * @throws UnsupportedOperationException {@inheritDoc}
9.249 + * @throws ClassCastException {@inheritDoc}
9.250 + * @throws NullPointerException {@inheritDoc}
9.251 + * @throws IllegalArgumentException {@inheritDoc}
9.252 + * @throws IllegalStateException {@inheritDoc}
9.253 + */
9.254 + public boolean add(E e) {
9.255 + throw new UnsupportedOperationException();
9.256 + }
9.257 +
9.258 + /**
9.259 + * {@inheritDoc}
9.260 + *
9.261 + * <p>This implementation iterates over the collection looking for the
9.262 + * specified element. If it finds the element, it removes the element
9.263 + * from the collection using the iterator's remove method.
9.264 + *
9.265 + * <p>Note that this implementation throws an
9.266 + * <tt>UnsupportedOperationException</tt> if the iterator returned by this
9.267 + * collection's iterator method does not implement the <tt>remove</tt>
9.268 + * method and this collection contains the specified object.
9.269 + *
9.270 + * @throws UnsupportedOperationException {@inheritDoc}
9.271 + * @throws ClassCastException {@inheritDoc}
9.272 + * @throws NullPointerException {@inheritDoc}
9.273 + */
9.274 + public boolean remove(Object o) {
9.275 + Iterator<E> it = iterator();
9.276 + if (o==null) {
9.277 + while (it.hasNext()) {
9.278 + if (it.next()==null) {
9.279 + it.remove();
9.280 + return true;
9.281 + }
9.282 + }
9.283 + } else {
9.284 + while (it.hasNext()) {
9.285 + if (o.equals(it.next())) {
9.286 + it.remove();
9.287 + return true;
9.288 + }
9.289 + }
9.290 + }
9.291 + return false;
9.292 + }
9.293 +
9.294 +
9.295 + // Bulk Operations
9.296 +
9.297 + /**
9.298 + * {@inheritDoc}
9.299 + *
9.300 + * <p>This implementation iterates over the specified collection,
9.301 + * checking each element returned by the iterator in turn to see
9.302 + * if it's contained in this collection. If all elements are so
9.303 + * contained <tt>true</tt> is returned, otherwise <tt>false</tt>.
9.304 + *
9.305 + * @throws ClassCastException {@inheritDoc}
9.306 + * @throws NullPointerException {@inheritDoc}
9.307 + * @see #contains(Object)
9.308 + */
9.309 + public boolean containsAll(Collection<?> c) {
9.310 + for (Object e : c)
9.311 + if (!contains(e))
9.312 + return false;
9.313 + return true;
9.314 + }
9.315 +
9.316 + /**
9.317 + * {@inheritDoc}
9.318 + *
9.319 + * <p>This implementation iterates over the specified collection, and adds
9.320 + * each object returned by the iterator to this collection, in turn.
9.321 + *
9.322 + * <p>Note that this implementation will throw an
9.323 + * <tt>UnsupportedOperationException</tt> unless <tt>add</tt> is
9.324 + * overridden (assuming the specified collection is non-empty).
9.325 + *
9.326 + * @throws UnsupportedOperationException {@inheritDoc}
9.327 + * @throws ClassCastException {@inheritDoc}
9.328 + * @throws NullPointerException {@inheritDoc}
9.329 + * @throws IllegalArgumentException {@inheritDoc}
9.330 + * @throws IllegalStateException {@inheritDoc}
9.331 + *
9.332 + * @see #add(Object)
9.333 + */
9.334 + public boolean addAll(Collection<? extends E> c) {
9.335 + boolean modified = false;
9.336 + for (E e : c)
9.337 + if (add(e))
9.338 + modified = true;
9.339 + return modified;
9.340 + }
9.341 +
9.342 + /**
9.343 + * {@inheritDoc}
9.344 + *
9.345 + * <p>This implementation iterates over this collection, checking each
9.346 + * element returned by the iterator in turn to see if it's contained
9.347 + * in the specified collection. If it's so contained, it's removed from
9.348 + * this collection with the iterator's <tt>remove</tt> method.
9.349 + *
9.350 + * <p>Note that this implementation will throw an
9.351 + * <tt>UnsupportedOperationException</tt> if the iterator returned by the
9.352 + * <tt>iterator</tt> method does not implement the <tt>remove</tt> method
9.353 + * and this collection contains one or more elements in common with the
9.354 + * specified collection.
9.355 + *
9.356 + * @throws UnsupportedOperationException {@inheritDoc}
9.357 + * @throws ClassCastException {@inheritDoc}
9.358 + * @throws NullPointerException {@inheritDoc}
9.359 + *
9.360 + * @see #remove(Object)
9.361 + * @see #contains(Object)
9.362 + */
9.363 + public boolean removeAll(Collection<?> c) {
9.364 + boolean modified = false;
9.365 + Iterator<?> it = iterator();
9.366 + while (it.hasNext()) {
9.367 + if (c.contains(it.next())) {
9.368 + it.remove();
9.369 + modified = true;
9.370 + }
9.371 + }
9.372 + return modified;
9.373 + }
9.374 +
9.375 + /**
9.376 + * {@inheritDoc}
9.377 + *
9.378 + * <p>This implementation iterates over this collection, checking each
9.379 + * element returned by the iterator in turn to see if it's contained
9.380 + * in the specified collection. If it's not so contained, it's removed
9.381 + * from this collection with the iterator's <tt>remove</tt> method.
9.382 + *
9.383 + * <p>Note that this implementation will throw an
9.384 + * <tt>UnsupportedOperationException</tt> if the iterator returned by the
9.385 + * <tt>iterator</tt> method does not implement the <tt>remove</tt> method
9.386 + * and this collection contains one or more elements not present in the
9.387 + * specified collection.
9.388 + *
9.389 + * @throws UnsupportedOperationException {@inheritDoc}
9.390 + * @throws ClassCastException {@inheritDoc}
9.391 + * @throws NullPointerException {@inheritDoc}
9.392 + *
9.393 + * @see #remove(Object)
9.394 + * @see #contains(Object)
9.395 + */
9.396 + public boolean retainAll(Collection<?> c) {
9.397 + boolean modified = false;
9.398 + Iterator<E> it = iterator();
9.399 + while (it.hasNext()) {
9.400 + if (!c.contains(it.next())) {
9.401 + it.remove();
9.402 + modified = true;
9.403 + }
9.404 + }
9.405 + return modified;
9.406 + }
9.407 +
9.408 + /**
9.409 + * {@inheritDoc}
9.410 + *
9.411 + * <p>This implementation iterates over this collection, removing each
9.412 + * element using the <tt>Iterator.remove</tt> operation. Most
9.413 + * implementations will probably choose to override this method for
9.414 + * efficiency.
9.415 + *
9.416 + * <p>Note that this implementation will throw an
9.417 + * <tt>UnsupportedOperationException</tt> if the iterator returned by this
9.418 + * collection's <tt>iterator</tt> method does not implement the
9.419 + * <tt>remove</tt> method and this collection is non-empty.
9.420 + *
9.421 + * @throws UnsupportedOperationException {@inheritDoc}
9.422 + */
9.423 + public void clear() {
9.424 + Iterator<E> it = iterator();
9.425 + while (it.hasNext()) {
9.426 + it.next();
9.427 + it.remove();
9.428 + }
9.429 + }
9.430 +
9.431 +
9.432 + // String conversion
9.433 +
9.434 + /**
9.435 + * Returns a string representation of this collection. The string
9.436 + * representation consists of a list of the collection's elements in the
9.437 + * order they are returned by its iterator, enclosed in square brackets
9.438 + * (<tt>"[]"</tt>). Adjacent elements are separated by the characters
9.439 + * <tt>", "</tt> (comma and space). Elements are converted to strings as
9.440 + * by {@link String#valueOf(Object)}.
9.441 + *
9.442 + * @return a string representation of this collection
9.443 + */
9.444 + public String toString() {
9.445 + Iterator<E> it = iterator();
9.446 + if (! it.hasNext())
9.447 + return "[]";
9.448 +
9.449 + StringBuilder sb = new StringBuilder();
9.450 + sb.append('[');
9.451 + for (;;) {
9.452 + E e = it.next();
9.453 + sb.append(e == this ? "(this Collection)" : e);
9.454 + if (! it.hasNext())
9.455 + return sb.append(']').toString();
9.456 + sb.append(',').append(' ');
9.457 + }
9.458 + }
9.459 +
9.460 +}
10.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
10.2 +++ b/emul/compact/src/main/java/java/util/AbstractList.java Wed Jan 23 22:33:45 2013 +0100
10.3 @@ -0,0 +1,781 @@
10.4 +/*
10.5 + * Copyright (c) 1997, 2010, 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 + * This class provides a skeletal implementation of the {@link List}
10.33 + * interface to minimize the effort required to implement this interface
10.34 + * backed by a "random access" data store (such as an array). For sequential
10.35 + * access data (such as a linked list), {@link AbstractSequentialList} should
10.36 + * be used in preference to this class.
10.37 + *
10.38 + * <p>To implement an unmodifiable list, the programmer needs only to extend
10.39 + * this class and provide implementations for the {@link #get(int)} and
10.40 + * {@link List#size() size()} methods.
10.41 + *
10.42 + * <p>To implement a modifiable list, the programmer must additionally
10.43 + * override the {@link #set(int, Object) set(int, E)} method (which otherwise
10.44 + * throws an {@code UnsupportedOperationException}). If the list is
10.45 + * variable-size the programmer must additionally override the
10.46 + * {@link #add(int, Object) add(int, E)} and {@link #remove(int)} methods.
10.47 + *
10.48 + * <p>The programmer should generally provide a void (no argument) and collection
10.49 + * constructor, as per the recommendation in the {@link Collection} interface
10.50 + * specification.
10.51 + *
10.52 + * <p>Unlike the other abstract collection implementations, the programmer does
10.53 + * <i>not</i> have to provide an iterator implementation; the iterator and
10.54 + * list iterator are implemented by this class, on top of the "random access"
10.55 + * methods:
10.56 + * {@link #get(int)},
10.57 + * {@link #set(int, Object) set(int, E)},
10.58 + * {@link #add(int, Object) add(int, E)} and
10.59 + * {@link #remove(int)}.
10.60 + *
10.61 + * <p>The documentation for each non-abstract method in this class describes its
10.62 + * implementation in detail. Each of these methods may be overridden if the
10.63 + * collection being implemented admits a more efficient implementation.
10.64 + *
10.65 + * <p>This class is a member of the
10.66 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
10.67 + * Java Collections Framework</a>.
10.68 + *
10.69 + * @author Josh Bloch
10.70 + * @author Neal Gafter
10.71 + * @since 1.2
10.72 + */
10.73 +
10.74 +public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
10.75 + /**
10.76 + * Sole constructor. (For invocation by subclass constructors, typically
10.77 + * implicit.)
10.78 + */
10.79 + protected AbstractList() {
10.80 + }
10.81 +
10.82 + /**
10.83 + * Appends the specified element to the end of this list (optional
10.84 + * operation).
10.85 + *
10.86 + * <p>Lists that support this operation may place limitations on what
10.87 + * elements may be added to this list. In particular, some
10.88 + * lists will refuse to add null elements, and others will impose
10.89 + * restrictions on the type of elements that may be added. List
10.90 + * classes should clearly specify in their documentation any restrictions
10.91 + * on what elements may be added.
10.92 + *
10.93 + * <p>This implementation calls {@code add(size(), e)}.
10.94 + *
10.95 + * <p>Note that this implementation throws an
10.96 + * {@code UnsupportedOperationException} unless
10.97 + * {@link #add(int, Object) add(int, E)} is overridden.
10.98 + *
10.99 + * @param e element to be appended to this list
10.100 + * @return {@code true} (as specified by {@link Collection#add})
10.101 + * @throws UnsupportedOperationException if the {@code add} operation
10.102 + * is not supported by this list
10.103 + * @throws ClassCastException if the class of the specified element
10.104 + * prevents it from being added to this list
10.105 + * @throws NullPointerException if the specified element is null and this
10.106 + * list does not permit null elements
10.107 + * @throws IllegalArgumentException if some property of this element
10.108 + * prevents it from being added to this list
10.109 + */
10.110 + public boolean add(E e) {
10.111 + add(size(), e);
10.112 + return true;
10.113 + }
10.114 +
10.115 + /**
10.116 + * {@inheritDoc}
10.117 + *
10.118 + * @throws IndexOutOfBoundsException {@inheritDoc}
10.119 + */
10.120 + abstract public E get(int index);
10.121 +
10.122 + /**
10.123 + * {@inheritDoc}
10.124 + *
10.125 + * <p>This implementation always throws an
10.126 + * {@code UnsupportedOperationException}.
10.127 + *
10.128 + * @throws UnsupportedOperationException {@inheritDoc}
10.129 + * @throws ClassCastException {@inheritDoc}
10.130 + * @throws NullPointerException {@inheritDoc}
10.131 + * @throws IllegalArgumentException {@inheritDoc}
10.132 + * @throws IndexOutOfBoundsException {@inheritDoc}
10.133 + */
10.134 + public E set(int index, E element) {
10.135 + throw new UnsupportedOperationException();
10.136 + }
10.137 +
10.138 + /**
10.139 + * {@inheritDoc}
10.140 + *
10.141 + * <p>This implementation always throws an
10.142 + * {@code UnsupportedOperationException}.
10.143 + *
10.144 + * @throws UnsupportedOperationException {@inheritDoc}
10.145 + * @throws ClassCastException {@inheritDoc}
10.146 + * @throws NullPointerException {@inheritDoc}
10.147 + * @throws IllegalArgumentException {@inheritDoc}
10.148 + * @throws IndexOutOfBoundsException {@inheritDoc}
10.149 + */
10.150 + public void add(int index, E element) {
10.151 + throw new UnsupportedOperationException();
10.152 + }
10.153 +
10.154 + /**
10.155 + * {@inheritDoc}
10.156 + *
10.157 + * <p>This implementation always throws an
10.158 + * {@code UnsupportedOperationException}.
10.159 + *
10.160 + * @throws UnsupportedOperationException {@inheritDoc}
10.161 + * @throws IndexOutOfBoundsException {@inheritDoc}
10.162 + */
10.163 + public E remove(int index) {
10.164 + throw new UnsupportedOperationException();
10.165 + }
10.166 +
10.167 +
10.168 + // Search Operations
10.169 +
10.170 + /**
10.171 + * {@inheritDoc}
10.172 + *
10.173 + * <p>This implementation first gets a list iterator (with
10.174 + * {@code listIterator()}). Then, it iterates over the list until the
10.175 + * specified element is found or the end of the list is reached.
10.176 + *
10.177 + * @throws ClassCastException {@inheritDoc}
10.178 + * @throws NullPointerException {@inheritDoc}
10.179 + */
10.180 + public int indexOf(Object o) {
10.181 + ListIterator<E> it = listIterator();
10.182 + if (o==null) {
10.183 + while (it.hasNext())
10.184 + if (it.next()==null)
10.185 + return it.previousIndex();
10.186 + } else {
10.187 + while (it.hasNext())
10.188 + if (o.equals(it.next()))
10.189 + return it.previousIndex();
10.190 + }
10.191 + return -1;
10.192 + }
10.193 +
10.194 + /**
10.195 + * {@inheritDoc}
10.196 + *
10.197 + * <p>This implementation first gets a list iterator that points to the end
10.198 + * of the list (with {@code listIterator(size())}). Then, it iterates
10.199 + * backwards over the list until the specified element is found, or the
10.200 + * beginning of the list is reached.
10.201 + *
10.202 + * @throws ClassCastException {@inheritDoc}
10.203 + * @throws NullPointerException {@inheritDoc}
10.204 + */
10.205 + public int lastIndexOf(Object o) {
10.206 + ListIterator<E> it = listIterator(size());
10.207 + if (o==null) {
10.208 + while (it.hasPrevious())
10.209 + if (it.previous()==null)
10.210 + return it.nextIndex();
10.211 + } else {
10.212 + while (it.hasPrevious())
10.213 + if (o.equals(it.previous()))
10.214 + return it.nextIndex();
10.215 + }
10.216 + return -1;
10.217 + }
10.218 +
10.219 +
10.220 + // Bulk Operations
10.221 +
10.222 + /**
10.223 + * Removes all of the elements from this list (optional operation).
10.224 + * The list will be empty after this call returns.
10.225 + *
10.226 + * <p>This implementation calls {@code removeRange(0, size())}.
10.227 + *
10.228 + * <p>Note that this implementation throws an
10.229 + * {@code UnsupportedOperationException} unless {@code remove(int
10.230 + * index)} or {@code removeRange(int fromIndex, int toIndex)} is
10.231 + * overridden.
10.232 + *
10.233 + * @throws UnsupportedOperationException if the {@code clear} operation
10.234 + * is not supported by this list
10.235 + */
10.236 + public void clear() {
10.237 + removeRange(0, size());
10.238 + }
10.239 +
10.240 + /**
10.241 + * {@inheritDoc}
10.242 + *
10.243 + * <p>This implementation gets an iterator over the specified collection
10.244 + * and iterates over it, inserting the elements obtained from the
10.245 + * iterator into this list at the appropriate position, one at a time,
10.246 + * using {@code add(int, E)}.
10.247 + * Many implementations will override this method for efficiency.
10.248 + *
10.249 + * <p>Note that this implementation throws an
10.250 + * {@code UnsupportedOperationException} unless
10.251 + * {@link #add(int, Object) add(int, E)} is overridden.
10.252 + *
10.253 + * @throws UnsupportedOperationException {@inheritDoc}
10.254 + * @throws ClassCastException {@inheritDoc}
10.255 + * @throws NullPointerException {@inheritDoc}
10.256 + * @throws IllegalArgumentException {@inheritDoc}
10.257 + * @throws IndexOutOfBoundsException {@inheritDoc}
10.258 + */
10.259 + public boolean addAll(int index, Collection<? extends E> c) {
10.260 + rangeCheckForAdd(index);
10.261 + boolean modified = false;
10.262 + for (E e : c) {
10.263 + add(index++, e);
10.264 + modified = true;
10.265 + }
10.266 + return modified;
10.267 + }
10.268 +
10.269 +
10.270 + // Iterators
10.271 +
10.272 + /**
10.273 + * Returns an iterator over the elements in this list in proper sequence.
10.274 + *
10.275 + * <p>This implementation returns a straightforward implementation of the
10.276 + * iterator interface, relying on the backing list's {@code size()},
10.277 + * {@code get(int)}, and {@code remove(int)} methods.
10.278 + *
10.279 + * <p>Note that the iterator returned by this method will throw an
10.280 + * {@link UnsupportedOperationException} in response to its
10.281 + * {@code remove} method unless the list's {@code remove(int)} method is
10.282 + * overridden.
10.283 + *
10.284 + * <p>This implementation can be made to throw runtime exceptions in the
10.285 + * face of concurrent modification, as described in the specification
10.286 + * for the (protected) {@link #modCount} field.
10.287 + *
10.288 + * @return an iterator over the elements in this list in proper sequence
10.289 + */
10.290 + public Iterator<E> iterator() {
10.291 + return new Itr();
10.292 + }
10.293 +
10.294 + /**
10.295 + * {@inheritDoc}
10.296 + *
10.297 + * <p>This implementation returns {@code listIterator(0)}.
10.298 + *
10.299 + * @see #listIterator(int)
10.300 + */
10.301 + public ListIterator<E> listIterator() {
10.302 + return listIterator(0);
10.303 + }
10.304 +
10.305 + /**
10.306 + * {@inheritDoc}
10.307 + *
10.308 + * <p>This implementation returns a straightforward implementation of the
10.309 + * {@code ListIterator} interface that extends the implementation of the
10.310 + * {@code Iterator} interface returned by the {@code iterator()} method.
10.311 + * The {@code ListIterator} implementation relies on the backing list's
10.312 + * {@code get(int)}, {@code set(int, E)}, {@code add(int, E)}
10.313 + * and {@code remove(int)} methods.
10.314 + *
10.315 + * <p>Note that the list iterator returned by this implementation will
10.316 + * throw an {@link UnsupportedOperationException} in response to its
10.317 + * {@code remove}, {@code set} and {@code add} methods unless the
10.318 + * list's {@code remove(int)}, {@code set(int, E)}, and
10.319 + * {@code add(int, E)} methods are overridden.
10.320 + *
10.321 + * <p>This implementation can be made to throw runtime exceptions in the
10.322 + * face of concurrent modification, as described in the specification for
10.323 + * the (protected) {@link #modCount} field.
10.324 + *
10.325 + * @throws IndexOutOfBoundsException {@inheritDoc}
10.326 + */
10.327 + public ListIterator<E> listIterator(final int index) {
10.328 + rangeCheckForAdd(index);
10.329 +
10.330 + return new ListItr(index);
10.331 + }
10.332 +
10.333 + private class Itr implements Iterator<E> {
10.334 + /**
10.335 + * Index of element to be returned by subsequent call to next.
10.336 + */
10.337 + int cursor = 0;
10.338 +
10.339 + /**
10.340 + * Index of element returned by most recent call to next or
10.341 + * previous. Reset to -1 if this element is deleted by a call
10.342 + * to remove.
10.343 + */
10.344 + int lastRet = -1;
10.345 +
10.346 + /**
10.347 + * The modCount value that the iterator believes that the backing
10.348 + * List should have. If this expectation is violated, the iterator
10.349 + * has detected concurrent modification.
10.350 + */
10.351 + int expectedModCount = modCount;
10.352 +
10.353 + public boolean hasNext() {
10.354 + return cursor != size();
10.355 + }
10.356 +
10.357 + public E next() {
10.358 + checkForComodification();
10.359 + try {
10.360 + int i = cursor;
10.361 + E next = get(i);
10.362 + lastRet = i;
10.363 + cursor = i + 1;
10.364 + return next;
10.365 + } catch (IndexOutOfBoundsException e) {
10.366 + checkForComodification();
10.367 + throw new NoSuchElementException();
10.368 + }
10.369 + }
10.370 +
10.371 + public void remove() {
10.372 + if (lastRet < 0)
10.373 + throw new IllegalStateException();
10.374 + checkForComodification();
10.375 +
10.376 + try {
10.377 + AbstractList.this.remove(lastRet);
10.378 + if (lastRet < cursor)
10.379 + cursor--;
10.380 + lastRet = -1;
10.381 + expectedModCount = modCount;
10.382 + } catch (IndexOutOfBoundsException e) {
10.383 + throw new ConcurrentModificationException();
10.384 + }
10.385 + }
10.386 +
10.387 + final void checkForComodification() {
10.388 + if (modCount != expectedModCount)
10.389 + throw new ConcurrentModificationException();
10.390 + }
10.391 + }
10.392 +
10.393 + private class ListItr extends Itr implements ListIterator<E> {
10.394 + ListItr(int index) {
10.395 + cursor = index;
10.396 + }
10.397 +
10.398 + public boolean hasPrevious() {
10.399 + return cursor != 0;
10.400 + }
10.401 +
10.402 + public E previous() {
10.403 + checkForComodification();
10.404 + try {
10.405 + int i = cursor - 1;
10.406 + E previous = get(i);
10.407 + lastRet = cursor = i;
10.408 + return previous;
10.409 + } catch (IndexOutOfBoundsException e) {
10.410 + checkForComodification();
10.411 + throw new NoSuchElementException();
10.412 + }
10.413 + }
10.414 +
10.415 + public int nextIndex() {
10.416 + return cursor;
10.417 + }
10.418 +
10.419 + public int previousIndex() {
10.420 + return cursor-1;
10.421 + }
10.422 +
10.423 + public void set(E e) {
10.424 + if (lastRet < 0)
10.425 + throw new IllegalStateException();
10.426 + checkForComodification();
10.427 +
10.428 + try {
10.429 + AbstractList.this.set(lastRet, e);
10.430 + expectedModCount = modCount;
10.431 + } catch (IndexOutOfBoundsException ex) {
10.432 + throw new ConcurrentModificationException();
10.433 + }
10.434 + }
10.435 +
10.436 + public void add(E e) {
10.437 + checkForComodification();
10.438 +
10.439 + try {
10.440 + int i = cursor;
10.441 + AbstractList.this.add(i, e);
10.442 + lastRet = -1;
10.443 + cursor = i + 1;
10.444 + expectedModCount = modCount;
10.445 + } catch (IndexOutOfBoundsException ex) {
10.446 + throw new ConcurrentModificationException();
10.447 + }
10.448 + }
10.449 + }
10.450 +
10.451 + /**
10.452 + * {@inheritDoc}
10.453 + *
10.454 + * <p>This implementation returns a list that subclasses
10.455 + * {@code AbstractList}. The subclass stores, in private fields, the
10.456 + * offset of the subList within the backing list, the size of the subList
10.457 + * (which can change over its lifetime), and the expected
10.458 + * {@code modCount} value of the backing list. There are two variants
10.459 + * of the subclass, one of which implements {@code RandomAccess}.
10.460 + * If this list implements {@code RandomAccess} the returned list will
10.461 + * be an instance of the subclass that implements {@code RandomAccess}.
10.462 + *
10.463 + * <p>The subclass's {@code set(int, E)}, {@code get(int)},
10.464 + * {@code add(int, E)}, {@code remove(int)}, {@code addAll(int,
10.465 + * Collection)} and {@code removeRange(int, int)} methods all
10.466 + * delegate to the corresponding methods on the backing abstract list,
10.467 + * after bounds-checking the index and adjusting for the offset. The
10.468 + * {@code addAll(Collection c)} method merely returns {@code addAll(size,
10.469 + * c)}.
10.470 + *
10.471 + * <p>The {@code listIterator(int)} method returns a "wrapper object"
10.472 + * over a list iterator on the backing list, which is created with the
10.473 + * corresponding method on the backing list. The {@code iterator} method
10.474 + * merely returns {@code listIterator()}, and the {@code size} method
10.475 + * merely returns the subclass's {@code size} field.
10.476 + *
10.477 + * <p>All methods first check to see if the actual {@code modCount} of
10.478 + * the backing list is equal to its expected value, and throw a
10.479 + * {@code ConcurrentModificationException} if it is not.
10.480 + *
10.481 + * @throws IndexOutOfBoundsException if an endpoint index value is out of range
10.482 + * {@code (fromIndex < 0 || toIndex > size)}
10.483 + * @throws IllegalArgumentException if the endpoint indices are out of order
10.484 + * {@code (fromIndex > toIndex)}
10.485 + */
10.486 + public List<E> subList(int fromIndex, int toIndex) {
10.487 + return (this instanceof RandomAccess ?
10.488 + new RandomAccessSubList<>(this, fromIndex, toIndex) :
10.489 + new SubList<>(this, fromIndex, toIndex));
10.490 + }
10.491 +
10.492 + // Comparison and hashing
10.493 +
10.494 + /**
10.495 + * Compares the specified object with this list for equality. Returns
10.496 + * {@code true} if and only if the specified object is also a list, both
10.497 + * lists have the same size, and all corresponding pairs of elements in
10.498 + * the two lists are <i>equal</i>. (Two elements {@code e1} and
10.499 + * {@code e2} are <i>equal</i> if {@code (e1==null ? e2==null :
10.500 + * e1.equals(e2))}.) In other words, two lists are defined to be
10.501 + * equal if they contain the same elements in the same order.<p>
10.502 + *
10.503 + * This implementation first checks if the specified object is this
10.504 + * list. If so, it returns {@code true}; if not, it checks if the
10.505 + * specified object is a list. If not, it returns {@code false}; if so,
10.506 + * it iterates over both lists, comparing corresponding pairs of elements.
10.507 + * If any comparison returns {@code false}, this method returns
10.508 + * {@code false}. If either iterator runs out of elements before the
10.509 + * other it returns {@code false} (as the lists are of unequal length);
10.510 + * otherwise it returns {@code true} when the iterations complete.
10.511 + *
10.512 + * @param o the object to be compared for equality with this list
10.513 + * @return {@code true} if the specified object is equal to this list
10.514 + */
10.515 + public boolean equals(Object o) {
10.516 + if (o == this)
10.517 + return true;
10.518 + if (!(o instanceof List))
10.519 + return false;
10.520 +
10.521 + ListIterator<E> e1 = listIterator();
10.522 + ListIterator e2 = ((List) o).listIterator();
10.523 + while (e1.hasNext() && e2.hasNext()) {
10.524 + E o1 = e1.next();
10.525 + Object o2 = e2.next();
10.526 + if (!(o1==null ? o2==null : o1.equals(o2)))
10.527 + return false;
10.528 + }
10.529 + return !(e1.hasNext() || e2.hasNext());
10.530 + }
10.531 +
10.532 + /**
10.533 + * Returns the hash code value for this list.
10.534 + *
10.535 + * <p>This implementation uses exactly the code that is used to define the
10.536 + * list hash function in the documentation for the {@link List#hashCode}
10.537 + * method.
10.538 + *
10.539 + * @return the hash code value for this list
10.540 + */
10.541 + public int hashCode() {
10.542 + int hashCode = 1;
10.543 + for (E e : this)
10.544 + hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
10.545 + return hashCode;
10.546 + }
10.547 +
10.548 + /**
10.549 + * Removes from this list all of the elements whose index is between
10.550 + * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
10.551 + * Shifts any succeeding elements to the left (reduces their index).
10.552 + * This call shortens the list by {@code (toIndex - fromIndex)} elements.
10.553 + * (If {@code toIndex==fromIndex}, this operation has no effect.)
10.554 + *
10.555 + * <p>This method is called by the {@code clear} operation on this list
10.556 + * and its subLists. Overriding this method to take advantage of
10.557 + * the internals of the list implementation can <i>substantially</i>
10.558 + * improve the performance of the {@code clear} operation on this list
10.559 + * and its subLists.
10.560 + *
10.561 + * <p>This implementation gets a list iterator positioned before
10.562 + * {@code fromIndex}, and repeatedly calls {@code ListIterator.next}
10.563 + * followed by {@code ListIterator.remove} until the entire range has
10.564 + * been removed. <b>Note: if {@code ListIterator.remove} requires linear
10.565 + * time, this implementation requires quadratic time.</b>
10.566 + *
10.567 + * @param fromIndex index of first element to be removed
10.568 + * @param toIndex index after last element to be removed
10.569 + */
10.570 + protected void removeRange(int fromIndex, int toIndex) {
10.571 + ListIterator<E> it = listIterator(fromIndex);
10.572 + for (int i=0, n=toIndex-fromIndex; i<n; i++) {
10.573 + it.next();
10.574 + it.remove();
10.575 + }
10.576 + }
10.577 +
10.578 + /**
10.579 + * The number of times this list has been <i>structurally modified</i>.
10.580 + * Structural modifications are those that change the size of the
10.581 + * list, or otherwise perturb it in such a fashion that iterations in
10.582 + * progress may yield incorrect results.
10.583 + *
10.584 + * <p>This field is used by the iterator and list iterator implementation
10.585 + * returned by the {@code iterator} and {@code listIterator} methods.
10.586 + * If the value of this field changes unexpectedly, the iterator (or list
10.587 + * iterator) will throw a {@code ConcurrentModificationException} in
10.588 + * response to the {@code next}, {@code remove}, {@code previous},
10.589 + * {@code set} or {@code add} operations. This provides
10.590 + * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
10.591 + * the face of concurrent modification during iteration.
10.592 + *
10.593 + * <p><b>Use of this field by subclasses is optional.</b> If a subclass
10.594 + * wishes to provide fail-fast iterators (and list iterators), then it
10.595 + * merely has to increment this field in its {@code add(int, E)} and
10.596 + * {@code remove(int)} methods (and any other methods that it overrides
10.597 + * that result in structural modifications to the list). A single call to
10.598 + * {@code add(int, E)} or {@code remove(int)} must add no more than
10.599 + * one to this field, or the iterators (and list iterators) will throw
10.600 + * bogus {@code ConcurrentModificationExceptions}. If an implementation
10.601 + * does not wish to provide fail-fast iterators, this field may be
10.602 + * ignored.
10.603 + */
10.604 + protected transient int modCount = 0;
10.605 +
10.606 + private void rangeCheckForAdd(int index) {
10.607 + if (index < 0 || index > size())
10.608 + throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
10.609 + }
10.610 +
10.611 + private String outOfBoundsMsg(int index) {
10.612 + return "Index: "+index+", Size: "+size();
10.613 + }
10.614 +}
10.615 +
10.616 +class SubList<E> extends AbstractList<E> {
10.617 + private final AbstractList<E> l;
10.618 + private final int offset;
10.619 + private int size;
10.620 +
10.621 + SubList(AbstractList<E> list, int fromIndex, int toIndex) {
10.622 + if (fromIndex < 0)
10.623 + throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
10.624 + if (toIndex > list.size())
10.625 + throw new IndexOutOfBoundsException("toIndex = " + toIndex);
10.626 + if (fromIndex > toIndex)
10.627 + throw new IllegalArgumentException("fromIndex(" + fromIndex +
10.628 + ") > toIndex(" + toIndex + ")");
10.629 + l = list;
10.630 + offset = fromIndex;
10.631 + size = toIndex - fromIndex;
10.632 + this.modCount = l.modCount;
10.633 + }
10.634 +
10.635 + public E set(int index, E element) {
10.636 + rangeCheck(index);
10.637 + checkForComodification();
10.638 + return l.set(index+offset, element);
10.639 + }
10.640 +
10.641 + public E get(int index) {
10.642 + rangeCheck(index);
10.643 + checkForComodification();
10.644 + return l.get(index+offset);
10.645 + }
10.646 +
10.647 + public int size() {
10.648 + checkForComodification();
10.649 + return size;
10.650 + }
10.651 +
10.652 + public void add(int index, E element) {
10.653 + rangeCheckForAdd(index);
10.654 + checkForComodification();
10.655 + l.add(index+offset, element);
10.656 + this.modCount = l.modCount;
10.657 + size++;
10.658 + }
10.659 +
10.660 + public E remove(int index) {
10.661 + rangeCheck(index);
10.662 + checkForComodification();
10.663 + E result = l.remove(index+offset);
10.664 + this.modCount = l.modCount;
10.665 + size--;
10.666 + return result;
10.667 + }
10.668 +
10.669 + protected void removeRange(int fromIndex, int toIndex) {
10.670 + checkForComodification();
10.671 + l.removeRange(fromIndex+offset, toIndex+offset);
10.672 + this.modCount = l.modCount;
10.673 + size -= (toIndex-fromIndex);
10.674 + }
10.675 +
10.676 + public boolean addAll(Collection<? extends E> c) {
10.677 + return addAll(size, c);
10.678 + }
10.679 +
10.680 + public boolean addAll(int index, Collection<? extends E> c) {
10.681 + rangeCheckForAdd(index);
10.682 + int cSize = c.size();
10.683 + if (cSize==0)
10.684 + return false;
10.685 +
10.686 + checkForComodification();
10.687 + l.addAll(offset+index, c);
10.688 + this.modCount = l.modCount;
10.689 + size += cSize;
10.690 + return true;
10.691 + }
10.692 +
10.693 + public Iterator<E> iterator() {
10.694 + return listIterator();
10.695 + }
10.696 +
10.697 + public ListIterator<E> listIterator(final int index) {
10.698 + checkForComodification();
10.699 + rangeCheckForAdd(index);
10.700 +
10.701 + return new ListIterator<E>() {
10.702 + private final ListIterator<E> i = l.listIterator(index+offset);
10.703 +
10.704 + public boolean hasNext() {
10.705 + return nextIndex() < size;
10.706 + }
10.707 +
10.708 + public E next() {
10.709 + if (hasNext())
10.710 + return i.next();
10.711 + else
10.712 + throw new NoSuchElementException();
10.713 + }
10.714 +
10.715 + public boolean hasPrevious() {
10.716 + return previousIndex() >= 0;
10.717 + }
10.718 +
10.719 + public E previous() {
10.720 + if (hasPrevious())
10.721 + return i.previous();
10.722 + else
10.723 + throw new NoSuchElementException();
10.724 + }
10.725 +
10.726 + public int nextIndex() {
10.727 + return i.nextIndex() - offset;
10.728 + }
10.729 +
10.730 + public int previousIndex() {
10.731 + return i.previousIndex() - offset;
10.732 + }
10.733 +
10.734 + public void remove() {
10.735 + i.remove();
10.736 + SubList.this.modCount = l.modCount;
10.737 + size--;
10.738 + }
10.739 +
10.740 + public void set(E e) {
10.741 + i.set(e);
10.742 + }
10.743 +
10.744 + public void add(E e) {
10.745 + i.add(e);
10.746 + SubList.this.modCount = l.modCount;
10.747 + size++;
10.748 + }
10.749 + };
10.750 + }
10.751 +
10.752 + public List<E> subList(int fromIndex, int toIndex) {
10.753 + return new SubList<>(this, fromIndex, toIndex);
10.754 + }
10.755 +
10.756 + private void rangeCheck(int index) {
10.757 + if (index < 0 || index >= size)
10.758 + throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
10.759 + }
10.760 +
10.761 + private void rangeCheckForAdd(int index) {
10.762 + if (index < 0 || index > size)
10.763 + throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
10.764 + }
10.765 +
10.766 + private String outOfBoundsMsg(int index) {
10.767 + return "Index: "+index+", Size: "+size;
10.768 + }
10.769 +
10.770 + private void checkForComodification() {
10.771 + if (this.modCount != l.modCount)
10.772 + throw new ConcurrentModificationException();
10.773 + }
10.774 +}
10.775 +
10.776 +class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
10.777 + RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
10.778 + super(list, fromIndex, toIndex);
10.779 + }
10.780 +
10.781 + public List<E> subList(int fromIndex, int toIndex) {
10.782 + return new RandomAccessSubList<>(this, fromIndex, toIndex);
10.783 + }
10.784 +}
11.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
11.2 +++ b/emul/compact/src/main/java/java/util/AbstractMap.java Wed Jan 23 22:33:45 2013 +0100
11.3 @@ -0,0 +1,822 @@
11.4 +/*
11.5 + * Copyright (c) 1997, 2010, 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.util.Map.Entry;
11.31 +
11.32 +/**
11.33 + * This class provides a skeletal implementation of the <tt>Map</tt>
11.34 + * interface, to minimize the effort required to implement this interface.
11.35 + *
11.36 + * <p>To implement an unmodifiable map, the programmer needs only to extend this
11.37 + * class and provide an implementation for the <tt>entrySet</tt> method, which
11.38 + * returns a set-view of the map's mappings. Typically, the returned set
11.39 + * will, in turn, be implemented atop <tt>AbstractSet</tt>. This set should
11.40 + * not support the <tt>add</tt> or <tt>remove</tt> methods, and its iterator
11.41 + * should not support the <tt>remove</tt> method.
11.42 + *
11.43 + * <p>To implement a modifiable map, the programmer must additionally override
11.44 + * this class's <tt>put</tt> method (which otherwise throws an
11.45 + * <tt>UnsupportedOperationException</tt>), and the iterator returned by
11.46 + * <tt>entrySet().iterator()</tt> must additionally implement its
11.47 + * <tt>remove</tt> method.
11.48 + *
11.49 + * <p>The programmer should generally provide a void (no argument) and map
11.50 + * constructor, as per the recommendation in the <tt>Map</tt> interface
11.51 + * specification.
11.52 + *
11.53 + * <p>The documentation for each non-abstract method in this class describes its
11.54 + * implementation in detail. Each of these methods may be overridden if the
11.55 + * map being implemented admits a more efficient implementation.
11.56 + *
11.57 + * <p>This class is a member of the
11.58 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
11.59 + * Java Collections Framework</a>.
11.60 + *
11.61 + * @param <K> the type of keys maintained by this map
11.62 + * @param <V> the type of mapped values
11.63 + *
11.64 + * @author Josh Bloch
11.65 + * @author Neal Gafter
11.66 + * @see Map
11.67 + * @see Collection
11.68 + * @since 1.2
11.69 + */
11.70 +
11.71 +public abstract class AbstractMap<K,V> implements Map<K,V> {
11.72 + /**
11.73 + * Sole constructor. (For invocation by subclass constructors, typically
11.74 + * implicit.)
11.75 + */
11.76 + protected AbstractMap() {
11.77 + }
11.78 +
11.79 + // Query Operations
11.80 +
11.81 + /**
11.82 + * {@inheritDoc}
11.83 + *
11.84 + * <p>This implementation returns <tt>entrySet().size()</tt>.
11.85 + */
11.86 + public int size() {
11.87 + return entrySet().size();
11.88 + }
11.89 +
11.90 + /**
11.91 + * {@inheritDoc}
11.92 + *
11.93 + * <p>This implementation returns <tt>size() == 0</tt>.
11.94 + */
11.95 + public boolean isEmpty() {
11.96 + return size() == 0;
11.97 + }
11.98 +
11.99 + /**
11.100 + * {@inheritDoc}
11.101 + *
11.102 + * <p>This implementation iterates over <tt>entrySet()</tt> searching
11.103 + * for an entry with the specified value. If such an entry is found,
11.104 + * <tt>true</tt> is returned. If the iteration terminates without
11.105 + * finding such an entry, <tt>false</tt> is returned. Note that this
11.106 + * implementation requires linear time in the size of the map.
11.107 + *
11.108 + * @throws ClassCastException {@inheritDoc}
11.109 + * @throws NullPointerException {@inheritDoc}
11.110 + */
11.111 + public boolean containsValue(Object value) {
11.112 + Iterator<Entry<K,V>> i = entrySet().iterator();
11.113 + if (value==null) {
11.114 + while (i.hasNext()) {
11.115 + Entry<K,V> e = i.next();
11.116 + if (e.getValue()==null)
11.117 + return true;
11.118 + }
11.119 + } else {
11.120 + while (i.hasNext()) {
11.121 + Entry<K,V> e = i.next();
11.122 + if (value.equals(e.getValue()))
11.123 + return true;
11.124 + }
11.125 + }
11.126 + return false;
11.127 + }
11.128 +
11.129 + /**
11.130 + * {@inheritDoc}
11.131 + *
11.132 + * <p>This implementation iterates over <tt>entrySet()</tt> searching
11.133 + * for an entry with the specified key. If such an entry is found,
11.134 + * <tt>true</tt> is returned. If the iteration terminates without
11.135 + * finding such an entry, <tt>false</tt> is returned. Note that this
11.136 + * implementation requires linear time in the size of the map; many
11.137 + * implementations will override this method.
11.138 + *
11.139 + * @throws ClassCastException {@inheritDoc}
11.140 + * @throws NullPointerException {@inheritDoc}
11.141 + */
11.142 + public boolean containsKey(Object key) {
11.143 + Iterator<Map.Entry<K,V>> i = entrySet().iterator();
11.144 + if (key==null) {
11.145 + while (i.hasNext()) {
11.146 + Entry<K,V> e = i.next();
11.147 + if (e.getKey()==null)
11.148 + return true;
11.149 + }
11.150 + } else {
11.151 + while (i.hasNext()) {
11.152 + Entry<K,V> e = i.next();
11.153 + if (key.equals(e.getKey()))
11.154 + return true;
11.155 + }
11.156 + }
11.157 + return false;
11.158 + }
11.159 +
11.160 + /**
11.161 + * {@inheritDoc}
11.162 + *
11.163 + * <p>This implementation iterates over <tt>entrySet()</tt> searching
11.164 + * for an entry with the specified key. If such an entry is found,
11.165 + * the entry's value is returned. If the iteration terminates without
11.166 + * finding such an entry, <tt>null</tt> is returned. Note that this
11.167 + * implementation requires linear time in the size of the map; many
11.168 + * implementations will override this method.
11.169 + *
11.170 + * @throws ClassCastException {@inheritDoc}
11.171 + * @throws NullPointerException {@inheritDoc}
11.172 + */
11.173 + public V get(Object key) {
11.174 + Iterator<Entry<K,V>> i = entrySet().iterator();
11.175 + if (key==null) {
11.176 + while (i.hasNext()) {
11.177 + Entry<K,V> e = i.next();
11.178 + if (e.getKey()==null)
11.179 + return e.getValue();
11.180 + }
11.181 + } else {
11.182 + while (i.hasNext()) {
11.183 + Entry<K,V> e = i.next();
11.184 + if (key.equals(e.getKey()))
11.185 + return e.getValue();
11.186 + }
11.187 + }
11.188 + return null;
11.189 + }
11.190 +
11.191 +
11.192 + // Modification Operations
11.193 +
11.194 + /**
11.195 + * {@inheritDoc}
11.196 + *
11.197 + * <p>This implementation always throws an
11.198 + * <tt>UnsupportedOperationException</tt>.
11.199 + *
11.200 + * @throws UnsupportedOperationException {@inheritDoc}
11.201 + * @throws ClassCastException {@inheritDoc}
11.202 + * @throws NullPointerException {@inheritDoc}
11.203 + * @throws IllegalArgumentException {@inheritDoc}
11.204 + */
11.205 + public V put(K key, V value) {
11.206 + throw new UnsupportedOperationException();
11.207 + }
11.208 +
11.209 + /**
11.210 + * {@inheritDoc}
11.211 + *
11.212 + * <p>This implementation iterates over <tt>entrySet()</tt> searching for an
11.213 + * entry with the specified key. If such an entry is found, its value is
11.214 + * obtained with its <tt>getValue</tt> operation, the entry is removed
11.215 + * from the collection (and the backing map) with the iterator's
11.216 + * <tt>remove</tt> operation, and the saved value is returned. If the
11.217 + * iteration terminates without finding such an entry, <tt>null</tt> is
11.218 + * returned. Note that this implementation requires linear time in the
11.219 + * size of the map; many implementations will override this method.
11.220 + *
11.221 + * <p>Note that this implementation throws an
11.222 + * <tt>UnsupportedOperationException</tt> if the <tt>entrySet</tt>
11.223 + * iterator does not support the <tt>remove</tt> method and this map
11.224 + * contains a mapping for the specified key.
11.225 + *
11.226 + * @throws UnsupportedOperationException {@inheritDoc}
11.227 + * @throws ClassCastException {@inheritDoc}
11.228 + * @throws NullPointerException {@inheritDoc}
11.229 + */
11.230 + public V remove(Object key) {
11.231 + Iterator<Entry<K,V>> i = entrySet().iterator();
11.232 + Entry<K,V> correctEntry = null;
11.233 + if (key==null) {
11.234 + while (correctEntry==null && i.hasNext()) {
11.235 + Entry<K,V> e = i.next();
11.236 + if (e.getKey()==null)
11.237 + correctEntry = e;
11.238 + }
11.239 + } else {
11.240 + while (correctEntry==null && i.hasNext()) {
11.241 + Entry<K,V> e = i.next();
11.242 + if (key.equals(e.getKey()))
11.243 + correctEntry = e;
11.244 + }
11.245 + }
11.246 +
11.247 + V oldValue = null;
11.248 + if (correctEntry !=null) {
11.249 + oldValue = correctEntry.getValue();
11.250 + i.remove();
11.251 + }
11.252 + return oldValue;
11.253 + }
11.254 +
11.255 +
11.256 + // Bulk Operations
11.257 +
11.258 + /**
11.259 + * {@inheritDoc}
11.260 + *
11.261 + * <p>This implementation iterates over the specified map's
11.262 + * <tt>entrySet()</tt> collection, and calls this map's <tt>put</tt>
11.263 + * operation once for each entry returned by the iteration.
11.264 + *
11.265 + * <p>Note that this implementation throws an
11.266 + * <tt>UnsupportedOperationException</tt> if this map does not support
11.267 + * the <tt>put</tt> operation and the specified map is nonempty.
11.268 + *
11.269 + * @throws UnsupportedOperationException {@inheritDoc}
11.270 + * @throws ClassCastException {@inheritDoc}
11.271 + * @throws NullPointerException {@inheritDoc}
11.272 + * @throws IllegalArgumentException {@inheritDoc}
11.273 + */
11.274 + public void putAll(Map<? extends K, ? extends V> m) {
11.275 + for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
11.276 + put(e.getKey(), e.getValue());
11.277 + }
11.278 +
11.279 + /**
11.280 + * {@inheritDoc}
11.281 + *
11.282 + * <p>This implementation calls <tt>entrySet().clear()</tt>.
11.283 + *
11.284 + * <p>Note that this implementation throws an
11.285 + * <tt>UnsupportedOperationException</tt> if the <tt>entrySet</tt>
11.286 + * does not support the <tt>clear</tt> operation.
11.287 + *
11.288 + * @throws UnsupportedOperationException {@inheritDoc}
11.289 + */
11.290 + public void clear() {
11.291 + entrySet().clear();
11.292 + }
11.293 +
11.294 +
11.295 + // Views
11.296 +
11.297 + /**
11.298 + * Each of these fields are initialized to contain an instance of the
11.299 + * appropriate view the first time this view is requested. The views are
11.300 + * stateless, so there's no reason to create more than one of each.
11.301 + */
11.302 + transient volatile Set<K> keySet = null;
11.303 + transient volatile Collection<V> values = null;
11.304 +
11.305 + /**
11.306 + * {@inheritDoc}
11.307 + *
11.308 + * <p>This implementation returns a set that subclasses {@link AbstractSet}.
11.309 + * The subclass's iterator method returns a "wrapper object" over this
11.310 + * map's <tt>entrySet()</tt> iterator. The <tt>size</tt> method
11.311 + * delegates to this map's <tt>size</tt> method and the
11.312 + * <tt>contains</tt> method delegates to this map's
11.313 + * <tt>containsKey</tt> method.
11.314 + *
11.315 + * <p>The set is created the first time this method is called,
11.316 + * and returned in response to all subsequent calls. No synchronization
11.317 + * is performed, so there is a slight chance that multiple calls to this
11.318 + * method will not all return the same set.
11.319 + */
11.320 + public Set<K> keySet() {
11.321 + if (keySet == null) {
11.322 + keySet = new AbstractSet<K>() {
11.323 + public Iterator<K> iterator() {
11.324 + return new Iterator<K>() {
11.325 + private Iterator<Entry<K,V>> i = entrySet().iterator();
11.326 +
11.327 + public boolean hasNext() {
11.328 + return i.hasNext();
11.329 + }
11.330 +
11.331 + public K next() {
11.332 + return i.next().getKey();
11.333 + }
11.334 +
11.335 + public void remove() {
11.336 + i.remove();
11.337 + }
11.338 + };
11.339 + }
11.340 +
11.341 + public int size() {
11.342 + return AbstractMap.this.size();
11.343 + }
11.344 +
11.345 + public boolean isEmpty() {
11.346 + return AbstractMap.this.isEmpty();
11.347 + }
11.348 +
11.349 + public void clear() {
11.350 + AbstractMap.this.clear();
11.351 + }
11.352 +
11.353 + public boolean contains(Object k) {
11.354 + return AbstractMap.this.containsKey(k);
11.355 + }
11.356 + };
11.357 + }
11.358 + return keySet;
11.359 + }
11.360 +
11.361 + /**
11.362 + * {@inheritDoc}
11.363 + *
11.364 + * <p>This implementation returns a collection that subclasses {@link
11.365 + * AbstractCollection}. The subclass's iterator method returns a
11.366 + * "wrapper object" over this map's <tt>entrySet()</tt> iterator.
11.367 + * The <tt>size</tt> method delegates to this map's <tt>size</tt>
11.368 + * method and the <tt>contains</tt> method delegates to this map's
11.369 + * <tt>containsValue</tt> method.
11.370 + *
11.371 + * <p>The collection is created the first time this method is called, and
11.372 + * returned in response to all subsequent calls. No synchronization is
11.373 + * performed, so there is a slight chance that multiple calls to this
11.374 + * method will not all return the same collection.
11.375 + */
11.376 + public Collection<V> values() {
11.377 + if (values == null) {
11.378 + values = new AbstractCollection<V>() {
11.379 + public Iterator<V> iterator() {
11.380 + return new Iterator<V>() {
11.381 + private Iterator<Entry<K,V>> i = entrySet().iterator();
11.382 +
11.383 + public boolean hasNext() {
11.384 + return i.hasNext();
11.385 + }
11.386 +
11.387 + public V next() {
11.388 + return i.next().getValue();
11.389 + }
11.390 +
11.391 + public void remove() {
11.392 + i.remove();
11.393 + }
11.394 + };
11.395 + }
11.396 +
11.397 + public int size() {
11.398 + return AbstractMap.this.size();
11.399 + }
11.400 +
11.401 + public boolean isEmpty() {
11.402 + return AbstractMap.this.isEmpty();
11.403 + }
11.404 +
11.405 + public void clear() {
11.406 + AbstractMap.this.clear();
11.407 + }
11.408 +
11.409 + public boolean contains(Object v) {
11.410 + return AbstractMap.this.containsValue(v);
11.411 + }
11.412 + };
11.413 + }
11.414 + return values;
11.415 + }
11.416 +
11.417 + public abstract Set<Entry<K,V>> entrySet();
11.418 +
11.419 +
11.420 + // Comparison and hashing
11.421 +
11.422 + /**
11.423 + * Compares the specified object with this map for equality. Returns
11.424 + * <tt>true</tt> if the given object is also a map and the two maps
11.425 + * represent the same mappings. More formally, two maps <tt>m1</tt> and
11.426 + * <tt>m2</tt> represent the same mappings if
11.427 + * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
11.428 + * <tt>equals</tt> method works properly across different implementations
11.429 + * of the <tt>Map</tt> interface.
11.430 + *
11.431 + * <p>This implementation first checks if the specified object is this map;
11.432 + * if so it returns <tt>true</tt>. Then, it checks if the specified
11.433 + * object is a map whose size is identical to the size of this map; if
11.434 + * not, it returns <tt>false</tt>. If so, it iterates over this map's
11.435 + * <tt>entrySet</tt> collection, and checks that the specified map
11.436 + * contains each mapping that this map contains. If the specified map
11.437 + * fails to contain such a mapping, <tt>false</tt> is returned. If the
11.438 + * iteration completes, <tt>true</tt> is returned.
11.439 + *
11.440 + * @param o object to be compared for equality with this map
11.441 + * @return <tt>true</tt> if the specified object is equal to this map
11.442 + */
11.443 + public boolean equals(Object o) {
11.444 + if (o == this)
11.445 + return true;
11.446 +
11.447 + if (!(o instanceof Map))
11.448 + return false;
11.449 + Map<K,V> m = (Map<K,V>) o;
11.450 + if (m.size() != size())
11.451 + return false;
11.452 +
11.453 + try {
11.454 + Iterator<Entry<K,V>> i = entrySet().iterator();
11.455 + while (i.hasNext()) {
11.456 + Entry<K,V> e = i.next();
11.457 + K key = e.getKey();
11.458 + V value = e.getValue();
11.459 + if (value == null) {
11.460 + if (!(m.get(key)==null && m.containsKey(key)))
11.461 + return false;
11.462 + } else {
11.463 + if (!value.equals(m.get(key)))
11.464 + return false;
11.465 + }
11.466 + }
11.467 + } catch (ClassCastException unused) {
11.468 + return false;
11.469 + } catch (NullPointerException unused) {
11.470 + return false;
11.471 + }
11.472 +
11.473 + return true;
11.474 + }
11.475 +
11.476 + /**
11.477 + * Returns the hash code value for this map. The hash code of a map is
11.478 + * defined to be the sum of the hash codes of each entry in the map's
11.479 + * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
11.480 + * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
11.481 + * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
11.482 + * {@link Object#hashCode}.
11.483 + *
11.484 + * <p>This implementation iterates over <tt>entrySet()</tt>, calling
11.485 + * {@link Map.Entry#hashCode hashCode()} on each element (entry) in the
11.486 + * set, and adding up the results.
11.487 + *
11.488 + * @return the hash code value for this map
11.489 + * @see Map.Entry#hashCode()
11.490 + * @see Object#equals(Object)
11.491 + * @see Set#equals(Object)
11.492 + */
11.493 + public int hashCode() {
11.494 + int h = 0;
11.495 + Iterator<Entry<K,V>> i = entrySet().iterator();
11.496 + while (i.hasNext())
11.497 + h += i.next().hashCode();
11.498 + return h;
11.499 + }
11.500 +
11.501 + /**
11.502 + * Returns a string representation of this map. The string representation
11.503 + * consists of a list of key-value mappings in the order returned by the
11.504 + * map's <tt>entrySet</tt> view's iterator, enclosed in braces
11.505 + * (<tt>"{}"</tt>). Adjacent mappings are separated by the characters
11.506 + * <tt>", "</tt> (comma and space). Each key-value mapping is rendered as
11.507 + * the key followed by an equals sign (<tt>"="</tt>) followed by the
11.508 + * associated value. Keys and values are converted to strings as by
11.509 + * {@link String#valueOf(Object)}.
11.510 + *
11.511 + * @return a string representation of this map
11.512 + */
11.513 + public String toString() {
11.514 + Iterator<Entry<K,V>> i = entrySet().iterator();
11.515 + if (! i.hasNext())
11.516 + return "{}";
11.517 +
11.518 + StringBuilder sb = new StringBuilder();
11.519 + sb.append('{');
11.520 + for (;;) {
11.521 + Entry<K,V> e = i.next();
11.522 + K key = e.getKey();
11.523 + V value = e.getValue();
11.524 + sb.append(key == this ? "(this Map)" : key);
11.525 + sb.append('=');
11.526 + sb.append(value == this ? "(this Map)" : value);
11.527 + if (! i.hasNext())
11.528 + return sb.append('}').toString();
11.529 + sb.append(',').append(' ');
11.530 + }
11.531 + }
11.532 +
11.533 + /**
11.534 + * Returns a shallow copy of this <tt>AbstractMap</tt> instance: the keys
11.535 + * and values themselves are not cloned.
11.536 + *
11.537 + * @return a shallow copy of this map
11.538 + */
11.539 + protected Object clone() throws CloneNotSupportedException {
11.540 + AbstractMap<K,V> result = (AbstractMap<K,V>)super.clone();
11.541 + result.keySet = null;
11.542 + result.values = null;
11.543 + return result;
11.544 + }
11.545 +
11.546 + /**
11.547 + * Utility method for SimpleEntry and SimpleImmutableEntry.
11.548 + * Test for equality, checking for nulls.
11.549 + */
11.550 + private static boolean eq(Object o1, Object o2) {
11.551 + return o1 == null ? o2 == null : o1.equals(o2);
11.552 + }
11.553 +
11.554 + // Implementation Note: SimpleEntry and SimpleImmutableEntry
11.555 + // are distinct unrelated classes, even though they share
11.556 + // some code. Since you can't add or subtract final-ness
11.557 + // of a field in a subclass, they can't share representations,
11.558 + // and the amount of duplicated code is too small to warrant
11.559 + // exposing a common abstract class.
11.560 +
11.561 +
11.562 + /**
11.563 + * An Entry maintaining a key and a value. The value may be
11.564 + * changed using the <tt>setValue</tt> method. This class
11.565 + * facilitates the process of building custom map
11.566 + * implementations. For example, it may be convenient to return
11.567 + * arrays of <tt>SimpleEntry</tt> instances in method
11.568 + * <tt>Map.entrySet().toArray</tt>.
11.569 + *
11.570 + * @since 1.6
11.571 + */
11.572 + public static class SimpleEntry<K,V>
11.573 + implements Entry<K,V>, java.io.Serializable
11.574 + {
11.575 + private static final long serialVersionUID = -8499721149061103585L;
11.576 +
11.577 + private final K key;
11.578 + private V value;
11.579 +
11.580 + /**
11.581 + * Creates an entry representing a mapping from the specified
11.582 + * key to the specified value.
11.583 + *
11.584 + * @param key the key represented by this entry
11.585 + * @param value the value represented by this entry
11.586 + */
11.587 + public SimpleEntry(K key, V value) {
11.588 + this.key = key;
11.589 + this.value = value;
11.590 + }
11.591 +
11.592 + /**
11.593 + * Creates an entry representing the same mapping as the
11.594 + * specified entry.
11.595 + *
11.596 + * @param entry the entry to copy
11.597 + */
11.598 + public SimpleEntry(Entry<? extends K, ? extends V> entry) {
11.599 + this.key = entry.getKey();
11.600 + this.value = entry.getValue();
11.601 + }
11.602 +
11.603 + /**
11.604 + * Returns the key corresponding to this entry.
11.605 + *
11.606 + * @return the key corresponding to this entry
11.607 + */
11.608 + public K getKey() {
11.609 + return key;
11.610 + }
11.611 +
11.612 + /**
11.613 + * Returns the value corresponding to this entry.
11.614 + *
11.615 + * @return the value corresponding to this entry
11.616 + */
11.617 + public V getValue() {
11.618 + return value;
11.619 + }
11.620 +
11.621 + /**
11.622 + * Replaces the value corresponding to this entry with the specified
11.623 + * value.
11.624 + *
11.625 + * @param value new value to be stored in this entry
11.626 + * @return the old value corresponding to the entry
11.627 + */
11.628 + public V setValue(V value) {
11.629 + V oldValue = this.value;
11.630 + this.value = value;
11.631 + return oldValue;
11.632 + }
11.633 +
11.634 + /**
11.635 + * Compares the specified object with this entry for equality.
11.636 + * Returns {@code true} if the given object is also a map entry and
11.637 + * the two entries represent the same mapping. More formally, two
11.638 + * entries {@code e1} and {@code e2} represent the same mapping
11.639 + * if<pre>
11.640 + * (e1.getKey()==null ?
11.641 + * e2.getKey()==null :
11.642 + * e1.getKey().equals(e2.getKey()))
11.643 + * &&
11.644 + * (e1.getValue()==null ?
11.645 + * e2.getValue()==null :
11.646 + * e1.getValue().equals(e2.getValue()))</pre>
11.647 + * This ensures that the {@code equals} method works properly across
11.648 + * different implementations of the {@code Map.Entry} interface.
11.649 + *
11.650 + * @param o object to be compared for equality with this map entry
11.651 + * @return {@code true} if the specified object is equal to this map
11.652 + * entry
11.653 + * @see #hashCode
11.654 + */
11.655 + public boolean equals(Object o) {
11.656 + if (!(o instanceof Map.Entry))
11.657 + return false;
11.658 + Map.Entry e = (Map.Entry)o;
11.659 + return eq(key, e.getKey()) && eq(value, e.getValue());
11.660 + }
11.661 +
11.662 + /**
11.663 + * Returns the hash code value for this map entry. The hash code
11.664 + * of a map entry {@code e} is defined to be: <pre>
11.665 + * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^
11.666 + * (e.getValue()==null ? 0 : e.getValue().hashCode())</pre>
11.667 + * This ensures that {@code e1.equals(e2)} implies that
11.668 + * {@code e1.hashCode()==e2.hashCode()} for any two Entries
11.669 + * {@code e1} and {@code e2}, as required by the general
11.670 + * contract of {@link Object#hashCode}.
11.671 + *
11.672 + * @return the hash code value for this map entry
11.673 + * @see #equals
11.674 + */
11.675 + public int hashCode() {
11.676 + return (key == null ? 0 : key.hashCode()) ^
11.677 + (value == null ? 0 : value.hashCode());
11.678 + }
11.679 +
11.680 + /**
11.681 + * Returns a String representation of this map entry. This
11.682 + * implementation returns the string representation of this
11.683 + * entry's key followed by the equals character ("<tt>=</tt>")
11.684 + * followed by the string representation of this entry's value.
11.685 + *
11.686 + * @return a String representation of this map entry
11.687 + */
11.688 + public String toString() {
11.689 + return key + "=" + value;
11.690 + }
11.691 +
11.692 + }
11.693 +
11.694 + /**
11.695 + * An Entry maintaining an immutable key and value. This class
11.696 + * does not support method <tt>setValue</tt>. This class may be
11.697 + * convenient in methods that return thread-safe snapshots of
11.698 + * key-value mappings.
11.699 + *
11.700 + * @since 1.6
11.701 + */
11.702 + public static class SimpleImmutableEntry<K,V>
11.703 + implements Entry<K,V>, java.io.Serializable
11.704 + {
11.705 + private static final long serialVersionUID = 7138329143949025153L;
11.706 +
11.707 + private final K key;
11.708 + private final V value;
11.709 +
11.710 + /**
11.711 + * Creates an entry representing a mapping from the specified
11.712 + * key to the specified value.
11.713 + *
11.714 + * @param key the key represented by this entry
11.715 + * @param value the value represented by this entry
11.716 + */
11.717 + public SimpleImmutableEntry(K key, V value) {
11.718 + this.key = key;
11.719 + this.value = value;
11.720 + }
11.721 +
11.722 + /**
11.723 + * Creates an entry representing the same mapping as the
11.724 + * specified entry.
11.725 + *
11.726 + * @param entry the entry to copy
11.727 + */
11.728 + public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) {
11.729 + this.key = entry.getKey();
11.730 + this.value = entry.getValue();
11.731 + }
11.732 +
11.733 + /**
11.734 + * Returns the key corresponding to this entry.
11.735 + *
11.736 + * @return the key corresponding to this entry
11.737 + */
11.738 + public K getKey() {
11.739 + return key;
11.740 + }
11.741 +
11.742 + /**
11.743 + * Returns the value corresponding to this entry.
11.744 + *
11.745 + * @return the value corresponding to this entry
11.746 + */
11.747 + public V getValue() {
11.748 + return value;
11.749 + }
11.750 +
11.751 + /**
11.752 + * Replaces the value corresponding to this entry with the specified
11.753 + * value (optional operation). This implementation simply throws
11.754 + * <tt>UnsupportedOperationException</tt>, as this class implements
11.755 + * an <i>immutable</i> map entry.
11.756 + *
11.757 + * @param value new value to be stored in this entry
11.758 + * @return (Does not return)
11.759 + * @throws UnsupportedOperationException always
11.760 + */
11.761 + public V setValue(V value) {
11.762 + throw new UnsupportedOperationException();
11.763 + }
11.764 +
11.765 + /**
11.766 + * Compares the specified object with this entry for equality.
11.767 + * Returns {@code true} if the given object is also a map entry and
11.768 + * the two entries represent the same mapping. More formally, two
11.769 + * entries {@code e1} and {@code e2} represent the same mapping
11.770 + * if<pre>
11.771 + * (e1.getKey()==null ?
11.772 + * e2.getKey()==null :
11.773 + * e1.getKey().equals(e2.getKey()))
11.774 + * &&
11.775 + * (e1.getValue()==null ?
11.776 + * e2.getValue()==null :
11.777 + * e1.getValue().equals(e2.getValue()))</pre>
11.778 + * This ensures that the {@code equals} method works properly across
11.779 + * different implementations of the {@code Map.Entry} interface.
11.780 + *
11.781 + * @param o object to be compared for equality with this map entry
11.782 + * @return {@code true} if the specified object is equal to this map
11.783 + * entry
11.784 + * @see #hashCode
11.785 + */
11.786 + public boolean equals(Object o) {
11.787 + if (!(o instanceof Map.Entry))
11.788 + return false;
11.789 + Map.Entry e = (Map.Entry)o;
11.790 + return eq(key, e.getKey()) && eq(value, e.getValue());
11.791 + }
11.792 +
11.793 + /**
11.794 + * Returns the hash code value for this map entry. The hash code
11.795 + * of a map entry {@code e} is defined to be: <pre>
11.796 + * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^
11.797 + * (e.getValue()==null ? 0 : e.getValue().hashCode())</pre>
11.798 + * This ensures that {@code e1.equals(e2)} implies that
11.799 + * {@code e1.hashCode()==e2.hashCode()} for any two Entries
11.800 + * {@code e1} and {@code e2}, as required by the general
11.801 + * contract of {@link Object#hashCode}.
11.802 + *
11.803 + * @return the hash code value for this map entry
11.804 + * @see #equals
11.805 + */
11.806 + public int hashCode() {
11.807 + return (key == null ? 0 : key.hashCode()) ^
11.808 + (value == null ? 0 : value.hashCode());
11.809 + }
11.810 +
11.811 + /**
11.812 + * Returns a String representation of this map entry. This
11.813 + * implementation returns the string representation of this
11.814 + * entry's key followed by the equals character ("<tt>=</tt>")
11.815 + * followed by the string representation of this entry's value.
11.816 + *
11.817 + * @return a String representation of this map entry
11.818 + */
11.819 + public String toString() {
11.820 + return key + "=" + value;
11.821 + }
11.822 +
11.823 + }
11.824 +
11.825 +}
12.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
12.2 +++ b/emul/compact/src/main/java/java/util/AbstractSet.java Wed Jan 23 22:33:45 2013 +0100
12.3 @@ -0,0 +1,185 @@
12.4 +/*
12.5 + * Copyright (c) 1997, 2006, 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 + * This class provides a skeletal implementation of the <tt>Set</tt>
12.33 + * interface to minimize the effort required to implement this
12.34 + * interface. <p>
12.35 + *
12.36 + * The process of implementing a set by extending this class is identical
12.37 + * to that of implementing a Collection by extending AbstractCollection,
12.38 + * except that all of the methods and constructors in subclasses of this
12.39 + * class must obey the additional constraints imposed by the <tt>Set</tt>
12.40 + * interface (for instance, the add method must not permit addition of
12.41 + * multiple instances of an object to a set).<p>
12.42 + *
12.43 + * Note that this class does not override any of the implementations from
12.44 + * the <tt>AbstractCollection</tt> class. It merely adds implementations
12.45 + * for <tt>equals</tt> and <tt>hashCode</tt>.<p>
12.46 + *
12.47 + * This class is a member of the
12.48 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
12.49 + * Java Collections Framework</a>.
12.50 + *
12.51 + * @param <E> the type of elements maintained by this set
12.52 + *
12.53 + * @author Josh Bloch
12.54 + * @author Neal Gafter
12.55 + * @see Collection
12.56 + * @see AbstractCollection
12.57 + * @see Set
12.58 + * @since 1.2
12.59 + */
12.60 +
12.61 +public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
12.62 + /**
12.63 + * Sole constructor. (For invocation by subclass constructors, typically
12.64 + * implicit.)
12.65 + */
12.66 + protected AbstractSet() {
12.67 + }
12.68 +
12.69 + // Comparison and hashing
12.70 +
12.71 + /**
12.72 + * Compares the specified object with this set for equality. Returns
12.73 + * <tt>true</tt> if the given object is also a set, the two sets have
12.74 + * the same size, and every member of the given set is contained in
12.75 + * this set. This ensures that the <tt>equals</tt> method works
12.76 + * properly across different implementations of the <tt>Set</tt>
12.77 + * interface.<p>
12.78 + *
12.79 + * This implementation first checks if the specified object is this
12.80 + * set; if so it returns <tt>true</tt>. Then, it checks if the
12.81 + * specified object is a set whose size is identical to the size of
12.82 + * this set; if not, it returns false. If so, it returns
12.83 + * <tt>containsAll((Collection) o)</tt>.
12.84 + *
12.85 + * @param o object to be compared for equality with this set
12.86 + * @return <tt>true</tt> if the specified object is equal to this set
12.87 + */
12.88 + public boolean equals(Object o) {
12.89 + if (o == this)
12.90 + return true;
12.91 +
12.92 + if (!(o instanceof Set))
12.93 + return false;
12.94 + Collection c = (Collection) o;
12.95 + if (c.size() != size())
12.96 + return false;
12.97 + try {
12.98 + return containsAll(c);
12.99 + } catch (ClassCastException unused) {
12.100 + return false;
12.101 + } catch (NullPointerException unused) {
12.102 + return false;
12.103 + }
12.104 + }
12.105 +
12.106 + /**
12.107 + * Returns the hash code value for this set. The hash code of a set is
12.108 + * defined to be the sum of the hash codes of the elements in the set,
12.109 + * where the hash code of a <tt>null</tt> element is defined to be zero.
12.110 + * This ensures that <tt>s1.equals(s2)</tt> implies that
12.111 + * <tt>s1.hashCode()==s2.hashCode()</tt> for any two sets <tt>s1</tt>
12.112 + * and <tt>s2</tt>, as required by the general contract of
12.113 + * {@link Object#hashCode}.
12.114 + *
12.115 + * <p>This implementation iterates over the set, calling the
12.116 + * <tt>hashCode</tt> method on each element in the set, and adding up
12.117 + * the results.
12.118 + *
12.119 + * @return the hash code value for this set
12.120 + * @see Object#equals(Object)
12.121 + * @see Set#equals(Object)
12.122 + */
12.123 + public int hashCode() {
12.124 + int h = 0;
12.125 + Iterator<E> i = iterator();
12.126 + while (i.hasNext()) {
12.127 + E obj = i.next();
12.128 + if (obj != null)
12.129 + h += obj.hashCode();
12.130 + }
12.131 + return h;
12.132 + }
12.133 +
12.134 + /**
12.135 + * Removes from this set all of its elements that are contained in the
12.136 + * specified collection (optional operation). If the specified
12.137 + * collection is also a set, this operation effectively modifies this
12.138 + * set so that its value is the <i>asymmetric set difference</i> of
12.139 + * the two sets.
12.140 + *
12.141 + * <p>This implementation determines which is the smaller of this set
12.142 + * and the specified collection, by invoking the <tt>size</tt>
12.143 + * method on each. If this set has fewer elements, then the
12.144 + * implementation iterates over this set, checking each element
12.145 + * returned by the iterator in turn to see if it is contained in
12.146 + * the specified collection. If it is so contained, it is removed
12.147 + * from this set with the iterator's <tt>remove</tt> method. If
12.148 + * the specified collection has fewer elements, then the
12.149 + * implementation iterates over the specified collection, removing
12.150 + * from this set each element returned by the iterator, using this
12.151 + * set's <tt>remove</tt> method.
12.152 + *
12.153 + * <p>Note that this implementation will throw an
12.154 + * <tt>UnsupportedOperationException</tt> if the iterator returned by the
12.155 + * <tt>iterator</tt> method does not implement the <tt>remove</tt> method.
12.156 + *
12.157 + * @param c collection containing elements to be removed from this set
12.158 + * @return <tt>true</tt> if this set changed as a result of the call
12.159 + * @throws UnsupportedOperationException if the <tt>removeAll</tt> operation
12.160 + * is not supported by this set
12.161 + * @throws ClassCastException if the class of an element of this set
12.162 + * is incompatible with the specified collection
12.163 + * (<a href="Collection.html#optional-restrictions">optional</a>)
12.164 + * @throws NullPointerException if this set contains a null element and the
12.165 + * specified collection does not permit null elements
12.166 + * (<a href="Collection.html#optional-restrictions">optional</a>),
12.167 + * or if the specified collection is null
12.168 + * @see #remove(Object)
12.169 + * @see #contains(Object)
12.170 + */
12.171 + public boolean removeAll(Collection<?> c) {
12.172 + boolean modified = false;
12.173 +
12.174 + if (size() > c.size()) {
12.175 + for (Iterator<?> i = c.iterator(); i.hasNext(); )
12.176 + modified |= remove(i.next());
12.177 + } else {
12.178 + for (Iterator<?> i = iterator(); i.hasNext(); ) {
12.179 + if (c.contains(i.next())) {
12.180 + i.remove();
12.181 + modified = true;
12.182 + }
12.183 + }
12.184 + }
12.185 + return modified;
12.186 + }
12.187 +
12.188 +}
13.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
13.2 +++ b/emul/compact/src/main/java/java/util/ArrayList.java Wed Jan 23 22:33:45 2013 +0100
13.3 @@ -0,0 +1,1132 @@
13.4 +/*
13.5 + * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
13.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
13.7 + *
13.8 + * This code is free software; you can redistribute it and/or modify it
13.9 + * under the terms of the GNU General Public License version 2 only, as
13.10 + * published by the Free Software Foundation. Oracle designates this
13.11 + * particular file as subject to the "Classpath" exception as provided
13.12 + * by Oracle in the LICENSE file that accompanied this code.
13.13 + *
13.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
13.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13.17 + * version 2 for more details (a copy is included in the LICENSE file that
13.18 + * accompanied this code).
13.19 + *
13.20 + * You should have received a copy of the GNU General Public License version
13.21 + * 2 along with this work; if not, write to the Free Software Foundation,
13.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
13.23 + *
13.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
13.25 + * or visit www.oracle.com if you need additional information or have any
13.26 + * questions.
13.27 + */
13.28 +
13.29 +package java.util;
13.30 +
13.31 +/**
13.32 + * Resizable-array implementation of the <tt>List</tt> interface. Implements
13.33 + * all optional list operations, and permits all elements, including
13.34 + * <tt>null</tt>. In addition to implementing the <tt>List</tt> interface,
13.35 + * this class provides methods to manipulate the size of the array that is
13.36 + * used internally to store the list. (This class is roughly equivalent to
13.37 + * <tt>Vector</tt>, except that it is unsynchronized.)
13.38 + *
13.39 + * <p>The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,
13.40 + * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant
13.41 + * time. The <tt>add</tt> operation runs in <i>amortized constant time</i>,
13.42 + * that is, adding n elements requires O(n) time. All of the other operations
13.43 + * run in linear time (roughly speaking). The constant factor is low compared
13.44 + * to that for the <tt>LinkedList</tt> implementation.
13.45 + *
13.46 + * <p>Each <tt>ArrayList</tt> instance has a <i>capacity</i>. The capacity is
13.47 + * the size of the array used to store the elements in the list. It is always
13.48 + * at least as large as the list size. As elements are added to an ArrayList,
13.49 + * its capacity grows automatically. The details of the growth policy are not
13.50 + * specified beyond the fact that adding an element has constant amortized
13.51 + * time cost.
13.52 + *
13.53 + * <p>An application can increase the capacity of an <tt>ArrayList</tt> instance
13.54 + * before adding a large number of elements using the <tt>ensureCapacity</tt>
13.55 + * operation. This may reduce the amount of incremental reallocation.
13.56 + *
13.57 + * <p><strong>Note that this implementation is not synchronized.</strong>
13.58 + * If multiple threads access an <tt>ArrayList</tt> instance concurrently,
13.59 + * and at least one of the threads modifies the list structurally, it
13.60 + * <i>must</i> be synchronized externally. (A structural modification is
13.61 + * any operation that adds or deletes one or more elements, or explicitly
13.62 + * resizes the backing array; merely setting the value of an element is not
13.63 + * a structural modification.) This is typically accomplished by
13.64 + * synchronizing on some object that naturally encapsulates the list.
13.65 + *
13.66 + * If no such object exists, the list should be "wrapped" using the
13.67 + * {@link Collections#synchronizedList Collections.synchronizedList}
13.68 + * method. This is best done at creation time, to prevent accidental
13.69 + * unsynchronized access to the list:<pre>
13.70 + * List list = Collections.synchronizedList(new ArrayList(...));</pre>
13.71 + *
13.72 + * <p><a name="fail-fast"/>
13.73 + * The iterators returned by this class's {@link #iterator() iterator} and
13.74 + * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
13.75 + * if the list is structurally modified at any time after the iterator is
13.76 + * created, in any way except through the iterator's own
13.77 + * {@link ListIterator#remove() remove} or
13.78 + * {@link ListIterator#add(Object) add} methods, the iterator will throw a
13.79 + * {@link ConcurrentModificationException}. Thus, in the face of
13.80 + * concurrent modification, the iterator fails quickly and cleanly, rather
13.81 + * than risking arbitrary, non-deterministic behavior at an undetermined
13.82 + * time in the future.
13.83 + *
13.84 + * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
13.85 + * as it is, generally speaking, impossible to make any hard guarantees in the
13.86 + * presence of unsynchronized concurrent modification. Fail-fast iterators
13.87 + * throw {@code ConcurrentModificationException} on a best-effort basis.
13.88 + * Therefore, it would be wrong to write a program that depended on this
13.89 + * exception for its correctness: <i>the fail-fast behavior of iterators
13.90 + * should be used only to detect bugs.</i>
13.91 + *
13.92 + * <p>This class is a member of the
13.93 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
13.94 + * Java Collections Framework</a>.
13.95 + *
13.96 + * @author Josh Bloch
13.97 + * @author Neal Gafter
13.98 + * @see Collection
13.99 + * @see List
13.100 + * @see LinkedList
13.101 + * @see Vector
13.102 + * @since 1.2
13.103 + */
13.104 +
13.105 +public class ArrayList<E> extends AbstractList<E>
13.106 + implements List<E>, RandomAccess, Cloneable, java.io.Serializable
13.107 +{
13.108 + private static final long serialVersionUID = 8683452581122892189L;
13.109 +
13.110 + /**
13.111 + * The array buffer into which the elements of the ArrayList are stored.
13.112 + * The capacity of the ArrayList is the length of this array buffer.
13.113 + */
13.114 + private transient Object[] elementData;
13.115 +
13.116 + /**
13.117 + * The size of the ArrayList (the number of elements it contains).
13.118 + *
13.119 + * @serial
13.120 + */
13.121 + private int size;
13.122 +
13.123 + /**
13.124 + * Constructs an empty list with the specified initial capacity.
13.125 + *
13.126 + * @param initialCapacity the initial capacity of the list
13.127 + * @throws IllegalArgumentException if the specified initial capacity
13.128 + * is negative
13.129 + */
13.130 + public ArrayList(int initialCapacity) {
13.131 + super();
13.132 + if (initialCapacity < 0)
13.133 + throw new IllegalArgumentException("Illegal Capacity: "+
13.134 + initialCapacity);
13.135 + this.elementData = new Object[initialCapacity];
13.136 + }
13.137 +
13.138 + /**
13.139 + * Constructs an empty list with an initial capacity of ten.
13.140 + */
13.141 + public ArrayList() {
13.142 + this(10);
13.143 + }
13.144 +
13.145 + /**
13.146 + * Constructs a list containing the elements of the specified
13.147 + * collection, in the order they are returned by the collection's
13.148 + * iterator.
13.149 + *
13.150 + * @param c the collection whose elements are to be placed into this list
13.151 + * @throws NullPointerException if the specified collection is null
13.152 + */
13.153 + public ArrayList(Collection<? extends E> c) {
13.154 + elementData = c.toArray();
13.155 + size = elementData.length;
13.156 + // c.toArray might (incorrectly) not return Object[] (see 6260652)
13.157 + if (elementData.getClass() != Object[].class)
13.158 + elementData = Arrays.copyOf(elementData, size, Object[].class);
13.159 + }
13.160 +
13.161 + /**
13.162 + * Trims the capacity of this <tt>ArrayList</tt> instance to be the
13.163 + * list's current size. An application can use this operation to minimize
13.164 + * the storage of an <tt>ArrayList</tt> instance.
13.165 + */
13.166 + public void trimToSize() {
13.167 + modCount++;
13.168 + int oldCapacity = elementData.length;
13.169 + if (size < oldCapacity) {
13.170 + elementData = Arrays.copyOf(elementData, size);
13.171 + }
13.172 + }
13.173 +
13.174 + /**
13.175 + * Increases the capacity of this <tt>ArrayList</tt> instance, if
13.176 + * necessary, to ensure that it can hold at least the number of elements
13.177 + * specified by the minimum capacity argument.
13.178 + *
13.179 + * @param minCapacity the desired minimum capacity
13.180 + */
13.181 + public void ensureCapacity(int minCapacity) {
13.182 + if (minCapacity > 0)
13.183 + ensureCapacityInternal(minCapacity);
13.184 + }
13.185 +
13.186 + private void ensureCapacityInternal(int minCapacity) {
13.187 + modCount++;
13.188 + // overflow-conscious code
13.189 + if (minCapacity - elementData.length > 0)
13.190 + grow(minCapacity);
13.191 + }
13.192 +
13.193 + /**
13.194 + * The maximum size of array to allocate.
13.195 + * Some VMs reserve some header words in an array.
13.196 + * Attempts to allocate larger arrays may result in
13.197 + * OutOfMemoryError: Requested array size exceeds VM limit
13.198 + */
13.199 + private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
13.200 +
13.201 + /**
13.202 + * Increases the capacity to ensure that it can hold at least the
13.203 + * number of elements specified by the minimum capacity argument.
13.204 + *
13.205 + * @param minCapacity the desired minimum capacity
13.206 + */
13.207 + private void grow(int minCapacity) {
13.208 + // overflow-conscious code
13.209 + int oldCapacity = elementData.length;
13.210 + int newCapacity = oldCapacity + (oldCapacity >> 1);
13.211 + if (newCapacity - minCapacity < 0)
13.212 + newCapacity = minCapacity;
13.213 + if (newCapacity - MAX_ARRAY_SIZE > 0)
13.214 + newCapacity = hugeCapacity(minCapacity);
13.215 + // minCapacity is usually close to size, so this is a win:
13.216 + elementData = Arrays.copyOf(elementData, newCapacity);
13.217 + }
13.218 +
13.219 + private static int hugeCapacity(int minCapacity) {
13.220 + if (minCapacity < 0) // overflow
13.221 + throw new OutOfMemoryError();
13.222 + return (minCapacity > MAX_ARRAY_SIZE) ?
13.223 + Integer.MAX_VALUE :
13.224 + MAX_ARRAY_SIZE;
13.225 + }
13.226 +
13.227 + /**
13.228 + * Returns the number of elements in this list.
13.229 + *
13.230 + * @return the number of elements in this list
13.231 + */
13.232 + public int size() {
13.233 + return size;
13.234 + }
13.235 +
13.236 + /**
13.237 + * Returns <tt>true</tt> if this list contains no elements.
13.238 + *
13.239 + * @return <tt>true</tt> if this list contains no elements
13.240 + */
13.241 + public boolean isEmpty() {
13.242 + return size == 0;
13.243 + }
13.244 +
13.245 + /**
13.246 + * Returns <tt>true</tt> if this list contains the specified element.
13.247 + * More formally, returns <tt>true</tt> if and only if this list contains
13.248 + * at least one element <tt>e</tt> such that
13.249 + * <tt>(o==null ? e==null : o.equals(e))</tt>.
13.250 + *
13.251 + * @param o element whose presence in this list is to be tested
13.252 + * @return <tt>true</tt> if this list contains the specified element
13.253 + */
13.254 + public boolean contains(Object o) {
13.255 + return indexOf(o) >= 0;
13.256 + }
13.257 +
13.258 + /**
13.259 + * Returns the index of the first occurrence of the specified element
13.260 + * in this list, or -1 if this list does not contain the element.
13.261 + * More formally, returns the lowest index <tt>i</tt> such that
13.262 + * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
13.263 + * or -1 if there is no such index.
13.264 + */
13.265 + public int indexOf(Object o) {
13.266 + if (o == null) {
13.267 + for (int i = 0; i < size; i++)
13.268 + if (elementData[i]==null)
13.269 + return i;
13.270 + } else {
13.271 + for (int i = 0; i < size; i++)
13.272 + if (o.equals(elementData[i]))
13.273 + return i;
13.274 + }
13.275 + return -1;
13.276 + }
13.277 +
13.278 + /**
13.279 + * Returns the index of the last occurrence of the specified element
13.280 + * in this list, or -1 if this list does not contain the element.
13.281 + * More formally, returns the highest index <tt>i</tt> such that
13.282 + * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
13.283 + * or -1 if there is no such index.
13.284 + */
13.285 + public int lastIndexOf(Object o) {
13.286 + if (o == null) {
13.287 + for (int i = size-1; i >= 0; i--)
13.288 + if (elementData[i]==null)
13.289 + return i;
13.290 + } else {
13.291 + for (int i = size-1; i >= 0; i--)
13.292 + if (o.equals(elementData[i]))
13.293 + return i;
13.294 + }
13.295 + return -1;
13.296 + }
13.297 +
13.298 + /**
13.299 + * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
13.300 + * elements themselves are not copied.)
13.301 + *
13.302 + * @return a clone of this <tt>ArrayList</tt> instance
13.303 + */
13.304 + public Object clone() {
13.305 + try {
13.306 + @SuppressWarnings("unchecked")
13.307 + ArrayList<E> v = (ArrayList<E>) super.clone();
13.308 + v.elementData = Arrays.copyOf(elementData, size);
13.309 + v.modCount = 0;
13.310 + return v;
13.311 + } catch (CloneNotSupportedException e) {
13.312 + // this shouldn't happen, since we are Cloneable
13.313 + throw new InternalError();
13.314 + }
13.315 + }
13.316 +
13.317 + /**
13.318 + * Returns an array containing all of the elements in this list
13.319 + * in proper sequence (from first to last element).
13.320 + *
13.321 + * <p>The returned array will be "safe" in that no references to it are
13.322 + * maintained by this list. (In other words, this method must allocate
13.323 + * a new array). The caller is thus free to modify the returned array.
13.324 + *
13.325 + * <p>This method acts as bridge between array-based and collection-based
13.326 + * APIs.
13.327 + *
13.328 + * @return an array containing all of the elements in this list in
13.329 + * proper sequence
13.330 + */
13.331 + public Object[] toArray() {
13.332 + return Arrays.copyOf(elementData, size);
13.333 + }
13.334 +
13.335 + /**
13.336 + * Returns an array containing all of the elements in this list in proper
13.337 + * sequence (from first to last element); the runtime type of the returned
13.338 + * array is that of the specified array. If the list fits in the
13.339 + * specified array, it is returned therein. Otherwise, a new array is
13.340 + * allocated with the runtime type of the specified array and the size of
13.341 + * this list.
13.342 + *
13.343 + * <p>If the list fits in the specified array with room to spare
13.344 + * (i.e., the array has more elements than the list), the element in
13.345 + * the array immediately following the end of the collection is set to
13.346 + * <tt>null</tt>. (This is useful in determining the length of the
13.347 + * list <i>only</i> if the caller knows that the list does not contain
13.348 + * any null elements.)
13.349 + *
13.350 + * @param a the array into which the elements of the list are to
13.351 + * be stored, if it is big enough; otherwise, a new array of the
13.352 + * same runtime type is allocated for this purpose.
13.353 + * @return an array containing the elements of the list
13.354 + * @throws ArrayStoreException if the runtime type of the specified array
13.355 + * is not a supertype of the runtime type of every element in
13.356 + * this list
13.357 + * @throws NullPointerException if the specified array is null
13.358 + */
13.359 + @SuppressWarnings("unchecked")
13.360 + public <T> T[] toArray(T[] a) {
13.361 + if (a.length < size)
13.362 + // Make a new array of a's runtime type, but my contents:
13.363 + return (T[]) Arrays.copyOf(elementData, size, a.getClass());
13.364 + System.arraycopy(elementData, 0, a, 0, size);
13.365 + if (a.length > size)
13.366 + a[size] = null;
13.367 + return a;
13.368 + }
13.369 +
13.370 + // Positional Access Operations
13.371 +
13.372 + @SuppressWarnings("unchecked")
13.373 + E elementData(int index) {
13.374 + return (E) elementData[index];
13.375 + }
13.376 +
13.377 + /**
13.378 + * Returns the element at the specified position in this list.
13.379 + *
13.380 + * @param index index of the element to return
13.381 + * @return the element at the specified position in this list
13.382 + * @throws IndexOutOfBoundsException {@inheritDoc}
13.383 + */
13.384 + public E get(int index) {
13.385 + rangeCheck(index);
13.386 +
13.387 + return elementData(index);
13.388 + }
13.389 +
13.390 + /**
13.391 + * Replaces the element at the specified position in this list with
13.392 + * the specified element.
13.393 + *
13.394 + * @param index index of the element to replace
13.395 + * @param element element to be stored at the specified position
13.396 + * @return the element previously at the specified position
13.397 + * @throws IndexOutOfBoundsException {@inheritDoc}
13.398 + */
13.399 + public E set(int index, E element) {
13.400 + rangeCheck(index);
13.401 +
13.402 + E oldValue = elementData(index);
13.403 + elementData[index] = element;
13.404 + return oldValue;
13.405 + }
13.406 +
13.407 + /**
13.408 + * Appends the specified element to the end of this list.
13.409 + *
13.410 + * @param e element to be appended to this list
13.411 + * @return <tt>true</tt> (as specified by {@link Collection#add})
13.412 + */
13.413 + public boolean add(E e) {
13.414 + ensureCapacityInternal(size + 1); // Increments modCount!!
13.415 + elementData[size++] = e;
13.416 + return true;
13.417 + }
13.418 +
13.419 + /**
13.420 + * Inserts the specified element at the specified position in this
13.421 + * list. Shifts the element currently at that position (if any) and
13.422 + * any subsequent elements to the right (adds one to their indices).
13.423 + *
13.424 + * @param index index at which the specified element is to be inserted
13.425 + * @param element element to be inserted
13.426 + * @throws IndexOutOfBoundsException {@inheritDoc}
13.427 + */
13.428 + public void add(int index, E element) {
13.429 + rangeCheckForAdd(index);
13.430 +
13.431 + ensureCapacityInternal(size + 1); // Increments modCount!!
13.432 + System.arraycopy(elementData, index, elementData, index + 1,
13.433 + size - index);
13.434 + elementData[index] = element;
13.435 + size++;
13.436 + }
13.437 +
13.438 + /**
13.439 + * Removes the element at the specified position in this list.
13.440 + * Shifts any subsequent elements to the left (subtracts one from their
13.441 + * indices).
13.442 + *
13.443 + * @param index the index of the element to be removed
13.444 + * @return the element that was removed from the list
13.445 + * @throws IndexOutOfBoundsException {@inheritDoc}
13.446 + */
13.447 + public E remove(int index) {
13.448 + rangeCheck(index);
13.449 +
13.450 + modCount++;
13.451 + E oldValue = elementData(index);
13.452 +
13.453 + int numMoved = size - index - 1;
13.454 + if (numMoved > 0)
13.455 + System.arraycopy(elementData, index+1, elementData, index,
13.456 + numMoved);
13.457 + elementData[--size] = null; // Let gc do its work
13.458 +
13.459 + return oldValue;
13.460 + }
13.461 +
13.462 + /**
13.463 + * Removes the first occurrence of the specified element from this list,
13.464 + * if it is present. If the list does not contain the element, it is
13.465 + * unchanged. More formally, removes the element with the lowest index
13.466 + * <tt>i</tt> such that
13.467 + * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
13.468 + * (if such an element exists). Returns <tt>true</tt> if this list
13.469 + * contained the specified element (or equivalently, if this list
13.470 + * changed as a result of the call).
13.471 + *
13.472 + * @param o element to be removed from this list, if present
13.473 + * @return <tt>true</tt> if this list contained the specified element
13.474 + */
13.475 + public boolean remove(Object o) {
13.476 + if (o == null) {
13.477 + for (int index = 0; index < size; index++)
13.478 + if (elementData[index] == null) {
13.479 + fastRemove(index);
13.480 + return true;
13.481 + }
13.482 + } else {
13.483 + for (int index = 0; index < size; index++)
13.484 + if (o.equals(elementData[index])) {
13.485 + fastRemove(index);
13.486 + return true;
13.487 + }
13.488 + }
13.489 + return false;
13.490 + }
13.491 +
13.492 + /*
13.493 + * Private remove method that skips bounds checking and does not
13.494 + * return the value removed.
13.495 + */
13.496 + private void fastRemove(int index) {
13.497 + modCount++;
13.498 + int numMoved = size - index - 1;
13.499 + if (numMoved > 0)
13.500 + System.arraycopy(elementData, index+1, elementData, index,
13.501 + numMoved);
13.502 + elementData[--size] = null; // Let gc do its work
13.503 + }
13.504 +
13.505 + /**
13.506 + * Removes all of the elements from this list. The list will
13.507 + * be empty after this call returns.
13.508 + */
13.509 + public void clear() {
13.510 + modCount++;
13.511 +
13.512 + // Let gc do its work
13.513 + for (int i = 0; i < size; i++)
13.514 + elementData[i] = null;
13.515 +
13.516 + size = 0;
13.517 + }
13.518 +
13.519 + /**
13.520 + * Appends all of the elements in the specified collection to the end of
13.521 + * this list, in the order that they are returned by the
13.522 + * specified collection's Iterator. The behavior of this operation is
13.523 + * undefined if the specified collection is modified while the operation
13.524 + * is in progress. (This implies that the behavior of this call is
13.525 + * undefined if the specified collection is this list, and this
13.526 + * list is nonempty.)
13.527 + *
13.528 + * @param c collection containing elements to be added to this list
13.529 + * @return <tt>true</tt> if this list changed as a result of the call
13.530 + * @throws NullPointerException if the specified collection is null
13.531 + */
13.532 + public boolean addAll(Collection<? extends E> c) {
13.533 + Object[] a = c.toArray();
13.534 + int numNew = a.length;
13.535 + ensureCapacityInternal(size + numNew); // Increments modCount
13.536 + System.arraycopy(a, 0, elementData, size, numNew);
13.537 + size += numNew;
13.538 + return numNew != 0;
13.539 + }
13.540 +
13.541 + /**
13.542 + * Inserts all of the elements in the specified collection into this
13.543 + * list, starting at the specified position. Shifts the element
13.544 + * currently at that position (if any) and any subsequent elements to
13.545 + * the right (increases their indices). The new elements will appear
13.546 + * in the list in the order that they are returned by the
13.547 + * specified collection's iterator.
13.548 + *
13.549 + * @param index index at which to insert the first element from the
13.550 + * specified collection
13.551 + * @param c collection containing elements to be added to this list
13.552 + * @return <tt>true</tt> if this list changed as a result of the call
13.553 + * @throws IndexOutOfBoundsException {@inheritDoc}
13.554 + * @throws NullPointerException if the specified collection is null
13.555 + */
13.556 + public boolean addAll(int index, Collection<? extends E> c) {
13.557 + rangeCheckForAdd(index);
13.558 +
13.559 + Object[] a = c.toArray();
13.560 + int numNew = a.length;
13.561 + ensureCapacityInternal(size + numNew); // Increments modCount
13.562 +
13.563 + int numMoved = size - index;
13.564 + if (numMoved > 0)
13.565 + System.arraycopy(elementData, index, elementData, index + numNew,
13.566 + numMoved);
13.567 +
13.568 + System.arraycopy(a, 0, elementData, index, numNew);
13.569 + size += numNew;
13.570 + return numNew != 0;
13.571 + }
13.572 +
13.573 + /**
13.574 + * Removes from this list all of the elements whose index is between
13.575 + * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
13.576 + * Shifts any succeeding elements to the left (reduces their index).
13.577 + * This call shortens the list by {@code (toIndex - fromIndex)} elements.
13.578 + * (If {@code toIndex==fromIndex}, this operation has no effect.)
13.579 + *
13.580 + * @throws IndexOutOfBoundsException if {@code fromIndex} or
13.581 + * {@code toIndex} is out of range
13.582 + * ({@code fromIndex < 0 ||
13.583 + * fromIndex >= size() ||
13.584 + * toIndex > size() ||
13.585 + * toIndex < fromIndex})
13.586 + */
13.587 + protected void removeRange(int fromIndex, int toIndex) {
13.588 + modCount++;
13.589 + int numMoved = size - toIndex;
13.590 + System.arraycopy(elementData, toIndex, elementData, fromIndex,
13.591 + numMoved);
13.592 +
13.593 + // Let gc do its work
13.594 + int newSize = size - (toIndex-fromIndex);
13.595 + while (size != newSize)
13.596 + elementData[--size] = null;
13.597 + }
13.598 +
13.599 + /**
13.600 + * Checks if the given index is in range. If not, throws an appropriate
13.601 + * runtime exception. This method does *not* check if the index is
13.602 + * negative: It is always used immediately prior to an array access,
13.603 + * which throws an ArrayIndexOutOfBoundsException if index is negative.
13.604 + */
13.605 + private void rangeCheck(int index) {
13.606 + if (index >= size)
13.607 + throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
13.608 + }
13.609 +
13.610 + /**
13.611 + * A version of rangeCheck used by add and addAll.
13.612 + */
13.613 + private void rangeCheckForAdd(int index) {
13.614 + if (index > size || index < 0)
13.615 + throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
13.616 + }
13.617 +
13.618 + /**
13.619 + * Constructs an IndexOutOfBoundsException detail message.
13.620 + * Of the many possible refactorings of the error handling code,
13.621 + * this "outlining" performs best with both server and client VMs.
13.622 + */
13.623 + private String outOfBoundsMsg(int index) {
13.624 + return "Index: "+index+", Size: "+size;
13.625 + }
13.626 +
13.627 + /**
13.628 + * Removes from this list all of its elements that are contained in the
13.629 + * specified collection.
13.630 + *
13.631 + * @param c collection containing elements to be removed from this list
13.632 + * @return {@code true} if this list changed as a result of the call
13.633 + * @throws ClassCastException if the class of an element of this list
13.634 + * is incompatible with the specified collection
13.635 + * (<a href="Collection.html#optional-restrictions">optional</a>)
13.636 + * @throws NullPointerException if this list contains a null element and the
13.637 + * specified collection does not permit null elements
13.638 + * (<a href="Collection.html#optional-restrictions">optional</a>),
13.639 + * or if the specified collection is null
13.640 + * @see Collection#contains(Object)
13.641 + */
13.642 + public boolean removeAll(Collection<?> c) {
13.643 + return batchRemove(c, false);
13.644 + }
13.645 +
13.646 + /**
13.647 + * Retains only the elements in this list that are contained in the
13.648 + * specified collection. In other words, removes from this list all
13.649 + * of its elements that are not contained in the specified collection.
13.650 + *
13.651 + * @param c collection containing elements to be retained in this list
13.652 + * @return {@code true} if this list changed as a result of the call
13.653 + * @throws ClassCastException if the class of an element of this list
13.654 + * is incompatible with the specified collection
13.655 + * (<a href="Collection.html#optional-restrictions">optional</a>)
13.656 + * @throws NullPointerException if this list contains a null element and the
13.657 + * specified collection does not permit null elements
13.658 + * (<a href="Collection.html#optional-restrictions">optional</a>),
13.659 + * or if the specified collection is null
13.660 + * @see Collection#contains(Object)
13.661 + */
13.662 + public boolean retainAll(Collection<?> c) {
13.663 + return batchRemove(c, true);
13.664 + }
13.665 +
13.666 + private boolean batchRemove(Collection<?> c, boolean complement) {
13.667 + final Object[] elementData = this.elementData;
13.668 + int r = 0, w = 0;
13.669 + boolean modified = false;
13.670 + try {
13.671 + for (; r < size; r++)
13.672 + if (c.contains(elementData[r]) == complement)
13.673 + elementData[w++] = elementData[r];
13.674 + } finally {
13.675 + // Preserve behavioral compatibility with AbstractCollection,
13.676 + // even if c.contains() throws.
13.677 + if (r != size) {
13.678 + System.arraycopy(elementData, r,
13.679 + elementData, w,
13.680 + size - r);
13.681 + w += size - r;
13.682 + }
13.683 + if (w != size) {
13.684 + for (int i = w; i < size; i++)
13.685 + elementData[i] = null;
13.686 + modCount += size - w;
13.687 + size = w;
13.688 + modified = true;
13.689 + }
13.690 + }
13.691 + return modified;
13.692 + }
13.693 +
13.694 + /**
13.695 + * Save the state of the <tt>ArrayList</tt> instance to a stream (that
13.696 + * is, serialize it).
13.697 + *
13.698 + * @serialData The length of the array backing the <tt>ArrayList</tt>
13.699 + * instance is emitted (int), followed by all of its elements
13.700 + * (each an <tt>Object</tt>) in the proper order.
13.701 + */
13.702 + private void writeObject(java.io.ObjectOutputStream s)
13.703 + throws java.io.IOException{
13.704 + // Write out element count, and any hidden stuff
13.705 + int expectedModCount = modCount;
13.706 + s.defaultWriteObject();
13.707 +
13.708 + // Write out array length
13.709 + s.writeInt(elementData.length);
13.710 +
13.711 + // Write out all elements in the proper order.
13.712 + for (int i=0; i<size; i++)
13.713 + s.writeObject(elementData[i]);
13.714 +
13.715 + if (modCount != expectedModCount) {
13.716 + throw new ConcurrentModificationException();
13.717 + }
13.718 +
13.719 + }
13.720 +
13.721 + /**
13.722 + * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
13.723 + * deserialize it).
13.724 + */
13.725 + private void readObject(java.io.ObjectInputStream s)
13.726 + throws java.io.IOException, ClassNotFoundException {
13.727 + // Read in size, and any hidden stuff
13.728 + s.defaultReadObject();
13.729 +
13.730 + // Read in array length and allocate array
13.731 + int arrayLength = s.readInt();
13.732 + Object[] a = elementData = new Object[arrayLength];
13.733 +
13.734 + // Read in all elements in the proper order.
13.735 + for (int i=0; i<size; i++)
13.736 + a[i] = s.readObject();
13.737 + }
13.738 +
13.739 + /**
13.740 + * Returns a list iterator over the elements in this list (in proper
13.741 + * sequence), starting at the specified position in the list.
13.742 + * The specified index indicates the first element that would be
13.743 + * returned by an initial call to {@link ListIterator#next next}.
13.744 + * An initial call to {@link ListIterator#previous previous} would
13.745 + * return the element with the specified index minus one.
13.746 + *
13.747 + * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
13.748 + *
13.749 + * @throws IndexOutOfBoundsException {@inheritDoc}
13.750 + */
13.751 + public ListIterator<E> listIterator(int index) {
13.752 + if (index < 0 || index > size)
13.753 + throw new IndexOutOfBoundsException("Index: "+index);
13.754 + return new ListItr(index);
13.755 + }
13.756 +
13.757 + /**
13.758 + * Returns a list iterator over the elements in this list (in proper
13.759 + * sequence).
13.760 + *
13.761 + * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
13.762 + *
13.763 + * @see #listIterator(int)
13.764 + */
13.765 + public ListIterator<E> listIterator() {
13.766 + return new ListItr(0);
13.767 + }
13.768 +
13.769 + /**
13.770 + * Returns an iterator over the elements in this list in proper sequence.
13.771 + *
13.772 + * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
13.773 + *
13.774 + * @return an iterator over the elements in this list in proper sequence
13.775 + */
13.776 + public Iterator<E> iterator() {
13.777 + return new Itr();
13.778 + }
13.779 +
13.780 + /**
13.781 + * An optimized version of AbstractList.Itr
13.782 + */
13.783 + private class Itr implements Iterator<E> {
13.784 + int cursor; // index of next element to return
13.785 + int lastRet = -1; // index of last element returned; -1 if no such
13.786 + int expectedModCount = modCount;
13.787 +
13.788 + public boolean hasNext() {
13.789 + return cursor != size;
13.790 + }
13.791 +
13.792 + @SuppressWarnings("unchecked")
13.793 + public E next() {
13.794 + checkForComodification();
13.795 + int i = cursor;
13.796 + if (i >= size)
13.797 + throw new NoSuchElementException();
13.798 + Object[] elementData = ArrayList.this.elementData;
13.799 + if (i >= elementData.length)
13.800 + throw new ConcurrentModificationException();
13.801 + cursor = i + 1;
13.802 + return (E) elementData[lastRet = i];
13.803 + }
13.804 +
13.805 + public void remove() {
13.806 + if (lastRet < 0)
13.807 + throw new IllegalStateException();
13.808 + checkForComodification();
13.809 +
13.810 + try {
13.811 + ArrayList.this.remove(lastRet);
13.812 + cursor = lastRet;
13.813 + lastRet = -1;
13.814 + expectedModCount = modCount;
13.815 + } catch (IndexOutOfBoundsException ex) {
13.816 + throw new ConcurrentModificationException();
13.817 + }
13.818 + }
13.819 +
13.820 + final void checkForComodification() {
13.821 + if (modCount != expectedModCount)
13.822 + throw new ConcurrentModificationException();
13.823 + }
13.824 + }
13.825 +
13.826 + /**
13.827 + * An optimized version of AbstractList.ListItr
13.828 + */
13.829 + private class ListItr extends Itr implements ListIterator<E> {
13.830 + ListItr(int index) {
13.831 + super();
13.832 + cursor = index;
13.833 + }
13.834 +
13.835 + public boolean hasPrevious() {
13.836 + return cursor != 0;
13.837 + }
13.838 +
13.839 + public int nextIndex() {
13.840 + return cursor;
13.841 + }
13.842 +
13.843 + public int previousIndex() {
13.844 + return cursor - 1;
13.845 + }
13.846 +
13.847 + @SuppressWarnings("unchecked")
13.848 + public E previous() {
13.849 + checkForComodification();
13.850 + int i = cursor - 1;
13.851 + if (i < 0)
13.852 + throw new NoSuchElementException();
13.853 + Object[] elementData = ArrayList.this.elementData;
13.854 + if (i >= elementData.length)
13.855 + throw new ConcurrentModificationException();
13.856 + cursor = i;
13.857 + return (E) elementData[lastRet = i];
13.858 + }
13.859 +
13.860 + public void set(E e) {
13.861 + if (lastRet < 0)
13.862 + throw new IllegalStateException();
13.863 + checkForComodification();
13.864 +
13.865 + try {
13.866 + ArrayList.this.set(lastRet, e);
13.867 + } catch (IndexOutOfBoundsException ex) {
13.868 + throw new ConcurrentModificationException();
13.869 + }
13.870 + }
13.871 +
13.872 + public void add(E e) {
13.873 + checkForComodification();
13.874 +
13.875 + try {
13.876 + int i = cursor;
13.877 + ArrayList.this.add(i, e);
13.878 + cursor = i + 1;
13.879 + lastRet = -1;
13.880 + expectedModCount = modCount;
13.881 + } catch (IndexOutOfBoundsException ex) {
13.882 + throw new ConcurrentModificationException();
13.883 + }
13.884 + }
13.885 + }
13.886 +
13.887 + /**
13.888 + * Returns a view of the portion of this list between the specified
13.889 + * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
13.890 + * {@code fromIndex} and {@code toIndex} are equal, the returned list is
13.891 + * empty.) The returned list is backed by this list, so non-structural
13.892 + * changes in the returned list are reflected in this list, and vice-versa.
13.893 + * The returned list supports all of the optional list operations.
13.894 + *
13.895 + * <p>This method eliminates the need for explicit range operations (of
13.896 + * the sort that commonly exist for arrays). Any operation that expects
13.897 + * a list can be used as a range operation by passing a subList view
13.898 + * instead of a whole list. For example, the following idiom
13.899 + * removes a range of elements from a list:
13.900 + * <pre>
13.901 + * list.subList(from, to).clear();
13.902 + * </pre>
13.903 + * Similar idioms may be constructed for {@link #indexOf(Object)} and
13.904 + * {@link #lastIndexOf(Object)}, and all of the algorithms in the
13.905 + * {@link Collections} class can be applied to a subList.
13.906 + *
13.907 + * <p>The semantics of the list returned by this method become undefined if
13.908 + * the backing list (i.e., this list) is <i>structurally modified</i> in
13.909 + * any way other than via the returned list. (Structural modifications are
13.910 + * those that change the size of this list, or otherwise perturb it in such
13.911 + * a fashion that iterations in progress may yield incorrect results.)
13.912 + *
13.913 + * @throws IndexOutOfBoundsException {@inheritDoc}
13.914 + * @throws IllegalArgumentException {@inheritDoc}
13.915 + */
13.916 + public List<E> subList(int fromIndex, int toIndex) {
13.917 + subListRangeCheck(fromIndex, toIndex, size);
13.918 + return new SubList(this, 0, fromIndex, toIndex);
13.919 + }
13.920 +
13.921 + static void subListRangeCheck(int fromIndex, int toIndex, int size) {
13.922 + if (fromIndex < 0)
13.923 + throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
13.924 + if (toIndex > size)
13.925 + throw new IndexOutOfBoundsException("toIndex = " + toIndex);
13.926 + if (fromIndex > toIndex)
13.927 + throw new IllegalArgumentException("fromIndex(" + fromIndex +
13.928 + ") > toIndex(" + toIndex + ")");
13.929 + }
13.930 +
13.931 + private class SubList extends AbstractList<E> implements RandomAccess {
13.932 + private final AbstractList<E> parent;
13.933 + private final int parentOffset;
13.934 + private final int offset;
13.935 + int size;
13.936 +
13.937 + SubList(AbstractList<E> parent,
13.938 + int offset, int fromIndex, int toIndex) {
13.939 + this.parent = parent;
13.940 + this.parentOffset = fromIndex;
13.941 + this.offset = offset + fromIndex;
13.942 + this.size = toIndex - fromIndex;
13.943 + this.modCount = ArrayList.this.modCount;
13.944 + }
13.945 +
13.946 + public E set(int index, E e) {
13.947 + rangeCheck(index);
13.948 + checkForComodification();
13.949 + E oldValue = ArrayList.this.elementData(offset + index);
13.950 + ArrayList.this.elementData[offset + index] = e;
13.951 + return oldValue;
13.952 + }
13.953 +
13.954 + public E get(int index) {
13.955 + rangeCheck(index);
13.956 + checkForComodification();
13.957 + return ArrayList.this.elementData(offset + index);
13.958 + }
13.959 +
13.960 + public int size() {
13.961 + checkForComodification();
13.962 + return this.size;
13.963 + }
13.964 +
13.965 + public void add(int index, E e) {
13.966 + rangeCheckForAdd(index);
13.967 + checkForComodification();
13.968 + parent.add(parentOffset + index, e);
13.969 + this.modCount = parent.modCount;
13.970 + this.size++;
13.971 + }
13.972 +
13.973 + public E remove(int index) {
13.974 + rangeCheck(index);
13.975 + checkForComodification();
13.976 + E result = parent.remove(parentOffset + index);
13.977 + this.modCount = parent.modCount;
13.978 + this.size--;
13.979 + return result;
13.980 + }
13.981 +
13.982 + protected void removeRange(int fromIndex, int toIndex) {
13.983 + checkForComodification();
13.984 + parent.removeRange(parentOffset + fromIndex,
13.985 + parentOffset + toIndex);
13.986 + this.modCount = parent.modCount;
13.987 + this.size -= toIndex - fromIndex;
13.988 + }
13.989 +
13.990 + public boolean addAll(Collection<? extends E> c) {
13.991 + return addAll(this.size, c);
13.992 + }
13.993 +
13.994 + public boolean addAll(int index, Collection<? extends E> c) {
13.995 + rangeCheckForAdd(index);
13.996 + int cSize = c.size();
13.997 + if (cSize==0)
13.998 + return false;
13.999 +
13.1000 + checkForComodification();
13.1001 + parent.addAll(parentOffset + index, c);
13.1002 + this.modCount = parent.modCount;
13.1003 + this.size += cSize;
13.1004 + return true;
13.1005 + }
13.1006 +
13.1007 + public Iterator<E> iterator() {
13.1008 + return listIterator();
13.1009 + }
13.1010 +
13.1011 + public ListIterator<E> listIterator(final int index) {
13.1012 + checkForComodification();
13.1013 + rangeCheckForAdd(index);
13.1014 + final int offset = this.offset;
13.1015 +
13.1016 + return new ListIterator<E>() {
13.1017 + int cursor = index;
13.1018 + int lastRet = -1;
13.1019 + int expectedModCount = ArrayList.this.modCount;
13.1020 +
13.1021 + public boolean hasNext() {
13.1022 + return cursor != SubList.this.size;
13.1023 + }
13.1024 +
13.1025 + @SuppressWarnings("unchecked")
13.1026 + public E next() {
13.1027 + checkForComodification();
13.1028 + int i = cursor;
13.1029 + if (i >= SubList.this.size)
13.1030 + throw new NoSuchElementException();
13.1031 + Object[] elementData = ArrayList.this.elementData;
13.1032 + if (offset + i >= elementData.length)
13.1033 + throw new ConcurrentModificationException();
13.1034 + cursor = i + 1;
13.1035 + return (E) elementData[offset + (lastRet = i)];
13.1036 + }
13.1037 +
13.1038 + public boolean hasPrevious() {
13.1039 + return cursor != 0;
13.1040 + }
13.1041 +
13.1042 + @SuppressWarnings("unchecked")
13.1043 + public E previous() {
13.1044 + checkForComodification();
13.1045 + int i = cursor - 1;
13.1046 + if (i < 0)
13.1047 + throw new NoSuchElementException();
13.1048 + Object[] elementData = ArrayList.this.elementData;
13.1049 + if (offset + i >= elementData.length)
13.1050 + throw new ConcurrentModificationException();
13.1051 + cursor = i;
13.1052 + return (E) elementData[offset + (lastRet = i)];
13.1053 + }
13.1054 +
13.1055 + public int nextIndex() {
13.1056 + return cursor;
13.1057 + }
13.1058 +
13.1059 + public int previousIndex() {
13.1060 + return cursor - 1;
13.1061 + }
13.1062 +
13.1063 + public void remove() {
13.1064 + if (lastRet < 0)
13.1065 + throw new IllegalStateException();
13.1066 + checkForComodification();
13.1067 +
13.1068 + try {
13.1069 + SubList.this.remove(lastRet);
13.1070 + cursor = lastRet;
13.1071 + lastRet = -1;
13.1072 + expectedModCount = ArrayList.this.modCount;
13.1073 + } catch (IndexOutOfBoundsException ex) {
13.1074 + throw new ConcurrentModificationException();
13.1075 + }
13.1076 + }
13.1077 +
13.1078 + public void set(E e) {
13.1079 + if (lastRet < 0)
13.1080 + throw new IllegalStateException();
13.1081 + checkForComodification();
13.1082 +
13.1083 + try {
13.1084 + ArrayList.this.set(offset + lastRet, e);
13.1085 + } catch (IndexOutOfBoundsException ex) {
13.1086 + throw new ConcurrentModificationException();
13.1087 + }
13.1088 + }
13.1089 +
13.1090 + public void add(E e) {
13.1091 + checkForComodification();
13.1092 +
13.1093 + try {
13.1094 + int i = cursor;
13.1095 + SubList.this.add(i, e);
13.1096 + cursor = i + 1;
13.1097 + lastRet = -1;
13.1098 + expectedModCount = ArrayList.this.modCount;
13.1099 + } catch (IndexOutOfBoundsException ex) {
13.1100 + throw new ConcurrentModificationException();
13.1101 + }
13.1102 + }
13.1103 +
13.1104 + final void checkForComodification() {
13.1105 + if (expectedModCount != ArrayList.this.modCount)
13.1106 + throw new ConcurrentModificationException();
13.1107 + }
13.1108 + };
13.1109 + }
13.1110 +
13.1111 + public List<E> subList(int fromIndex, int toIndex) {
13.1112 + subListRangeCheck(fromIndex, toIndex, size);
13.1113 + return new SubList(this, offset, fromIndex, toIndex);
13.1114 + }
13.1115 +
13.1116 + private void rangeCheck(int index) {
13.1117 + if (index < 0 || index >= this.size)
13.1118 + throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
13.1119 + }
13.1120 +
13.1121 + private void rangeCheckForAdd(int index) {
13.1122 + if (index < 0 || index > this.size)
13.1123 + throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
13.1124 + }
13.1125 +
13.1126 + private String outOfBoundsMsg(int index) {
13.1127 + return "Index: "+index+", Size: "+this.size;
13.1128 + }
13.1129 +
13.1130 + private void checkForComodification() {
13.1131 + if (ArrayList.this.modCount != this.modCount)
13.1132 + throw new ConcurrentModificationException();
13.1133 + }
13.1134 + }
13.1135 +}
14.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
14.2 +++ b/emul/compact/src/main/java/java/util/Arrays.java Wed Jan 23 22:33:45 2013 +0100
14.3 @@ -0,0 +1,3673 @@
14.4 +/*
14.5 + * Copyright (c) 1997, 2011, 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 java.lang.reflect.*;
14.32 +
14.33 +/**
14.34 + * This class contains various methods for manipulating arrays (such as
14.35 + * sorting and searching). This class also contains a static factory
14.36 + * that allows arrays to be viewed as lists.
14.37 + *
14.38 + * <p>The methods in this class all throw a {@code NullPointerException},
14.39 + * if the specified array reference is null, except where noted.
14.40 + *
14.41 + * <p>The documentation for the methods contained in this class includes
14.42 + * briefs description of the <i>implementations</i>. Such descriptions should
14.43 + * be regarded as <i>implementation notes</i>, rather than parts of the
14.44 + * <i>specification</i>. Implementors should feel free to substitute other
14.45 + * algorithms, so long as the specification itself is adhered to. (For
14.46 + * example, the algorithm used by {@code sort(Object[])} does not have to be
14.47 + * a MergeSort, but it does have to be <i>stable</i>.)
14.48 + *
14.49 + * <p>This class is a member of the
14.50 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
14.51 + * Java Collections Framework</a>.
14.52 + *
14.53 + * @author Josh Bloch
14.54 + * @author Neal Gafter
14.55 + * @author John Rose
14.56 + * @since 1.2
14.57 + */
14.58 +public class Arrays {
14.59 +
14.60 + // Suppresses default constructor, ensuring non-instantiability.
14.61 + private Arrays() {}
14.62 +
14.63 + /*
14.64 + * Sorting of primitive type arrays.
14.65 + */
14.66 +
14.67 + /**
14.68 + * Sorts the specified array into ascending numerical order.
14.69 + *
14.70 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.71 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.72 + * offers O(n log(n)) performance on many data sets that cause other
14.73 + * quicksorts to degrade to quadratic performance, and is typically
14.74 + * faster than traditional (one-pivot) Quicksort implementations.
14.75 + *
14.76 + * @param a the array to be sorted
14.77 + */
14.78 + public static void sort(int[] a) {
14.79 + DualPivotQuicksort.sort(a);
14.80 + }
14.81 +
14.82 + /**
14.83 + * Sorts the specified range of the array into ascending order. The range
14.84 + * to be sorted extends from the index {@code fromIndex}, inclusive, to
14.85 + * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
14.86 + * the range to be sorted is empty.
14.87 + *
14.88 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.89 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.90 + * offers O(n log(n)) performance on many data sets that cause other
14.91 + * quicksorts to degrade to quadratic performance, and is typically
14.92 + * faster than traditional (one-pivot) Quicksort implementations.
14.93 + *
14.94 + * @param a the array to be sorted
14.95 + * @param fromIndex the index of the first element, inclusive, to be sorted
14.96 + * @param toIndex the index of the last element, exclusive, to be sorted
14.97 + *
14.98 + * @throws IllegalArgumentException if {@code fromIndex > toIndex}
14.99 + * @throws ArrayIndexOutOfBoundsException
14.100 + * if {@code fromIndex < 0} or {@code toIndex > a.length}
14.101 + */
14.102 + public static void sort(int[] a, int fromIndex, int toIndex) {
14.103 + rangeCheck(a.length, fromIndex, toIndex);
14.104 + DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
14.105 + }
14.106 +
14.107 + /**
14.108 + * Sorts the specified array into ascending numerical order.
14.109 + *
14.110 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.111 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.112 + * offers O(n log(n)) performance on many data sets that cause other
14.113 + * quicksorts to degrade to quadratic performance, and is typically
14.114 + * faster than traditional (one-pivot) Quicksort implementations.
14.115 + *
14.116 + * @param a the array to be sorted
14.117 + */
14.118 + public static void sort(long[] a) {
14.119 + DualPivotQuicksort.sort(a);
14.120 + }
14.121 +
14.122 + /**
14.123 + * Sorts the specified range of the array into ascending order. The range
14.124 + * to be sorted extends from the index {@code fromIndex}, inclusive, to
14.125 + * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
14.126 + * the range to be sorted is empty.
14.127 + *
14.128 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.129 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.130 + * offers O(n log(n)) performance on many data sets that cause other
14.131 + * quicksorts to degrade to quadratic performance, and is typically
14.132 + * faster than traditional (one-pivot) Quicksort implementations.
14.133 + *
14.134 + * @param a the array to be sorted
14.135 + * @param fromIndex the index of the first element, inclusive, to be sorted
14.136 + * @param toIndex the index of the last element, exclusive, to be sorted
14.137 + *
14.138 + * @throws IllegalArgumentException if {@code fromIndex > toIndex}
14.139 + * @throws ArrayIndexOutOfBoundsException
14.140 + * if {@code fromIndex < 0} or {@code toIndex > a.length}
14.141 + */
14.142 + public static void sort(long[] a, int fromIndex, int toIndex) {
14.143 + rangeCheck(a.length, fromIndex, toIndex);
14.144 + DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
14.145 + }
14.146 +
14.147 + /**
14.148 + * Sorts the specified array into ascending numerical order.
14.149 + *
14.150 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.151 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.152 + * offers O(n log(n)) performance on many data sets that cause other
14.153 + * quicksorts to degrade to quadratic performance, and is typically
14.154 + * faster than traditional (one-pivot) Quicksort implementations.
14.155 + *
14.156 + * @param a the array to be sorted
14.157 + */
14.158 + public static void sort(short[] a) {
14.159 + DualPivotQuicksort.sort(a);
14.160 + }
14.161 +
14.162 + /**
14.163 + * Sorts the specified range of the array into ascending order. The range
14.164 + * to be sorted extends from the index {@code fromIndex}, inclusive, to
14.165 + * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
14.166 + * the range to be sorted is empty.
14.167 + *
14.168 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.169 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.170 + * offers O(n log(n)) performance on many data sets that cause other
14.171 + * quicksorts to degrade to quadratic performance, and is typically
14.172 + * faster than traditional (one-pivot) Quicksort implementations.
14.173 + *
14.174 + * @param a the array to be sorted
14.175 + * @param fromIndex the index of the first element, inclusive, to be sorted
14.176 + * @param toIndex the index of the last element, exclusive, to be sorted
14.177 + *
14.178 + * @throws IllegalArgumentException if {@code fromIndex > toIndex}
14.179 + * @throws ArrayIndexOutOfBoundsException
14.180 + * if {@code fromIndex < 0} or {@code toIndex > a.length}
14.181 + */
14.182 + public static void sort(short[] a, int fromIndex, int toIndex) {
14.183 + rangeCheck(a.length, fromIndex, toIndex);
14.184 + DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
14.185 + }
14.186 +
14.187 + /**
14.188 + * Sorts the specified array into ascending numerical order.
14.189 + *
14.190 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.191 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.192 + * offers O(n log(n)) performance on many data sets that cause other
14.193 + * quicksorts to degrade to quadratic performance, and is typically
14.194 + * faster than traditional (one-pivot) Quicksort implementations.
14.195 + *
14.196 + * @param a the array to be sorted
14.197 + */
14.198 + public static void sort(char[] a) {
14.199 + DualPivotQuicksort.sort(a);
14.200 + }
14.201 +
14.202 + /**
14.203 + * Sorts the specified range of the array into ascending order. The range
14.204 + * to be sorted extends from the index {@code fromIndex}, inclusive, to
14.205 + * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
14.206 + * the range to be sorted is empty.
14.207 + *
14.208 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.209 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.210 + * offers O(n log(n)) performance on many data sets that cause other
14.211 + * quicksorts to degrade to quadratic performance, and is typically
14.212 + * faster than traditional (one-pivot) Quicksort implementations.
14.213 + *
14.214 + * @param a the array to be sorted
14.215 + * @param fromIndex the index of the first element, inclusive, to be sorted
14.216 + * @param toIndex the index of the last element, exclusive, to be sorted
14.217 + *
14.218 + * @throws IllegalArgumentException if {@code fromIndex > toIndex}
14.219 + * @throws ArrayIndexOutOfBoundsException
14.220 + * if {@code fromIndex < 0} or {@code toIndex > a.length}
14.221 + */
14.222 + public static void sort(char[] a, int fromIndex, int toIndex) {
14.223 + rangeCheck(a.length, fromIndex, toIndex);
14.224 + DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
14.225 + }
14.226 +
14.227 + /**
14.228 + * Sorts the specified array into ascending numerical order.
14.229 + *
14.230 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.231 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.232 + * offers O(n log(n)) performance on many data sets that cause other
14.233 + * quicksorts to degrade to quadratic performance, and is typically
14.234 + * faster than traditional (one-pivot) Quicksort implementations.
14.235 + *
14.236 + * @param a the array to be sorted
14.237 + */
14.238 + public static void sort(byte[] a) {
14.239 + DualPivotQuicksort.sort(a);
14.240 + }
14.241 +
14.242 + /**
14.243 + * Sorts the specified range of the array into ascending order. The range
14.244 + * to be sorted extends from the index {@code fromIndex}, inclusive, to
14.245 + * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
14.246 + * the range to be sorted is empty.
14.247 + *
14.248 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.249 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.250 + * offers O(n log(n)) performance on many data sets that cause other
14.251 + * quicksorts to degrade to quadratic performance, and is typically
14.252 + * faster than traditional (one-pivot) Quicksort implementations.
14.253 + *
14.254 + * @param a the array to be sorted
14.255 + * @param fromIndex the index of the first element, inclusive, to be sorted
14.256 + * @param toIndex the index of the last element, exclusive, to be sorted
14.257 + *
14.258 + * @throws IllegalArgumentException if {@code fromIndex > toIndex}
14.259 + * @throws ArrayIndexOutOfBoundsException
14.260 + * if {@code fromIndex < 0} or {@code toIndex > a.length}
14.261 + */
14.262 + public static void sort(byte[] a, int fromIndex, int toIndex) {
14.263 + rangeCheck(a.length, fromIndex, toIndex);
14.264 + DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
14.265 + }
14.266 +
14.267 + /**
14.268 + * Sorts the specified array into ascending numerical order.
14.269 + *
14.270 + * <p>The {@code <} relation does not provide a total order on all float
14.271 + * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
14.272 + * value compares neither less than, greater than, nor equal to any value,
14.273 + * even itself. This method uses the total order imposed by the method
14.274 + * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
14.275 + * {@code 0.0f} and {@code Float.NaN} is considered greater than any
14.276 + * other value and all {@code Float.NaN} values are considered equal.
14.277 + *
14.278 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.279 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.280 + * offers O(n log(n)) performance on many data sets that cause other
14.281 + * quicksorts to degrade to quadratic performance, and is typically
14.282 + * faster than traditional (one-pivot) Quicksort implementations.
14.283 + *
14.284 + * @param a the array to be sorted
14.285 + */
14.286 + public static void sort(float[] a) {
14.287 + DualPivotQuicksort.sort(a);
14.288 + }
14.289 +
14.290 + /**
14.291 + * Sorts the specified range of the array into ascending order. The range
14.292 + * to be sorted extends from the index {@code fromIndex}, inclusive, to
14.293 + * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
14.294 + * the range to be sorted is empty.
14.295 + *
14.296 + * <p>The {@code <} relation does not provide a total order on all float
14.297 + * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
14.298 + * value compares neither less than, greater than, nor equal to any value,
14.299 + * even itself. This method uses the total order imposed by the method
14.300 + * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
14.301 + * {@code 0.0f} and {@code Float.NaN} is considered greater than any
14.302 + * other value and all {@code Float.NaN} values are considered equal.
14.303 + *
14.304 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.305 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.306 + * offers O(n log(n)) performance on many data sets that cause other
14.307 + * quicksorts to degrade to quadratic performance, and is typically
14.308 + * faster than traditional (one-pivot) Quicksort implementations.
14.309 + *
14.310 + * @param a the array to be sorted
14.311 + * @param fromIndex the index of the first element, inclusive, to be sorted
14.312 + * @param toIndex the index of the last element, exclusive, to be sorted
14.313 + *
14.314 + * @throws IllegalArgumentException if {@code fromIndex > toIndex}
14.315 + * @throws ArrayIndexOutOfBoundsException
14.316 + * if {@code fromIndex < 0} or {@code toIndex > a.length}
14.317 + */
14.318 + public static void sort(float[] a, int fromIndex, int toIndex) {
14.319 + rangeCheck(a.length, fromIndex, toIndex);
14.320 + DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
14.321 + }
14.322 +
14.323 + /**
14.324 + * Sorts the specified array into ascending numerical order.
14.325 + *
14.326 + * <p>The {@code <} relation does not provide a total order on all double
14.327 + * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
14.328 + * value compares neither less than, greater than, nor equal to any value,
14.329 + * even itself. This method uses the total order imposed by the method
14.330 + * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
14.331 + * {@code 0.0d} and {@code Double.NaN} is considered greater than any
14.332 + * other value and all {@code Double.NaN} values are considered equal.
14.333 + *
14.334 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.335 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.336 + * offers O(n log(n)) performance on many data sets that cause other
14.337 + * quicksorts to degrade to quadratic performance, and is typically
14.338 + * faster than traditional (one-pivot) Quicksort implementations.
14.339 + *
14.340 + * @param a the array to be sorted
14.341 + */
14.342 + public static void sort(double[] a) {
14.343 + DualPivotQuicksort.sort(a);
14.344 + }
14.345 +
14.346 + /**
14.347 + * Sorts the specified range of the array into ascending order. The range
14.348 + * to be sorted extends from the index {@code fromIndex}, inclusive, to
14.349 + * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
14.350 + * the range to be sorted is empty.
14.351 + *
14.352 + * <p>The {@code <} relation does not provide a total order on all double
14.353 + * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
14.354 + * value compares neither less than, greater than, nor equal to any value,
14.355 + * even itself. This method uses the total order imposed by the method
14.356 + * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
14.357 + * {@code 0.0d} and {@code Double.NaN} is considered greater than any
14.358 + * other value and all {@code Double.NaN} values are considered equal.
14.359 + *
14.360 + * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
14.361 + * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
14.362 + * offers O(n log(n)) performance on many data sets that cause other
14.363 + * quicksorts to degrade to quadratic performance, and is typically
14.364 + * faster than traditional (one-pivot) Quicksort implementations.
14.365 + *
14.366 + * @param a the array to be sorted
14.367 + * @param fromIndex the index of the first element, inclusive, to be sorted
14.368 + * @param toIndex the index of the last element, exclusive, to be sorted
14.369 + *
14.370 + * @throws IllegalArgumentException if {@code fromIndex > toIndex}
14.371 + * @throws ArrayIndexOutOfBoundsException
14.372 + * if {@code fromIndex < 0} or {@code toIndex > a.length}
14.373 + */
14.374 + public static void sort(double[] a, int fromIndex, int toIndex) {
14.375 + rangeCheck(a.length, fromIndex, toIndex);
14.376 + DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
14.377 + }
14.378 +
14.379 + /*
14.380 + * Sorting of complex type arrays.
14.381 + */
14.382 +
14.383 + /**
14.384 + * Old merge sort implementation can be selected (for
14.385 + * compatibility with broken comparators) using a system property.
14.386 + * Cannot be a static boolean in the enclosing class due to
14.387 + * circular dependencies. To be removed in a future release.
14.388 + */
14.389 + static final class LegacyMergeSort {
14.390 + private static final boolean userRequested =
14.391 + java.security.AccessController.doPrivileged(
14.392 + new sun.security.action.GetBooleanAction(
14.393 + "java.util.Arrays.useLegacyMergeSort")).booleanValue();
14.394 + }
14.395 +
14.396 + /*
14.397 + * If this platform has an optimizing VM, check whether ComparableTimSort
14.398 + * offers any performance benefit over TimSort in conjunction with a
14.399 + * comparator that returns:
14.400 + * {@code ((Comparable)first).compareTo(Second)}.
14.401 + * If not, you are better off deleting ComparableTimSort to
14.402 + * eliminate the code duplication. In other words, the commented
14.403 + * out code below is the preferable implementation for sorting
14.404 + * arrays of Comparables if it offers sufficient performance.
14.405 + */
14.406 +
14.407 +// /**
14.408 +// * A comparator that implements the natural ordering of a group of
14.409 +// * mutually comparable elements. Using this comparator saves us
14.410 +// * from duplicating most of the code in this file (one version for
14.411 +// * Comparables, one for explicit Comparators).
14.412 +// */
14.413 +// private static final Comparator<Object> NATURAL_ORDER =
14.414 +// new Comparator<Object>() {
14.415 +// @SuppressWarnings("unchecked")
14.416 +// public int compare(Object first, Object second) {
14.417 +// return ((Comparable<Object>)first).compareTo(second);
14.418 +// }
14.419 +// };
14.420 +//
14.421 +// public static void sort(Object[] a) {
14.422 +// sort(a, 0, a.length, NATURAL_ORDER);
14.423 +// }
14.424 +//
14.425 +// public static void sort(Object[] a, int fromIndex, int toIndex) {
14.426 +// sort(a, fromIndex, toIndex, NATURAL_ORDER);
14.427 +// }
14.428 +
14.429 + /**
14.430 + * Sorts the specified array of objects into ascending order, according
14.431 + * to the {@linkplain Comparable natural ordering} of its elements.
14.432 + * All elements in the array must implement the {@link Comparable}
14.433 + * interface. Furthermore, all elements in the array must be
14.434 + * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} must
14.435 + * not throw a {@code ClassCastException} for any elements {@code e1}
14.436 + * and {@code e2} in the array).
14.437 + *
14.438 + * <p>This sort is guaranteed to be <i>stable</i>: equal elements will
14.439 + * not be reordered as a result of the sort.
14.440 + *
14.441 + * <p>Implementation note: This implementation is a stable, adaptive,
14.442 + * iterative mergesort that requires far fewer than n lg(n) comparisons
14.443 + * when the input array is partially sorted, while offering the
14.444 + * performance of a traditional mergesort when the input array is
14.445 + * randomly ordered. If the input array is nearly sorted, the
14.446 + * implementation requires approximately n comparisons. Temporary
14.447 + * storage requirements vary from a small constant for nearly sorted
14.448 + * input arrays to n/2 object references for randomly ordered input
14.449 + * arrays.
14.450 + *
14.451 + * <p>The implementation takes equal advantage of ascending and
14.452 + * descending order in its input array, and can take advantage of
14.453 + * ascending and descending order in different parts of the the same
14.454 + * input array. It is well-suited to merging two or more sorted arrays:
14.455 + * simply concatenate the arrays and sort the resulting array.
14.456 + *
14.457 + * <p>The implementation was adapted from Tim Peters's list sort for Python
14.458 + * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
14.459 + * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic
14.460 + * Sorting and Information Theoretic Complexity", in Proceedings of the
14.461 + * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
14.462 + * January 1993.
14.463 + *
14.464 + * @param a the array to be sorted
14.465 + * @throws ClassCastException if the array contains elements that are not
14.466 + * <i>mutually comparable</i> (for example, strings and integers)
14.467 + * @throws IllegalArgumentException (optional) if the natural
14.468 + * ordering of the array elements is found to violate the
14.469 + * {@link Comparable} contract
14.470 + */
14.471 + public static void sort(Object[] a) {
14.472 + if (LegacyMergeSort.userRequested)
14.473 + legacyMergeSort(a);
14.474 + else
14.475 + ComparableTimSort.sort(a);
14.476 + }
14.477 +
14.478 + /** To be removed in a future release. */
14.479 + private static void legacyMergeSort(Object[] a) {
14.480 + Object[] aux = a.clone();
14.481 + mergeSort(aux, a, 0, a.length, 0);
14.482 + }
14.483 +
14.484 + /**
14.485 + * Sorts the specified range of the specified array of objects into
14.486 + * ascending order, according to the
14.487 + * {@linkplain Comparable natural ordering} of its
14.488 + * elements. The range to be sorted extends from index
14.489 + * {@code fromIndex}, inclusive, to index {@code toIndex}, exclusive.
14.490 + * (If {@code fromIndex==toIndex}, the range to be sorted is empty.) All
14.491 + * elements in this range must implement the {@link Comparable}
14.492 + * interface. Furthermore, all elements in this range must be <i>mutually
14.493 + * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
14.494 + * {@code ClassCastException} for any elements {@code e1} and
14.495 + * {@code e2} in the array).
14.496 + *
14.497 + * <p>This sort is guaranteed to be <i>stable</i>: equal elements will
14.498 + * not be reordered as a result of the sort.
14.499 + *
14.500 + * <p>Implementation note: This implementation is a stable, adaptive,
14.501 + * iterative mergesort that requires far fewer than n lg(n) comparisons
14.502 + * when the input array is partially sorted, while offering the
14.503 + * performance of a traditional mergesort when the input array is
14.504 + * randomly ordered. If the input array is nearly sorted, the
14.505 + * implementation requires approximately n comparisons. Temporary
14.506 + * storage requirements vary from a small constant for nearly sorted
14.507 + * input arrays to n/2 object references for randomly ordered input
14.508 + * arrays.
14.509 + *
14.510 + * <p>The implementation takes equal advantage of ascending and
14.511 + * descending order in its input array, and can take advantage of
14.512 + * ascending and descending order in different parts of the the same
14.513 + * input array. It is well-suited to merging two or more sorted arrays:
14.514 + * simply concatenate the arrays and sort the resulting array.
14.515 + *
14.516 + * <p>The implementation was adapted from Tim Peters's list sort for Python
14.517 + * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
14.518 + * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic
14.519 + * Sorting and Information Theoretic Complexity", in Proceedings of the
14.520 + * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
14.521 + * January 1993.
14.522 + *
14.523 + * @param a the array to be sorted
14.524 + * @param fromIndex the index of the first element (inclusive) to be
14.525 + * sorted
14.526 + * @param toIndex the index of the last element (exclusive) to be sorted
14.527 + * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
14.528 + * (optional) if the natural ordering of the array elements is
14.529 + * found to violate the {@link Comparable} contract
14.530 + * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
14.531 + * {@code toIndex > a.length}
14.532 + * @throws ClassCastException if the array contains elements that are
14.533 + * not <i>mutually comparable</i> (for example, strings and
14.534 + * integers).
14.535 + */
14.536 + public static void sort(Object[] a, int fromIndex, int toIndex) {
14.537 + if (LegacyMergeSort.userRequested)
14.538 + legacyMergeSort(a, fromIndex, toIndex);
14.539 + else
14.540 + ComparableTimSort.sort(a, fromIndex, toIndex);
14.541 + }
14.542 +
14.543 + /** To be removed in a future release. */
14.544 + private static void legacyMergeSort(Object[] a,
14.545 + int fromIndex, int toIndex) {
14.546 + rangeCheck(a.length, fromIndex, toIndex);
14.547 + Object[] aux = copyOfRange(a, fromIndex, toIndex);
14.548 + mergeSort(aux, a, fromIndex, toIndex, -fromIndex);
14.549 + }
14.550 +
14.551 + /**
14.552 + * Tuning parameter: list size at or below which insertion sort will be
14.553 + * used in preference to mergesort.
14.554 + * To be removed in a future release.
14.555 + */
14.556 + private static final int INSERTIONSORT_THRESHOLD = 7;
14.557 +
14.558 + /**
14.559 + * Src is the source array that starts at index 0
14.560 + * Dest is the (possibly larger) array destination with a possible offset
14.561 + * low is the index in dest to start sorting
14.562 + * high is the end index in dest to end sorting
14.563 + * off is the offset to generate corresponding low, high in src
14.564 + * To be removed in a future release.
14.565 + */
14.566 + private static void mergeSort(Object[] src,
14.567 + Object[] dest,
14.568 + int low,
14.569 + int high,
14.570 + int off) {
14.571 + int length = high - low;
14.572 +
14.573 + // Insertion sort on smallest arrays
14.574 + if (length < INSERTIONSORT_THRESHOLD) {
14.575 + for (int i=low; i<high; i++)
14.576 + for (int j=i; j>low &&
14.577 + ((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
14.578 + swap(dest, j, j-1);
14.579 + return;
14.580 + }
14.581 +
14.582 + // Recursively sort halves of dest into src
14.583 + int destLow = low;
14.584 + int destHigh = high;
14.585 + low += off;
14.586 + high += off;
14.587 + int mid = (low + high) >>> 1;
14.588 + mergeSort(dest, src, low, mid, -off);
14.589 + mergeSort(dest, src, mid, high, -off);
14.590 +
14.591 + // If list is already sorted, just copy from src to dest. This is an
14.592 + // optimization that results in faster sorts for nearly ordered lists.
14.593 + if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
14.594 + System.arraycopy(src, low, dest, destLow, length);
14.595 + return;
14.596 + }
14.597 +
14.598 + // Merge sorted halves (now in src) into dest
14.599 + for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
14.600 + if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
14.601 + dest[i] = src[p++];
14.602 + else
14.603 + dest[i] = src[q++];
14.604 + }
14.605 + }
14.606 +
14.607 + /**
14.608 + * Swaps x[a] with x[b].
14.609 + */
14.610 + private static void swap(Object[] x, int a, int b) {
14.611 + Object t = x[a];
14.612 + x[a] = x[b];
14.613 + x[b] = t;
14.614 + }
14.615 +
14.616 + /**
14.617 + * Sorts the specified array of objects according to the order induced by
14.618 + * the specified comparator. All elements in the array must be
14.619 + * <i>mutually comparable</i> by the specified comparator (that is,
14.620 + * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
14.621 + * for any elements {@code e1} and {@code e2} in the array).
14.622 + *
14.623 + * <p>This sort is guaranteed to be <i>stable</i>: equal elements will
14.624 + * not be reordered as a result of the sort.
14.625 + *
14.626 + * <p>Implementation note: This implementation is a stable, adaptive,
14.627 + * iterative mergesort that requires far fewer than n lg(n) comparisons
14.628 + * when the input array is partially sorted, while offering the
14.629 + * performance of a traditional mergesort when the input array is
14.630 + * randomly ordered. If the input array is nearly sorted, the
14.631 + * implementation requires approximately n comparisons. Temporary
14.632 + * storage requirements vary from a small constant for nearly sorted
14.633 + * input arrays to n/2 object references for randomly ordered input
14.634 + * arrays.
14.635 + *
14.636 + * <p>The implementation takes equal advantage of ascending and
14.637 + * descending order in its input array, and can take advantage of
14.638 + * ascending and descending order in different parts of the the same
14.639 + * input array. It is well-suited to merging two or more sorted arrays:
14.640 + * simply concatenate the arrays and sort the resulting array.
14.641 + *
14.642 + * <p>The implementation was adapted from Tim Peters's list sort for Python
14.643 + * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
14.644 + * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic
14.645 + * Sorting and Information Theoretic Complexity", in Proceedings of the
14.646 + * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
14.647 + * January 1993.
14.648 + *
14.649 + * @param a the array to be sorted
14.650 + * @param c the comparator to determine the order of the array. A
14.651 + * {@code null} value indicates that the elements'
14.652 + * {@linkplain Comparable natural ordering} should be used.
14.653 + * @throws ClassCastException if the array contains elements that are
14.654 + * not <i>mutually comparable</i> using the specified comparator
14.655 + * @throws IllegalArgumentException (optional) if the comparator is
14.656 + * found to violate the {@link Comparator} contract
14.657 + */
14.658 + public static <T> void sort(T[] a, Comparator<? super T> c) {
14.659 + if (LegacyMergeSort.userRequested)
14.660 + legacyMergeSort(a, c);
14.661 + else
14.662 + TimSort.sort(a, c);
14.663 + }
14.664 +
14.665 + /** To be removed in a future release. */
14.666 + private static <T> void legacyMergeSort(T[] a, Comparator<? super T> c) {
14.667 + T[] aux = a.clone();
14.668 + if (c==null)
14.669 + mergeSort(aux, a, 0, a.length, 0);
14.670 + else
14.671 + mergeSort(aux, a, 0, a.length, 0, c);
14.672 + }
14.673 +
14.674 + /**
14.675 + * Sorts the specified range of the specified array of objects according
14.676 + * to the order induced by the specified comparator. The range to be
14.677 + * sorted extends from index {@code fromIndex}, inclusive, to index
14.678 + * {@code toIndex}, exclusive. (If {@code fromIndex==toIndex}, the
14.679 + * range to be sorted is empty.) All elements in the range must be
14.680 + * <i>mutually comparable</i> by the specified comparator (that is,
14.681 + * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
14.682 + * for any elements {@code e1} and {@code e2} in the range).
14.683 + *
14.684 + * <p>This sort is guaranteed to be <i>stable</i>: equal elements will
14.685 + * not be reordered as a result of the sort.
14.686 + *
14.687 + * <p>Implementation note: This implementation is a stable, adaptive,
14.688 + * iterative mergesort that requires far fewer than n lg(n) comparisons
14.689 + * when the input array is partially sorted, while offering the
14.690 + * performance of a traditional mergesort when the input array is
14.691 + * randomly ordered. If the input array is nearly sorted, the
14.692 + * implementation requires approximately n comparisons. Temporary
14.693 + * storage requirements vary from a small constant for nearly sorted
14.694 + * input arrays to n/2 object references for randomly ordered input
14.695 + * arrays.
14.696 + *
14.697 + * <p>The implementation takes equal advantage of ascending and
14.698 + * descending order in its input array, and can take advantage of
14.699 + * ascending and descending order in different parts of the the same
14.700 + * input array. It is well-suited to merging two or more sorted arrays:
14.701 + * simply concatenate the arrays and sort the resulting array.
14.702 + *
14.703 + * <p>The implementation was adapted from Tim Peters's list sort for Python
14.704 + * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
14.705 + * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic
14.706 + * Sorting and Information Theoretic Complexity", in Proceedings of the
14.707 + * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
14.708 + * January 1993.
14.709 + *
14.710 + * @param a the array to be sorted
14.711 + * @param fromIndex the index of the first element (inclusive) to be
14.712 + * sorted
14.713 + * @param toIndex the index of the last element (exclusive) to be sorted
14.714 + * @param c the comparator to determine the order of the array. A
14.715 + * {@code null} value indicates that the elements'
14.716 + * {@linkplain Comparable natural ordering} should be used.
14.717 + * @throws ClassCastException if the array contains elements that are not
14.718 + * <i>mutually comparable</i> using the specified comparator.
14.719 + * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
14.720 + * (optional) if the comparator is found to violate the
14.721 + * {@link Comparator} contract
14.722 + * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
14.723 + * {@code toIndex > a.length}
14.724 + */
14.725 + public static <T> void sort(T[] a, int fromIndex, int toIndex,
14.726 + Comparator<? super T> c) {
14.727 + if (LegacyMergeSort.userRequested)
14.728 + legacyMergeSort(a, fromIndex, toIndex, c);
14.729 + else
14.730 + TimSort.sort(a, fromIndex, toIndex, c);
14.731 + }
14.732 +
14.733 + /** To be removed in a future release. */
14.734 + private static <T> void legacyMergeSort(T[] a, int fromIndex, int toIndex,
14.735 + Comparator<? super T> c) {
14.736 + rangeCheck(a.length, fromIndex, toIndex);
14.737 + T[] aux = copyOfRange(a, fromIndex, toIndex);
14.738 + if (c==null)
14.739 + mergeSort(aux, a, fromIndex, toIndex, -fromIndex);
14.740 + else
14.741 + mergeSort(aux, a, fromIndex, toIndex, -fromIndex, c);
14.742 + }
14.743 +
14.744 + /**
14.745 + * Src is the source array that starts at index 0
14.746 + * Dest is the (possibly larger) array destination with a possible offset
14.747 + * low is the index in dest to start sorting
14.748 + * high is the end index in dest to end sorting
14.749 + * off is the offset into src corresponding to low in dest
14.750 + * To be removed in a future release.
14.751 + */
14.752 + private static void mergeSort(Object[] src,
14.753 + Object[] dest,
14.754 + int low, int high, int off,
14.755 + Comparator c) {
14.756 + int length = high - low;
14.757 +
14.758 + // Insertion sort on smallest arrays
14.759 + if (length < INSERTIONSORT_THRESHOLD) {
14.760 + for (int i=low; i<high; i++)
14.761 + for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
14.762 + swap(dest, j, j-1);
14.763 + return;
14.764 + }
14.765 +
14.766 + // Recursively sort halves of dest into src
14.767 + int destLow = low;
14.768 + int destHigh = high;
14.769 + low += off;
14.770 + high += off;
14.771 + int mid = (low + high) >>> 1;
14.772 + mergeSort(dest, src, low, mid, -off, c);
14.773 + mergeSort(dest, src, mid, high, -off, c);
14.774 +
14.775 + // If list is already sorted, just copy from src to dest. This is an
14.776 + // optimization that results in faster sorts for nearly ordered lists.
14.777 + if (c.compare(src[mid-1], src[mid]) <= 0) {
14.778 + System.arraycopy(src, low, dest, destLow, length);
14.779 + return;
14.780 + }
14.781 +
14.782 + // Merge sorted halves (now in src) into dest
14.783 + for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
14.784 + if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0)
14.785 + dest[i] = src[p++];
14.786 + else
14.787 + dest[i] = src[q++];
14.788 + }
14.789 + }
14.790 +
14.791 + /**
14.792 + * Checks that {@code fromIndex} and {@code toIndex} are in
14.793 + * the range and throws an appropriate exception, if they aren't.
14.794 + */
14.795 + private static void rangeCheck(int length, int fromIndex, int toIndex) {
14.796 + if (fromIndex > toIndex) {
14.797 + throw new IllegalArgumentException(
14.798 + "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
14.799 + }
14.800 + if (fromIndex < 0) {
14.801 + throw new ArrayIndexOutOfBoundsException(fromIndex);
14.802 + }
14.803 + if (toIndex > length) {
14.804 + throw new ArrayIndexOutOfBoundsException(toIndex);
14.805 + }
14.806 + }
14.807 +
14.808 + // Searching
14.809 +
14.810 + /**
14.811 + * Searches the specified array of longs for the specified value using the
14.812 + * binary search algorithm. The array must be sorted (as
14.813 + * by the {@link #sort(long[])} method) prior to making this call. If it
14.814 + * is not sorted, the results are undefined. If the array contains
14.815 + * multiple elements with the specified value, there is no guarantee which
14.816 + * one will be found.
14.817 + *
14.818 + * @param a the array to be searched
14.819 + * @param key the value to be searched for
14.820 + * @return index of the search key, if it is contained in the array;
14.821 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.822 + * <i>insertion point</i> is defined as the point at which the
14.823 + * key would be inserted into the array: the index of the first
14.824 + * element greater than the key, or <tt>a.length</tt> if all
14.825 + * elements in the array are less than the specified key. Note
14.826 + * that this guarantees that the return value will be >= 0 if
14.827 + * and only if the key is found.
14.828 + */
14.829 + public static int binarySearch(long[] a, long key) {
14.830 + return binarySearch0(a, 0, a.length, key);
14.831 + }
14.832 +
14.833 + /**
14.834 + * Searches a range of
14.835 + * the specified array of longs for the specified value using the
14.836 + * binary search algorithm.
14.837 + * The range must be sorted (as
14.838 + * by the {@link #sort(long[], int, int)} method)
14.839 + * prior to making this call. If it
14.840 + * is not sorted, the results are undefined. If the range contains
14.841 + * multiple elements with the specified value, there is no guarantee which
14.842 + * one will be found.
14.843 + *
14.844 + * @param a the array to be searched
14.845 + * @param fromIndex the index of the first element (inclusive) to be
14.846 + * searched
14.847 + * @param toIndex the index of the last element (exclusive) to be searched
14.848 + * @param key the value to be searched for
14.849 + * @return index of the search key, if it is contained in the array
14.850 + * within the specified range;
14.851 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.852 + * <i>insertion point</i> is defined as the point at which the
14.853 + * key would be inserted into the array: the index of the first
14.854 + * element in the range greater than the key,
14.855 + * or <tt>toIndex</tt> if all
14.856 + * elements in the range are less than the specified key. Note
14.857 + * that this guarantees that the return value will be >= 0 if
14.858 + * and only if the key is found.
14.859 + * @throws IllegalArgumentException
14.860 + * if {@code fromIndex > toIndex}
14.861 + * @throws ArrayIndexOutOfBoundsException
14.862 + * if {@code fromIndex < 0 or toIndex > a.length}
14.863 + * @since 1.6
14.864 + */
14.865 + public static int binarySearch(long[] a, int fromIndex, int toIndex,
14.866 + long key) {
14.867 + rangeCheck(a.length, fromIndex, toIndex);
14.868 + return binarySearch0(a, fromIndex, toIndex, key);
14.869 + }
14.870 +
14.871 + // Like public version, but without range checks.
14.872 + private static int binarySearch0(long[] a, int fromIndex, int toIndex,
14.873 + long key) {
14.874 + int low = fromIndex;
14.875 + int high = toIndex - 1;
14.876 +
14.877 + while (low <= high) {
14.878 + int mid = (low + high) >>> 1;
14.879 + long midVal = a[mid];
14.880 +
14.881 + if (midVal < key)
14.882 + low = mid + 1;
14.883 + else if (midVal > key)
14.884 + high = mid - 1;
14.885 + else
14.886 + return mid; // key found
14.887 + }
14.888 + return -(low + 1); // key not found.
14.889 + }
14.890 +
14.891 + /**
14.892 + * Searches the specified array of ints for the specified value using the
14.893 + * binary search algorithm. The array must be sorted (as
14.894 + * by the {@link #sort(int[])} method) prior to making this call. If it
14.895 + * is not sorted, the results are undefined. If the array contains
14.896 + * multiple elements with the specified value, there is no guarantee which
14.897 + * one will be found.
14.898 + *
14.899 + * @param a the array to be searched
14.900 + * @param key the value to be searched for
14.901 + * @return index of the search key, if it is contained in the array;
14.902 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.903 + * <i>insertion point</i> is defined as the point at which the
14.904 + * key would be inserted into the array: the index of the first
14.905 + * element greater than the key, or <tt>a.length</tt> if all
14.906 + * elements in the array are less than the specified key. Note
14.907 + * that this guarantees that the return value will be >= 0 if
14.908 + * and only if the key is found.
14.909 + */
14.910 + public static int binarySearch(int[] a, int key) {
14.911 + return binarySearch0(a, 0, a.length, key);
14.912 + }
14.913 +
14.914 + /**
14.915 + * Searches a range of
14.916 + * the specified array of ints for the specified value using the
14.917 + * binary search algorithm.
14.918 + * The range must be sorted (as
14.919 + * by the {@link #sort(int[], int, int)} method)
14.920 + * prior to making this call. If it
14.921 + * is not sorted, the results are undefined. If the range contains
14.922 + * multiple elements with the specified value, there is no guarantee which
14.923 + * one will be found.
14.924 + *
14.925 + * @param a the array to be searched
14.926 + * @param fromIndex the index of the first element (inclusive) to be
14.927 + * searched
14.928 + * @param toIndex the index of the last element (exclusive) to be searched
14.929 + * @param key the value to be searched for
14.930 + * @return index of the search key, if it is contained in the array
14.931 + * within the specified range;
14.932 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.933 + * <i>insertion point</i> is defined as the point at which the
14.934 + * key would be inserted into the array: the index of the first
14.935 + * element in the range greater than the key,
14.936 + * or <tt>toIndex</tt> if all
14.937 + * elements in the range are less than the specified key. Note
14.938 + * that this guarantees that the return value will be >= 0 if
14.939 + * and only if the key is found.
14.940 + * @throws IllegalArgumentException
14.941 + * if {@code fromIndex > toIndex}
14.942 + * @throws ArrayIndexOutOfBoundsException
14.943 + * if {@code fromIndex < 0 or toIndex > a.length}
14.944 + * @since 1.6
14.945 + */
14.946 + public static int binarySearch(int[] a, int fromIndex, int toIndex,
14.947 + int key) {
14.948 + rangeCheck(a.length, fromIndex, toIndex);
14.949 + return binarySearch0(a, fromIndex, toIndex, key);
14.950 + }
14.951 +
14.952 + // Like public version, but without range checks.
14.953 + private static int binarySearch0(int[] a, int fromIndex, int toIndex,
14.954 + int key) {
14.955 + int low = fromIndex;
14.956 + int high = toIndex - 1;
14.957 +
14.958 + while (low <= high) {
14.959 + int mid = (low + high) >>> 1;
14.960 + int midVal = a[mid];
14.961 +
14.962 + if (midVal < key)
14.963 + low = mid + 1;
14.964 + else if (midVal > key)
14.965 + high = mid - 1;
14.966 + else
14.967 + return mid; // key found
14.968 + }
14.969 + return -(low + 1); // key not found.
14.970 + }
14.971 +
14.972 + /**
14.973 + * Searches the specified array of shorts for the specified value using
14.974 + * the binary search algorithm. The array must be sorted
14.975 + * (as by the {@link #sort(short[])} method) prior to making this call. If
14.976 + * it is not sorted, the results are undefined. If the array contains
14.977 + * multiple elements with the specified value, there is no guarantee which
14.978 + * one will be found.
14.979 + *
14.980 + * @param a the array to be searched
14.981 + * @param key the value to be searched for
14.982 + * @return index of the search key, if it is contained in the array;
14.983 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.984 + * <i>insertion point</i> is defined as the point at which the
14.985 + * key would be inserted into the array: the index of the first
14.986 + * element greater than the key, or <tt>a.length</tt> if all
14.987 + * elements in the array are less than the specified key. Note
14.988 + * that this guarantees that the return value will be >= 0 if
14.989 + * and only if the key is found.
14.990 + */
14.991 + public static int binarySearch(short[] a, short key) {
14.992 + return binarySearch0(a, 0, a.length, key);
14.993 + }
14.994 +
14.995 + /**
14.996 + * Searches a range of
14.997 + * the specified array of shorts for the specified value using
14.998 + * the binary search algorithm.
14.999 + * The range must be sorted
14.1000 + * (as by the {@link #sort(short[], int, int)} method)
14.1001 + * prior to making this call. If
14.1002 + * it is not sorted, the results are undefined. If the range contains
14.1003 + * multiple elements with the specified value, there is no guarantee which
14.1004 + * one will be found.
14.1005 + *
14.1006 + * @param a the array to be searched
14.1007 + * @param fromIndex the index of the first element (inclusive) to be
14.1008 + * searched
14.1009 + * @param toIndex the index of the last element (exclusive) to be searched
14.1010 + * @param key the value to be searched for
14.1011 + * @return index of the search key, if it is contained in the array
14.1012 + * within the specified range;
14.1013 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1014 + * <i>insertion point</i> is defined as the point at which the
14.1015 + * key would be inserted into the array: the index of the first
14.1016 + * element in the range greater than the key,
14.1017 + * or <tt>toIndex</tt> if all
14.1018 + * elements in the range are less than the specified key. Note
14.1019 + * that this guarantees that the return value will be >= 0 if
14.1020 + * and only if the key is found.
14.1021 + * @throws IllegalArgumentException
14.1022 + * if {@code fromIndex > toIndex}
14.1023 + * @throws ArrayIndexOutOfBoundsException
14.1024 + * if {@code fromIndex < 0 or toIndex > a.length}
14.1025 + * @since 1.6
14.1026 + */
14.1027 + public static int binarySearch(short[] a, int fromIndex, int toIndex,
14.1028 + short key) {
14.1029 + rangeCheck(a.length, fromIndex, toIndex);
14.1030 + return binarySearch0(a, fromIndex, toIndex, key);
14.1031 + }
14.1032 +
14.1033 + // Like public version, but without range checks.
14.1034 + private static int binarySearch0(short[] a, int fromIndex, int toIndex,
14.1035 + short key) {
14.1036 + int low = fromIndex;
14.1037 + int high = toIndex - 1;
14.1038 +
14.1039 + while (low <= high) {
14.1040 + int mid = (low + high) >>> 1;
14.1041 + short midVal = a[mid];
14.1042 +
14.1043 + if (midVal < key)
14.1044 + low = mid + 1;
14.1045 + else if (midVal > key)
14.1046 + high = mid - 1;
14.1047 + else
14.1048 + return mid; // key found
14.1049 + }
14.1050 + return -(low + 1); // key not found.
14.1051 + }
14.1052 +
14.1053 + /**
14.1054 + * Searches the specified array of chars for the specified value using the
14.1055 + * binary search algorithm. The array must be sorted (as
14.1056 + * by the {@link #sort(char[])} method) prior to making this call. If it
14.1057 + * is not sorted, the results are undefined. If the array contains
14.1058 + * multiple elements with the specified value, there is no guarantee which
14.1059 + * one will be found.
14.1060 + *
14.1061 + * @param a the array to be searched
14.1062 + * @param key the value to be searched for
14.1063 + * @return index of the search key, if it is contained in the array;
14.1064 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1065 + * <i>insertion point</i> is defined as the point at which the
14.1066 + * key would be inserted into the array: the index of the first
14.1067 + * element greater than the key, or <tt>a.length</tt> if all
14.1068 + * elements in the array are less than the specified key. Note
14.1069 + * that this guarantees that the return value will be >= 0 if
14.1070 + * and only if the key is found.
14.1071 + */
14.1072 + public static int binarySearch(char[] a, char key) {
14.1073 + return binarySearch0(a, 0, a.length, key);
14.1074 + }
14.1075 +
14.1076 + /**
14.1077 + * Searches a range of
14.1078 + * the specified array of chars for the specified value using the
14.1079 + * binary search algorithm.
14.1080 + * The range must be sorted (as
14.1081 + * by the {@link #sort(char[], int, int)} method)
14.1082 + * prior to making this call. If it
14.1083 + * is not sorted, the results are undefined. If the range contains
14.1084 + * multiple elements with the specified value, there is no guarantee which
14.1085 + * one will be found.
14.1086 + *
14.1087 + * @param a the array to be searched
14.1088 + * @param fromIndex the index of the first element (inclusive) to be
14.1089 + * searched
14.1090 + * @param toIndex the index of the last element (exclusive) to be searched
14.1091 + * @param key the value to be searched for
14.1092 + * @return index of the search key, if it is contained in the array
14.1093 + * within the specified range;
14.1094 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1095 + * <i>insertion point</i> is defined as the point at which the
14.1096 + * key would be inserted into the array: the index of the first
14.1097 + * element in the range greater than the key,
14.1098 + * or <tt>toIndex</tt> if all
14.1099 + * elements in the range are less than the specified key. Note
14.1100 + * that this guarantees that the return value will be >= 0 if
14.1101 + * and only if the key is found.
14.1102 + * @throws IllegalArgumentException
14.1103 + * if {@code fromIndex > toIndex}
14.1104 + * @throws ArrayIndexOutOfBoundsException
14.1105 + * if {@code fromIndex < 0 or toIndex > a.length}
14.1106 + * @since 1.6
14.1107 + */
14.1108 + public static int binarySearch(char[] a, int fromIndex, int toIndex,
14.1109 + char key) {
14.1110 + rangeCheck(a.length, fromIndex, toIndex);
14.1111 + return binarySearch0(a, fromIndex, toIndex, key);
14.1112 + }
14.1113 +
14.1114 + // Like public version, but without range checks.
14.1115 + private static int binarySearch0(char[] a, int fromIndex, int toIndex,
14.1116 + char key) {
14.1117 + int low = fromIndex;
14.1118 + int high = toIndex - 1;
14.1119 +
14.1120 + while (low <= high) {
14.1121 + int mid = (low + high) >>> 1;
14.1122 + char midVal = a[mid];
14.1123 +
14.1124 + if (midVal < key)
14.1125 + low = mid + 1;
14.1126 + else if (midVal > key)
14.1127 + high = mid - 1;
14.1128 + else
14.1129 + return mid; // key found
14.1130 + }
14.1131 + return -(low + 1); // key not found.
14.1132 + }
14.1133 +
14.1134 + /**
14.1135 + * Searches the specified array of bytes for the specified value using the
14.1136 + * binary search algorithm. The array must be sorted (as
14.1137 + * by the {@link #sort(byte[])} method) prior to making this call. If it
14.1138 + * is not sorted, the results are undefined. If the array contains
14.1139 + * multiple elements with the specified value, there is no guarantee which
14.1140 + * one will be found.
14.1141 + *
14.1142 + * @param a the array to be searched
14.1143 + * @param key the value to be searched for
14.1144 + * @return index of the search key, if it is contained in the array;
14.1145 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1146 + * <i>insertion point</i> is defined as the point at which the
14.1147 + * key would be inserted into the array: the index of the first
14.1148 + * element greater than the key, or <tt>a.length</tt> if all
14.1149 + * elements in the array are less than the specified key. Note
14.1150 + * that this guarantees that the return value will be >= 0 if
14.1151 + * and only if the key is found.
14.1152 + */
14.1153 + public static int binarySearch(byte[] a, byte key) {
14.1154 + return binarySearch0(a, 0, a.length, key);
14.1155 + }
14.1156 +
14.1157 + /**
14.1158 + * Searches a range of
14.1159 + * the specified array of bytes for the specified value using the
14.1160 + * binary search algorithm.
14.1161 + * The range must be sorted (as
14.1162 + * by the {@link #sort(byte[], int, int)} method)
14.1163 + * prior to making this call. If it
14.1164 + * is not sorted, the results are undefined. If the range contains
14.1165 + * multiple elements with the specified value, there is no guarantee which
14.1166 + * one will be found.
14.1167 + *
14.1168 + * @param a the array to be searched
14.1169 + * @param fromIndex the index of the first element (inclusive) to be
14.1170 + * searched
14.1171 + * @param toIndex the index of the last element (exclusive) to be searched
14.1172 + * @param key the value to be searched for
14.1173 + * @return index of the search key, if it is contained in the array
14.1174 + * within the specified range;
14.1175 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1176 + * <i>insertion point</i> is defined as the point at which the
14.1177 + * key would be inserted into the array: the index of the first
14.1178 + * element in the range greater than the key,
14.1179 + * or <tt>toIndex</tt> if all
14.1180 + * elements in the range are less than the specified key. Note
14.1181 + * that this guarantees that the return value will be >= 0 if
14.1182 + * and only if the key is found.
14.1183 + * @throws IllegalArgumentException
14.1184 + * if {@code fromIndex > toIndex}
14.1185 + * @throws ArrayIndexOutOfBoundsException
14.1186 + * if {@code fromIndex < 0 or toIndex > a.length}
14.1187 + * @since 1.6
14.1188 + */
14.1189 + public static int binarySearch(byte[] a, int fromIndex, int toIndex,
14.1190 + byte key) {
14.1191 + rangeCheck(a.length, fromIndex, toIndex);
14.1192 + return binarySearch0(a, fromIndex, toIndex, key);
14.1193 + }
14.1194 +
14.1195 + // Like public version, but without range checks.
14.1196 + private static int binarySearch0(byte[] a, int fromIndex, int toIndex,
14.1197 + byte key) {
14.1198 + int low = fromIndex;
14.1199 + int high = toIndex - 1;
14.1200 +
14.1201 + while (low <= high) {
14.1202 + int mid = (low + high) >>> 1;
14.1203 + byte midVal = a[mid];
14.1204 +
14.1205 + if (midVal < key)
14.1206 + low = mid + 1;
14.1207 + else if (midVal > key)
14.1208 + high = mid - 1;
14.1209 + else
14.1210 + return mid; // key found
14.1211 + }
14.1212 + return -(low + 1); // key not found.
14.1213 + }
14.1214 +
14.1215 + /**
14.1216 + * Searches the specified array of doubles for the specified value using
14.1217 + * the binary search algorithm. The array must be sorted
14.1218 + * (as by the {@link #sort(double[])} method) prior to making this call.
14.1219 + * If it is not sorted, the results are undefined. If the array contains
14.1220 + * multiple elements with the specified value, there is no guarantee which
14.1221 + * one will be found. This method considers all NaN values to be
14.1222 + * equivalent and equal.
14.1223 + *
14.1224 + * @param a the array to be searched
14.1225 + * @param key the value to be searched for
14.1226 + * @return index of the search key, if it is contained in the array;
14.1227 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1228 + * <i>insertion point</i> is defined as the point at which the
14.1229 + * key would be inserted into the array: the index of the first
14.1230 + * element greater than the key, or <tt>a.length</tt> if all
14.1231 + * elements in the array are less than the specified key. Note
14.1232 + * that this guarantees that the return value will be >= 0 if
14.1233 + * and only if the key is found.
14.1234 + */
14.1235 + public static int binarySearch(double[] a, double key) {
14.1236 + return binarySearch0(a, 0, a.length, key);
14.1237 + }
14.1238 +
14.1239 + /**
14.1240 + * Searches a range of
14.1241 + * the specified array of doubles for the specified value using
14.1242 + * the binary search algorithm.
14.1243 + * The range must be sorted
14.1244 + * (as by the {@link #sort(double[], int, int)} method)
14.1245 + * prior to making this call.
14.1246 + * If it is not sorted, the results are undefined. If the range contains
14.1247 + * multiple elements with the specified value, there is no guarantee which
14.1248 + * one will be found. This method considers all NaN values to be
14.1249 + * equivalent and equal.
14.1250 + *
14.1251 + * @param a the array to be searched
14.1252 + * @param fromIndex the index of the first element (inclusive) to be
14.1253 + * searched
14.1254 + * @param toIndex the index of the last element (exclusive) to be searched
14.1255 + * @param key the value to be searched for
14.1256 + * @return index of the search key, if it is contained in the array
14.1257 + * within the specified range;
14.1258 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1259 + * <i>insertion point</i> is defined as the point at which the
14.1260 + * key would be inserted into the array: the index of the first
14.1261 + * element in the range greater than the key,
14.1262 + * or <tt>toIndex</tt> if all
14.1263 + * elements in the range are less than the specified key. Note
14.1264 + * that this guarantees that the return value will be >= 0 if
14.1265 + * and only if the key is found.
14.1266 + * @throws IllegalArgumentException
14.1267 + * if {@code fromIndex > toIndex}
14.1268 + * @throws ArrayIndexOutOfBoundsException
14.1269 + * if {@code fromIndex < 0 or toIndex > a.length}
14.1270 + * @since 1.6
14.1271 + */
14.1272 + public static int binarySearch(double[] a, int fromIndex, int toIndex,
14.1273 + double key) {
14.1274 + rangeCheck(a.length, fromIndex, toIndex);
14.1275 + return binarySearch0(a, fromIndex, toIndex, key);
14.1276 + }
14.1277 +
14.1278 + // Like public version, but without range checks.
14.1279 + private static int binarySearch0(double[] a, int fromIndex, int toIndex,
14.1280 + double key) {
14.1281 + int low = fromIndex;
14.1282 + int high = toIndex - 1;
14.1283 +
14.1284 + while (low <= high) {
14.1285 + int mid = (low + high) >>> 1;
14.1286 + double midVal = a[mid];
14.1287 +
14.1288 + if (midVal < key)
14.1289 + low = mid + 1; // Neither val is NaN, thisVal is smaller
14.1290 + else if (midVal > key)
14.1291 + high = mid - 1; // Neither val is NaN, thisVal is larger
14.1292 + else {
14.1293 + long midBits = Double.doubleToLongBits(midVal);
14.1294 + long keyBits = Double.doubleToLongBits(key);
14.1295 + if (midBits == keyBits) // Values are equal
14.1296 + return mid; // Key found
14.1297 + else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)
14.1298 + low = mid + 1;
14.1299 + else // (0.0, -0.0) or (NaN, !NaN)
14.1300 + high = mid - 1;
14.1301 + }
14.1302 + }
14.1303 + return -(low + 1); // key not found.
14.1304 + }
14.1305 +
14.1306 + /**
14.1307 + * Searches the specified array of floats for the specified value using
14.1308 + * the binary search algorithm. The array must be sorted
14.1309 + * (as by the {@link #sort(float[])} method) prior to making this call. If
14.1310 + * it is not sorted, the results are undefined. If the array contains
14.1311 + * multiple elements with the specified value, there is no guarantee which
14.1312 + * one will be found. This method considers all NaN values to be
14.1313 + * equivalent and equal.
14.1314 + *
14.1315 + * @param a the array to be searched
14.1316 + * @param key the value to be searched for
14.1317 + * @return index of the search key, if it is contained in the array;
14.1318 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1319 + * <i>insertion point</i> is defined as the point at which the
14.1320 + * key would be inserted into the array: the index of the first
14.1321 + * element greater than the key, or <tt>a.length</tt> if all
14.1322 + * elements in the array are less than the specified key. Note
14.1323 + * that this guarantees that the return value will be >= 0 if
14.1324 + * and only if the key is found.
14.1325 + */
14.1326 + public static int binarySearch(float[] a, float key) {
14.1327 + return binarySearch0(a, 0, a.length, key);
14.1328 + }
14.1329 +
14.1330 + /**
14.1331 + * Searches a range of
14.1332 + * the specified array of floats for the specified value using
14.1333 + * the binary search algorithm.
14.1334 + * The range must be sorted
14.1335 + * (as by the {@link #sort(float[], int, int)} method)
14.1336 + * prior to making this call. If
14.1337 + * it is not sorted, the results are undefined. If the range contains
14.1338 + * multiple elements with the specified value, there is no guarantee which
14.1339 + * one will be found. This method considers all NaN values to be
14.1340 + * equivalent and equal.
14.1341 + *
14.1342 + * @param a the array to be searched
14.1343 + * @param fromIndex the index of the first element (inclusive) to be
14.1344 + * searched
14.1345 + * @param toIndex the index of the last element (exclusive) to be searched
14.1346 + * @param key the value to be searched for
14.1347 + * @return index of the search key, if it is contained in the array
14.1348 + * within the specified range;
14.1349 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1350 + * <i>insertion point</i> is defined as the point at which the
14.1351 + * key would be inserted into the array: the index of the first
14.1352 + * element in the range greater than the key,
14.1353 + * or <tt>toIndex</tt> if all
14.1354 + * elements in the range are less than the specified key. Note
14.1355 + * that this guarantees that the return value will be >= 0 if
14.1356 + * and only if the key is found.
14.1357 + * @throws IllegalArgumentException
14.1358 + * if {@code fromIndex > toIndex}
14.1359 + * @throws ArrayIndexOutOfBoundsException
14.1360 + * if {@code fromIndex < 0 or toIndex > a.length}
14.1361 + * @since 1.6
14.1362 + */
14.1363 + public static int binarySearch(float[] a, int fromIndex, int toIndex,
14.1364 + float key) {
14.1365 + rangeCheck(a.length, fromIndex, toIndex);
14.1366 + return binarySearch0(a, fromIndex, toIndex, key);
14.1367 + }
14.1368 +
14.1369 + // Like public version, but without range checks.
14.1370 + private static int binarySearch0(float[] a, int fromIndex, int toIndex,
14.1371 + float key) {
14.1372 + int low = fromIndex;
14.1373 + int high = toIndex - 1;
14.1374 +
14.1375 + while (low <= high) {
14.1376 + int mid = (low + high) >>> 1;
14.1377 + float midVal = a[mid];
14.1378 +
14.1379 + if (midVal < key)
14.1380 + low = mid + 1; // Neither val is NaN, thisVal is smaller
14.1381 + else if (midVal > key)
14.1382 + high = mid - 1; // Neither val is NaN, thisVal is larger
14.1383 + else {
14.1384 + int midBits = Float.floatToIntBits(midVal);
14.1385 + int keyBits = Float.floatToIntBits(key);
14.1386 + if (midBits == keyBits) // Values are equal
14.1387 + return mid; // Key found
14.1388 + else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)
14.1389 + low = mid + 1;
14.1390 + else // (0.0, -0.0) or (NaN, !NaN)
14.1391 + high = mid - 1;
14.1392 + }
14.1393 + }
14.1394 + return -(low + 1); // key not found.
14.1395 + }
14.1396 +
14.1397 + /**
14.1398 + * Searches the specified array for the specified object using the binary
14.1399 + * search algorithm. The array must be sorted into ascending order
14.1400 + * according to the
14.1401 + * {@linkplain Comparable natural ordering}
14.1402 + * of its elements (as by the
14.1403 + * {@link #sort(Object[])} method) prior to making this call.
14.1404 + * If it is not sorted, the results are undefined.
14.1405 + * (If the array contains elements that are not mutually comparable (for
14.1406 + * example, strings and integers), it <i>cannot</i> be sorted according
14.1407 + * to the natural ordering of its elements, hence results are undefined.)
14.1408 + * If the array contains multiple
14.1409 + * elements equal to the specified object, there is no guarantee which
14.1410 + * one will be found.
14.1411 + *
14.1412 + * @param a the array to be searched
14.1413 + * @param key the value to be searched for
14.1414 + * @return index of the search key, if it is contained in the array;
14.1415 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1416 + * <i>insertion point</i> is defined as the point at which the
14.1417 + * key would be inserted into the array: the index of the first
14.1418 + * element greater than the key, or <tt>a.length</tt> if all
14.1419 + * elements in the array are less than the specified key. Note
14.1420 + * that this guarantees that the return value will be >= 0 if
14.1421 + * and only if the key is found.
14.1422 + * @throws ClassCastException if the search key is not comparable to the
14.1423 + * elements of the array.
14.1424 + */
14.1425 + public static int binarySearch(Object[] a, Object key) {
14.1426 + return binarySearch0(a, 0, a.length, key);
14.1427 + }
14.1428 +
14.1429 + /**
14.1430 + * Searches a range of
14.1431 + * the specified array for the specified object using the binary
14.1432 + * search algorithm.
14.1433 + * The range must be sorted into ascending order
14.1434 + * according to the
14.1435 + * {@linkplain Comparable natural ordering}
14.1436 + * of its elements (as by the
14.1437 + * {@link #sort(Object[], int, int)} method) prior to making this
14.1438 + * call. If it is not sorted, the results are undefined.
14.1439 + * (If the range contains elements that are not mutually comparable (for
14.1440 + * example, strings and integers), it <i>cannot</i> be sorted according
14.1441 + * to the natural ordering of its elements, hence results are undefined.)
14.1442 + * If the range contains multiple
14.1443 + * elements equal to the specified object, there is no guarantee which
14.1444 + * one will be found.
14.1445 + *
14.1446 + * @param a the array to be searched
14.1447 + * @param fromIndex the index of the first element (inclusive) to be
14.1448 + * searched
14.1449 + * @param toIndex the index of the last element (exclusive) to be searched
14.1450 + * @param key the value to be searched for
14.1451 + * @return index of the search key, if it is contained in the array
14.1452 + * within the specified range;
14.1453 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1454 + * <i>insertion point</i> is defined as the point at which the
14.1455 + * key would be inserted into the array: the index of the first
14.1456 + * element in the range greater than the key,
14.1457 + * or <tt>toIndex</tt> if all
14.1458 + * elements in the range are less than the specified key. Note
14.1459 + * that this guarantees that the return value will be >= 0 if
14.1460 + * and only if the key is found.
14.1461 + * @throws ClassCastException if the search key is not comparable to the
14.1462 + * elements of the array within the specified range.
14.1463 + * @throws IllegalArgumentException
14.1464 + * if {@code fromIndex > toIndex}
14.1465 + * @throws ArrayIndexOutOfBoundsException
14.1466 + * if {@code fromIndex < 0 or toIndex > a.length}
14.1467 + * @since 1.6
14.1468 + */
14.1469 + public static int binarySearch(Object[] a, int fromIndex, int toIndex,
14.1470 + Object key) {
14.1471 + rangeCheck(a.length, fromIndex, toIndex);
14.1472 + return binarySearch0(a, fromIndex, toIndex, key);
14.1473 + }
14.1474 +
14.1475 + // Like public version, but without range checks.
14.1476 + private static int binarySearch0(Object[] a, int fromIndex, int toIndex,
14.1477 + Object key) {
14.1478 + int low = fromIndex;
14.1479 + int high = toIndex - 1;
14.1480 +
14.1481 + while (low <= high) {
14.1482 + int mid = (low + high) >>> 1;
14.1483 + Comparable midVal = (Comparable)a[mid];
14.1484 + int cmp = midVal.compareTo(key);
14.1485 +
14.1486 + if (cmp < 0)
14.1487 + low = mid + 1;
14.1488 + else if (cmp > 0)
14.1489 + high = mid - 1;
14.1490 + else
14.1491 + return mid; // key found
14.1492 + }
14.1493 + return -(low + 1); // key not found.
14.1494 + }
14.1495 +
14.1496 + /**
14.1497 + * Searches the specified array for the specified object using the binary
14.1498 + * search algorithm. The array must be sorted into ascending order
14.1499 + * according to the specified comparator (as by the
14.1500 + * {@link #sort(Object[], Comparator) sort(T[], Comparator)}
14.1501 + * method) prior to making this call. If it is
14.1502 + * not sorted, the results are undefined.
14.1503 + * If the array contains multiple
14.1504 + * elements equal to the specified object, there is no guarantee which one
14.1505 + * will be found.
14.1506 + *
14.1507 + * @param a the array to be searched
14.1508 + * @param key the value to be searched for
14.1509 + * @param c the comparator by which the array is ordered. A
14.1510 + * <tt>null</tt> value indicates that the elements'
14.1511 + * {@linkplain Comparable natural ordering} should be used.
14.1512 + * @return index of the search key, if it is contained in the array;
14.1513 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1514 + * <i>insertion point</i> is defined as the point at which the
14.1515 + * key would be inserted into the array: the index of the first
14.1516 + * element greater than the key, or <tt>a.length</tt> if all
14.1517 + * elements in the array are less than the specified key. Note
14.1518 + * that this guarantees that the return value will be >= 0 if
14.1519 + * and only if the key is found.
14.1520 + * @throws ClassCastException if the array contains elements that are not
14.1521 + * <i>mutually comparable</i> using the specified comparator,
14.1522 + * or the search key is not comparable to the
14.1523 + * elements of the array using this comparator.
14.1524 + */
14.1525 + public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c) {
14.1526 + return binarySearch0(a, 0, a.length, key, c);
14.1527 + }
14.1528 +
14.1529 + /**
14.1530 + * Searches a range of
14.1531 + * the specified array for the specified object using the binary
14.1532 + * search algorithm.
14.1533 + * The range must be sorted into ascending order
14.1534 + * according to the specified comparator (as by the
14.1535 + * {@link #sort(Object[], int, int, Comparator)
14.1536 + * sort(T[], int, int, Comparator)}
14.1537 + * method) prior to making this call.
14.1538 + * If it is not sorted, the results are undefined.
14.1539 + * If the range contains multiple elements equal to the specified object,
14.1540 + * there is no guarantee which one will be found.
14.1541 + *
14.1542 + * @param a the array to be searched
14.1543 + * @param fromIndex the index of the first element (inclusive) to be
14.1544 + * searched
14.1545 + * @param toIndex the index of the last element (exclusive) to be searched
14.1546 + * @param key the value to be searched for
14.1547 + * @param c the comparator by which the array is ordered. A
14.1548 + * <tt>null</tt> value indicates that the elements'
14.1549 + * {@linkplain Comparable natural ordering} should be used.
14.1550 + * @return index of the search key, if it is contained in the array
14.1551 + * within the specified range;
14.1552 + * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
14.1553 + * <i>insertion point</i> is defined as the point at which the
14.1554 + * key would be inserted into the array: the index of the first
14.1555 + * element in the range greater than the key,
14.1556 + * or <tt>toIndex</tt> if all
14.1557 + * elements in the range are less than the specified key. Note
14.1558 + * that this guarantees that the return value will be >= 0 if
14.1559 + * and only if the key is found.
14.1560 + * @throws ClassCastException if the range contains elements that are not
14.1561 + * <i>mutually comparable</i> using the specified comparator,
14.1562 + * or the search key is not comparable to the
14.1563 + * elements in the range using this comparator.
14.1564 + * @throws IllegalArgumentException
14.1565 + * if {@code fromIndex > toIndex}
14.1566 + * @throws ArrayIndexOutOfBoundsException
14.1567 + * if {@code fromIndex < 0 or toIndex > a.length}
14.1568 + * @since 1.6
14.1569 + */
14.1570 + public static <T> int binarySearch(T[] a, int fromIndex, int toIndex,
14.1571 + T key, Comparator<? super T> c) {
14.1572 + rangeCheck(a.length, fromIndex, toIndex);
14.1573 + return binarySearch0(a, fromIndex, toIndex, key, c);
14.1574 + }
14.1575 +
14.1576 + // Like public version, but without range checks.
14.1577 + private static <T> int binarySearch0(T[] a, int fromIndex, int toIndex,
14.1578 + T key, Comparator<? super T> c) {
14.1579 + if (c == null) {
14.1580 + return binarySearch0(a, fromIndex, toIndex, key);
14.1581 + }
14.1582 + int low = fromIndex;
14.1583 + int high = toIndex - 1;
14.1584 +
14.1585 + while (low <= high) {
14.1586 + int mid = (low + high) >>> 1;
14.1587 + T midVal = a[mid];
14.1588 + int cmp = c.compare(midVal, key);
14.1589 + if (cmp < 0)
14.1590 + low = mid + 1;
14.1591 + else if (cmp > 0)
14.1592 + high = mid - 1;
14.1593 + else
14.1594 + return mid; // key found
14.1595 + }
14.1596 + return -(low + 1); // key not found.
14.1597 + }
14.1598 +
14.1599 + // Equality Testing
14.1600 +
14.1601 + /**
14.1602 + * Returns <tt>true</tt> if the two specified arrays of longs are
14.1603 + * <i>equal</i> to one another. Two arrays are considered equal if both
14.1604 + * arrays contain the same number of elements, and all corresponding pairs
14.1605 + * of elements in the two arrays are equal. In other words, two arrays
14.1606 + * are equal if they contain the same elements in the same order. Also,
14.1607 + * two array references are considered equal if both are <tt>null</tt>.<p>
14.1608 + *
14.1609 + * @param a one array to be tested for equality
14.1610 + * @param a2 the other array to be tested for equality
14.1611 + * @return <tt>true</tt> if the two arrays are equal
14.1612 + */
14.1613 + public static boolean equals(long[] a, long[] a2) {
14.1614 + if (a==a2)
14.1615 + return true;
14.1616 + if (a==null || a2==null)
14.1617 + return false;
14.1618 +
14.1619 + int length = a.length;
14.1620 + if (a2.length != length)
14.1621 + return false;
14.1622 +
14.1623 + for (int i=0; i<length; i++)
14.1624 + if (a[i] != a2[i])
14.1625 + return false;
14.1626 +
14.1627 + return true;
14.1628 + }
14.1629 +
14.1630 + /**
14.1631 + * Returns <tt>true</tt> if the two specified arrays of ints are
14.1632 + * <i>equal</i> to one another. Two arrays are considered equal if both
14.1633 + * arrays contain the same number of elements, and all corresponding pairs
14.1634 + * of elements in the two arrays are equal. In other words, two arrays
14.1635 + * are equal if they contain the same elements in the same order. Also,
14.1636 + * two array references are considered equal if both are <tt>null</tt>.<p>
14.1637 + *
14.1638 + * @param a one array to be tested for equality
14.1639 + * @param a2 the other array to be tested for equality
14.1640 + * @return <tt>true</tt> if the two arrays are equal
14.1641 + */
14.1642 + public static boolean equals(int[] a, int[] a2) {
14.1643 + if (a==a2)
14.1644 + return true;
14.1645 + if (a==null || a2==null)
14.1646 + return false;
14.1647 +
14.1648 + int length = a.length;
14.1649 + if (a2.length != length)
14.1650 + return false;
14.1651 +
14.1652 + for (int i=0; i<length; i++)
14.1653 + if (a[i] != a2[i])
14.1654 + return false;
14.1655 +
14.1656 + return true;
14.1657 + }
14.1658 +
14.1659 + /**
14.1660 + * Returns <tt>true</tt> if the two specified arrays of shorts are
14.1661 + * <i>equal</i> to one another. Two arrays are considered equal if both
14.1662 + * arrays contain the same number of elements, and all corresponding pairs
14.1663 + * of elements in the two arrays are equal. In other words, two arrays
14.1664 + * are equal if they contain the same elements in the same order. Also,
14.1665 + * two array references are considered equal if both are <tt>null</tt>.<p>
14.1666 + *
14.1667 + * @param a one array to be tested for equality
14.1668 + * @param a2 the other array to be tested for equality
14.1669 + * @return <tt>true</tt> if the two arrays are equal
14.1670 + */
14.1671 + public static boolean equals(short[] a, short a2[]) {
14.1672 + if (a==a2)
14.1673 + return true;
14.1674 + if (a==null || a2==null)
14.1675 + return false;
14.1676 +
14.1677 + int length = a.length;
14.1678 + if (a2.length != length)
14.1679 + return false;
14.1680 +
14.1681 + for (int i=0; i<length; i++)
14.1682 + if (a[i] != a2[i])
14.1683 + return false;
14.1684 +
14.1685 + return true;
14.1686 + }
14.1687 +
14.1688 + /**
14.1689 + * Returns <tt>true</tt> if the two specified arrays of chars are
14.1690 + * <i>equal</i> to one another. Two arrays are considered equal if both
14.1691 + * arrays contain the same number of elements, and all corresponding pairs
14.1692 + * of elements in the two arrays are equal. In other words, two arrays
14.1693 + * are equal if they contain the same elements in the same order. Also,
14.1694 + * two array references are considered equal if both are <tt>null</tt>.<p>
14.1695 + *
14.1696 + * @param a one array to be tested for equality
14.1697 + * @param a2 the other array to be tested for equality
14.1698 + * @return <tt>true</tt> if the two arrays are equal
14.1699 + */
14.1700 + public static boolean equals(char[] a, char[] a2) {
14.1701 + if (a==a2)
14.1702 + return true;
14.1703 + if (a==null || a2==null)
14.1704 + return false;
14.1705 +
14.1706 + int length = a.length;
14.1707 + if (a2.length != length)
14.1708 + return false;
14.1709 +
14.1710 + for (int i=0; i<length; i++)
14.1711 + if (a[i] != a2[i])
14.1712 + return false;
14.1713 +
14.1714 + return true;
14.1715 + }
14.1716 +
14.1717 + /**
14.1718 + * Returns <tt>true</tt> if the two specified arrays of bytes are
14.1719 + * <i>equal</i> to one another. Two arrays are considered equal if both
14.1720 + * arrays contain the same number of elements, and all corresponding pairs
14.1721 + * of elements in the two arrays are equal. In other words, two arrays
14.1722 + * are equal if they contain the same elements in the same order. Also,
14.1723 + * two array references are considered equal if both are <tt>null</tt>.<p>
14.1724 + *
14.1725 + * @param a one array to be tested for equality
14.1726 + * @param a2 the other array to be tested for equality
14.1727 + * @return <tt>true</tt> if the two arrays are equal
14.1728 + */
14.1729 + public static boolean equals(byte[] a, byte[] a2) {
14.1730 + if (a==a2)
14.1731 + return true;
14.1732 + if (a==null || a2==null)
14.1733 + return false;
14.1734 +
14.1735 + int length = a.length;
14.1736 + if (a2.length != length)
14.1737 + return false;
14.1738 +
14.1739 + for (int i=0; i<length; i++)
14.1740 + if (a[i] != a2[i])
14.1741 + return false;
14.1742 +
14.1743 + return true;
14.1744 + }
14.1745 +
14.1746 + /**
14.1747 + * Returns <tt>true</tt> if the two specified arrays of booleans are
14.1748 + * <i>equal</i> to one another. Two arrays are considered equal if both
14.1749 + * arrays contain the same number of elements, and all corresponding pairs
14.1750 + * of elements in the two arrays are equal. In other words, two arrays
14.1751 + * are equal if they contain the same elements in the same order. Also,
14.1752 + * two array references are considered equal if both are <tt>null</tt>.<p>
14.1753 + *
14.1754 + * @param a one array to be tested for equality
14.1755 + * @param a2 the other array to be tested for equality
14.1756 + * @return <tt>true</tt> if the two arrays are equal
14.1757 + */
14.1758 + public static boolean equals(boolean[] a, boolean[] a2) {
14.1759 + if (a==a2)
14.1760 + return true;
14.1761 + if (a==null || a2==null)
14.1762 + return false;
14.1763 +
14.1764 + int length = a.length;
14.1765 + if (a2.length != length)
14.1766 + return false;
14.1767 +
14.1768 + for (int i=0; i<length; i++)
14.1769 + if (a[i] != a2[i])
14.1770 + return false;
14.1771 +
14.1772 + return true;
14.1773 + }
14.1774 +
14.1775 + /**
14.1776 + * Returns <tt>true</tt> if the two specified arrays of doubles are
14.1777 + * <i>equal</i> to one another. Two arrays are considered equal if both
14.1778 + * arrays contain the same number of elements, and all corresponding pairs
14.1779 + * of elements in the two arrays are equal. In other words, two arrays
14.1780 + * are equal if they contain the same elements in the same order. Also,
14.1781 + * two array references are considered equal if both are <tt>null</tt>.<p>
14.1782 + *
14.1783 + * Two doubles <tt>d1</tt> and <tt>d2</tt> are considered equal if:
14.1784 + * <pre> <tt>new Double(d1).equals(new Double(d2))</tt></pre>
14.1785 + * (Unlike the <tt>==</tt> operator, this method considers
14.1786 + * <tt>NaN</tt> equals to itself, and 0.0d unequal to -0.0d.)
14.1787 + *
14.1788 + * @param a one array to be tested for equality
14.1789 + * @param a2 the other array to be tested for equality
14.1790 + * @return <tt>true</tt> if the two arrays are equal
14.1791 + * @see Double#equals(Object)
14.1792 + */
14.1793 + public static boolean equals(double[] a, double[] a2) {
14.1794 + if (a==a2)
14.1795 + return true;
14.1796 + if (a==null || a2==null)
14.1797 + return false;
14.1798 +
14.1799 + int length = a.length;
14.1800 + if (a2.length != length)
14.1801 + return false;
14.1802 +
14.1803 + for (int i=0; i<length; i++)
14.1804 + if (Double.doubleToLongBits(a[i])!=Double.doubleToLongBits(a2[i]))
14.1805 + return false;
14.1806 +
14.1807 + return true;
14.1808 + }
14.1809 +
14.1810 + /**
14.1811 + * Returns <tt>true</tt> if the two specified arrays of floats are
14.1812 + * <i>equal</i> to one another. Two arrays are considered equal if both
14.1813 + * arrays contain the same number of elements, and all corresponding pairs
14.1814 + * of elements in the two arrays are equal. In other words, two arrays
14.1815 + * are equal if they contain the same elements in the same order. Also,
14.1816 + * two array references are considered equal if both are <tt>null</tt>.<p>
14.1817 + *
14.1818 + * Two floats <tt>f1</tt> and <tt>f2</tt> are considered equal if:
14.1819 + * <pre> <tt>new Float(f1).equals(new Float(f2))</tt></pre>
14.1820 + * (Unlike the <tt>==</tt> operator, this method considers
14.1821 + * <tt>NaN</tt> equals to itself, and 0.0f unequal to -0.0f.)
14.1822 + *
14.1823 + * @param a one array to be tested for equality
14.1824 + * @param a2 the other array to be tested for equality
14.1825 + * @return <tt>true</tt> if the two arrays are equal
14.1826 + * @see Float#equals(Object)
14.1827 + */
14.1828 + public static boolean equals(float[] a, float[] a2) {
14.1829 + if (a==a2)
14.1830 + return true;
14.1831 + if (a==null || a2==null)
14.1832 + return false;
14.1833 +
14.1834 + int length = a.length;
14.1835 + if (a2.length != length)
14.1836 + return false;
14.1837 +
14.1838 + for (int i=0; i<length; i++)
14.1839 + if (Float.floatToIntBits(a[i])!=Float.floatToIntBits(a2[i]))
14.1840 + return false;
14.1841 +
14.1842 + return true;
14.1843 + }
14.1844 +
14.1845 + /**
14.1846 + * Returns <tt>true</tt> if the two specified arrays of Objects are
14.1847 + * <i>equal</i> to one another. The two arrays are considered equal if
14.1848 + * both arrays contain the same number of elements, and all corresponding
14.1849 + * pairs of elements in the two arrays are equal. Two objects <tt>e1</tt>
14.1850 + * and <tt>e2</tt> are considered <i>equal</i> if <tt>(e1==null ? e2==null
14.1851 + * : e1.equals(e2))</tt>. In other words, the two arrays are equal if
14.1852 + * they contain the same elements in the same order. Also, two array
14.1853 + * references are considered equal if both are <tt>null</tt>.<p>
14.1854 + *
14.1855 + * @param a one array to be tested for equality
14.1856 + * @param a2 the other array to be tested for equality
14.1857 + * @return <tt>true</tt> if the two arrays are equal
14.1858 + */
14.1859 + public static boolean equals(Object[] a, Object[] a2) {
14.1860 + if (a==a2)
14.1861 + return true;
14.1862 + if (a==null || a2==null)
14.1863 + return false;
14.1864 +
14.1865 + int length = a.length;
14.1866 + if (a2.length != length)
14.1867 + return false;
14.1868 +
14.1869 + for (int i=0; i<length; i++) {
14.1870 + Object o1 = a[i];
14.1871 + Object o2 = a2[i];
14.1872 + if (!(o1==null ? o2==null : o1.equals(o2)))
14.1873 + return false;
14.1874 + }
14.1875 +
14.1876 + return true;
14.1877 + }
14.1878 +
14.1879 + // Filling
14.1880 +
14.1881 + /**
14.1882 + * Assigns the specified long value to each element of the specified array
14.1883 + * of longs.
14.1884 + *
14.1885 + * @param a the array to be filled
14.1886 + * @param val the value to be stored in all elements of the array
14.1887 + */
14.1888 + public static void fill(long[] a, long val) {
14.1889 + for (int i = 0, len = a.length; i < len; i++)
14.1890 + a[i] = val;
14.1891 + }
14.1892 +
14.1893 + /**
14.1894 + * Assigns the specified long value to each element of the specified
14.1895 + * range of the specified array of longs. The range to be filled
14.1896 + * extends from index <tt>fromIndex</tt>, inclusive, to index
14.1897 + * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
14.1898 + * range to be filled is empty.)
14.1899 + *
14.1900 + * @param a the array to be filled
14.1901 + * @param fromIndex the index of the first element (inclusive) to be
14.1902 + * filled with the specified value
14.1903 + * @param toIndex the index of the last element (exclusive) to be
14.1904 + * filled with the specified value
14.1905 + * @param val the value to be stored in all elements of the array
14.1906 + * @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
14.1907 + * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
14.1908 + * <tt>toIndex > a.length</tt>
14.1909 + */
14.1910 + public static void fill(long[] a, int fromIndex, int toIndex, long val) {
14.1911 + rangeCheck(a.length, fromIndex, toIndex);
14.1912 + for (int i = fromIndex; i < toIndex; i++)
14.1913 + a[i] = val;
14.1914 + }
14.1915 +
14.1916 + /**
14.1917 + * Assigns the specified int value to each element of the specified array
14.1918 + * of ints.
14.1919 + *
14.1920 + * @param a the array to be filled
14.1921 + * @param val the value to be stored in all elements of the array
14.1922 + */
14.1923 + public static void fill(int[] a, int val) {
14.1924 + for (int i = 0, len = a.length; i < len; i++)
14.1925 + a[i] = val;
14.1926 + }
14.1927 +
14.1928 + /**
14.1929 + * Assigns the specified int value to each element of the specified
14.1930 + * range of the specified array of ints. The range to be filled
14.1931 + * extends from index <tt>fromIndex</tt>, inclusive, to index
14.1932 + * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
14.1933 + * range to be filled is empty.)
14.1934 + *
14.1935 + * @param a the array to be filled
14.1936 + * @param fromIndex the index of the first element (inclusive) to be
14.1937 + * filled with the specified value
14.1938 + * @param toIndex the index of the last element (exclusive) to be
14.1939 + * filled with the specified value
14.1940 + * @param val the value to be stored in all elements of the array
14.1941 + * @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
14.1942 + * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
14.1943 + * <tt>toIndex > a.length</tt>
14.1944 + */
14.1945 + public static void fill(int[] a, int fromIndex, int toIndex, int val) {
14.1946 + rangeCheck(a.length, fromIndex, toIndex);
14.1947 + for (int i = fromIndex; i < toIndex; i++)
14.1948 + a[i] = val;
14.1949 + }
14.1950 +
14.1951 + /**
14.1952 + * Assigns the specified short value to each element of the specified array
14.1953 + * of shorts.
14.1954 + *
14.1955 + * @param a the array to be filled
14.1956 + * @param val the value to be stored in all elements of the array
14.1957 + */
14.1958 + public static void fill(short[] a, short val) {
14.1959 + for (int i = 0, len = a.length; i < len; i++)
14.1960 + a[i] = val;
14.1961 + }
14.1962 +
14.1963 + /**
14.1964 + * Assigns the specified short value to each element of the specified
14.1965 + * range of the specified array of shorts. The range to be filled
14.1966 + * extends from index <tt>fromIndex</tt>, inclusive, to index
14.1967 + * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
14.1968 + * range to be filled is empty.)
14.1969 + *
14.1970 + * @param a the array to be filled
14.1971 + * @param fromIndex the index of the first element (inclusive) to be
14.1972 + * filled with the specified value
14.1973 + * @param toIndex the index of the last element (exclusive) to be
14.1974 + * filled with the specified value
14.1975 + * @param val the value to be stored in all elements of the array
14.1976 + * @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
14.1977 + * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
14.1978 + * <tt>toIndex > a.length</tt>
14.1979 + */
14.1980 + public static void fill(short[] a, int fromIndex, int toIndex, short val) {
14.1981 + rangeCheck(a.length, fromIndex, toIndex);
14.1982 + for (int i = fromIndex; i < toIndex; i++)
14.1983 + a[i] = val;
14.1984 + }
14.1985 +
14.1986 + /**
14.1987 + * Assigns the specified char value to each element of the specified array
14.1988 + * of chars.
14.1989 + *
14.1990 + * @param a the array to be filled
14.1991 + * @param val the value to be stored in all elements of the array
14.1992 + */
14.1993 + public static void fill(char[] a, char val) {
14.1994 + for (int i = 0, len = a.length; i < len; i++)
14.1995 + a[i] = val;
14.1996 + }
14.1997 +
14.1998 + /**
14.1999 + * Assigns the specified char value to each element of the specified
14.2000 + * range of the specified array of chars. The range to be filled
14.2001 + * extends from index <tt>fromIndex</tt>, inclusive, to index
14.2002 + * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
14.2003 + * range to be filled is empty.)
14.2004 + *
14.2005 + * @param a the array to be filled
14.2006 + * @param fromIndex the index of the first element (inclusive) to be
14.2007 + * filled with the specified value
14.2008 + * @param toIndex the index of the last element (exclusive) to be
14.2009 + * filled with the specified value
14.2010 + * @param val the value to be stored in all elements of the array
14.2011 + * @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
14.2012 + * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
14.2013 + * <tt>toIndex > a.length</tt>
14.2014 + */
14.2015 + public static void fill(char[] a, int fromIndex, int toIndex, char val) {
14.2016 + rangeCheck(a.length, fromIndex, toIndex);
14.2017 + for (int i = fromIndex; i < toIndex; i++)
14.2018 + a[i] = val;
14.2019 + }
14.2020 +
14.2021 + /**
14.2022 + * Assigns the specified byte value to each element of the specified array
14.2023 + * of bytes.
14.2024 + *
14.2025 + * @param a the array to be filled
14.2026 + * @param val the value to be stored in all elements of the array
14.2027 + */
14.2028 + public static void fill(byte[] a, byte val) {
14.2029 + for (int i = 0, len = a.length; i < len; i++)
14.2030 + a[i] = val;
14.2031 + }
14.2032 +
14.2033 + /**
14.2034 + * Assigns the specified byte value to each element of the specified
14.2035 + * range of the specified array of bytes. The range to be filled
14.2036 + * extends from index <tt>fromIndex</tt>, inclusive, to index
14.2037 + * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
14.2038 + * range to be filled is empty.)
14.2039 + *
14.2040 + * @param a the array to be filled
14.2041 + * @param fromIndex the index of the first element (inclusive) to be
14.2042 + * filled with the specified value
14.2043 + * @param toIndex the index of the last element (exclusive) to be
14.2044 + * filled with the specified value
14.2045 + * @param val the value to be stored in all elements of the array
14.2046 + * @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
14.2047 + * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
14.2048 + * <tt>toIndex > a.length</tt>
14.2049 + */
14.2050 + public static void fill(byte[] a, int fromIndex, int toIndex, byte val) {
14.2051 + rangeCheck(a.length, fromIndex, toIndex);
14.2052 + for (int i = fromIndex; i < toIndex; i++)
14.2053 + a[i] = val;
14.2054 + }
14.2055 +
14.2056 + /**
14.2057 + * Assigns the specified boolean value to each element of the specified
14.2058 + * array of booleans.
14.2059 + *
14.2060 + * @param a the array to be filled
14.2061 + * @param val the value to be stored in all elements of the array
14.2062 + */
14.2063 + public static void fill(boolean[] a, boolean val) {
14.2064 + for (int i = 0, len = a.length; i < len; i++)
14.2065 + a[i] = val;
14.2066 + }
14.2067 +
14.2068 + /**
14.2069 + * Assigns the specified boolean value to each element of the specified
14.2070 + * range of the specified array of booleans. The range to be filled
14.2071 + * extends from index <tt>fromIndex</tt>, inclusive, to index
14.2072 + * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
14.2073 + * range to be filled is empty.)
14.2074 + *
14.2075 + * @param a the array to be filled
14.2076 + * @param fromIndex the index of the first element (inclusive) to be
14.2077 + * filled with the specified value
14.2078 + * @param toIndex the index of the last element (exclusive) to be
14.2079 + * filled with the specified value
14.2080 + * @param val the value to be stored in all elements of the array
14.2081 + * @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
14.2082 + * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
14.2083 + * <tt>toIndex > a.length</tt>
14.2084 + */
14.2085 + public static void fill(boolean[] a, int fromIndex, int toIndex,
14.2086 + boolean val) {
14.2087 + rangeCheck(a.length, fromIndex, toIndex);
14.2088 + for (int i = fromIndex; i < toIndex; i++)
14.2089 + a[i] = val;
14.2090 + }
14.2091 +
14.2092 + /**
14.2093 + * Assigns the specified double value to each element of the specified
14.2094 + * array of doubles.
14.2095 + *
14.2096 + * @param a the array to be filled
14.2097 + * @param val the value to be stored in all elements of the array
14.2098 + */
14.2099 + public static void fill(double[] a, double val) {
14.2100 + for (int i = 0, len = a.length; i < len; i++)
14.2101 + a[i] = val;
14.2102 + }
14.2103 +
14.2104 + /**
14.2105 + * Assigns the specified double value to each element of the specified
14.2106 + * range of the specified array of doubles. The range to be filled
14.2107 + * extends from index <tt>fromIndex</tt>, inclusive, to index
14.2108 + * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
14.2109 + * range to be filled is empty.)
14.2110 + *
14.2111 + * @param a the array to be filled
14.2112 + * @param fromIndex the index of the first element (inclusive) to be
14.2113 + * filled with the specified value
14.2114 + * @param toIndex the index of the last element (exclusive) to be
14.2115 + * filled with the specified value
14.2116 + * @param val the value to be stored in all elements of the array
14.2117 + * @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
14.2118 + * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
14.2119 + * <tt>toIndex > a.length</tt>
14.2120 + */
14.2121 + public static void fill(double[] a, int fromIndex, int toIndex,double val){
14.2122 + rangeCheck(a.length, fromIndex, toIndex);
14.2123 + for (int i = fromIndex; i < toIndex; i++)
14.2124 + a[i] = val;
14.2125 + }
14.2126 +
14.2127 + /**
14.2128 + * Assigns the specified float value to each element of the specified array
14.2129 + * of floats.
14.2130 + *
14.2131 + * @param a the array to be filled
14.2132 + * @param val the value to be stored in all elements of the array
14.2133 + */
14.2134 + public static void fill(float[] a, float val) {
14.2135 + for (int i = 0, len = a.length; i < len; i++)
14.2136 + a[i] = val;
14.2137 + }
14.2138 +
14.2139 + /**
14.2140 + * Assigns the specified float value to each element of the specified
14.2141 + * range of the specified array of floats. The range to be filled
14.2142 + * extends from index <tt>fromIndex</tt>, inclusive, to index
14.2143 + * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
14.2144 + * range to be filled is empty.)
14.2145 + *
14.2146 + * @param a the array to be filled
14.2147 + * @param fromIndex the index of the first element (inclusive) to be
14.2148 + * filled with the specified value
14.2149 + * @param toIndex the index of the last element (exclusive) to be
14.2150 + * filled with the specified value
14.2151 + * @param val the value to be stored in all elements of the array
14.2152 + * @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
14.2153 + * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
14.2154 + * <tt>toIndex > a.length</tt>
14.2155 + */
14.2156 + public static void fill(float[] a, int fromIndex, int toIndex, float val) {
14.2157 + rangeCheck(a.length, fromIndex, toIndex);
14.2158 + for (int i = fromIndex; i < toIndex; i++)
14.2159 + a[i] = val;
14.2160 + }
14.2161 +
14.2162 + /**
14.2163 + * Assigns the specified Object reference to each element of the specified
14.2164 + * array of Objects.
14.2165 + *
14.2166 + * @param a the array to be filled
14.2167 + * @param val the value to be stored in all elements of the array
14.2168 + * @throws ArrayStoreException if the specified value is not of a
14.2169 + * runtime type that can be stored in the specified array
14.2170 + */
14.2171 + public static void fill(Object[] a, Object val) {
14.2172 + for (int i = 0, len = a.length; i < len; i++)
14.2173 + a[i] = val;
14.2174 + }
14.2175 +
14.2176 + /**
14.2177 + * Assigns the specified Object reference to each element of the specified
14.2178 + * range of the specified array of Objects. The range to be filled
14.2179 + * extends from index <tt>fromIndex</tt>, inclusive, to index
14.2180 + * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
14.2181 + * range to be filled is empty.)
14.2182 + *
14.2183 + * @param a the array to be filled
14.2184 + * @param fromIndex the index of the first element (inclusive) to be
14.2185 + * filled with the specified value
14.2186 + * @param toIndex the index of the last element (exclusive) to be
14.2187 + * filled with the specified value
14.2188 + * @param val the value to be stored in all elements of the array
14.2189 + * @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
14.2190 + * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
14.2191 + * <tt>toIndex > a.length</tt>
14.2192 + * @throws ArrayStoreException if the specified value is not of a
14.2193 + * runtime type that can be stored in the specified array
14.2194 + */
14.2195 + public static void fill(Object[] a, int fromIndex, int toIndex, Object val) {
14.2196 + rangeCheck(a.length, fromIndex, toIndex);
14.2197 + for (int i = fromIndex; i < toIndex; i++)
14.2198 + a[i] = val;
14.2199 + }
14.2200 +
14.2201 + // Cloning
14.2202 +
14.2203 + /**
14.2204 + * Copies the specified array, truncating or padding with nulls (if necessary)
14.2205 + * so the copy has the specified length. For all indices that are
14.2206 + * valid in both the original array and the copy, the two arrays will
14.2207 + * contain identical values. For any indices that are valid in the
14.2208 + * copy but not the original, the copy will contain <tt>null</tt>.
14.2209 + * Such indices will exist if and only if the specified length
14.2210 + * is greater than that of the original array.
14.2211 + * The resulting array is of exactly the same class as the original array.
14.2212 + *
14.2213 + * @param original the array to be copied
14.2214 + * @param newLength the length of the copy to be returned
14.2215 + * @return a copy of the original array, truncated or padded with nulls
14.2216 + * to obtain the specified length
14.2217 + * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
14.2218 + * @throws NullPointerException if <tt>original</tt> is null
14.2219 + * @since 1.6
14.2220 + */
14.2221 + public static <T> T[] copyOf(T[] original, int newLength) {
14.2222 + return (T[]) copyOf(original, newLength, original.getClass());
14.2223 + }
14.2224 +
14.2225 + /**
14.2226 + * Copies the specified array, truncating or padding with nulls (if necessary)
14.2227 + * so the copy has the specified length. For all indices that are
14.2228 + * valid in both the original array and the copy, the two arrays will
14.2229 + * contain identical values. For any indices that are valid in the
14.2230 + * copy but not the original, the copy will contain <tt>null</tt>.
14.2231 + * Such indices will exist if and only if the specified length
14.2232 + * is greater than that of the original array.
14.2233 + * The resulting array is of the class <tt>newType</tt>.
14.2234 + *
14.2235 + * @param original the array to be copied
14.2236 + * @param newLength the length of the copy to be returned
14.2237 + * @param newType the class of the copy to be returned
14.2238 + * @return a copy of the original array, truncated or padded with nulls
14.2239 + * to obtain the specified length
14.2240 + * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
14.2241 + * @throws NullPointerException if <tt>original</tt> is null
14.2242 + * @throws ArrayStoreException if an element copied from
14.2243 + * <tt>original</tt> is not of a runtime type that can be stored in
14.2244 + * an array of class <tt>newType</tt>
14.2245 + * @since 1.6
14.2246 + */
14.2247 + public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
14.2248 + T[] copy = ((Object)newType == (Object)Object[].class)
14.2249 + ? (T[]) new Object[newLength]
14.2250 + : (T[]) Array.newInstance(newType.getComponentType(), newLength);
14.2251 + System.arraycopy(original, 0, copy, 0,
14.2252 + Math.min(original.length, newLength));
14.2253 + return copy;
14.2254 + }
14.2255 +
14.2256 + /**
14.2257 + * Copies the specified array, truncating or padding with zeros (if necessary)
14.2258 + * so the copy has the specified length. For all indices that are
14.2259 + * valid in both the original array and the copy, the two arrays will
14.2260 + * contain identical values. For any indices that are valid in the
14.2261 + * copy but not the original, the copy will contain <tt>(byte)0</tt>.
14.2262 + * Such indices will exist if and only if the specified length
14.2263 + * is greater than that of the original array.
14.2264 + *
14.2265 + * @param original the array to be copied
14.2266 + * @param newLength the length of the copy to be returned
14.2267 + * @return a copy of the original array, truncated or padded with zeros
14.2268 + * to obtain the specified length
14.2269 + * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
14.2270 + * @throws NullPointerException if <tt>original</tt> is null
14.2271 + * @since 1.6
14.2272 + */
14.2273 + public static byte[] copyOf(byte[] original, int newLength) {
14.2274 + byte[] copy = new byte[newLength];
14.2275 + System.arraycopy(original, 0, copy, 0,
14.2276 + Math.min(original.length, newLength));
14.2277 + return copy;
14.2278 + }
14.2279 +
14.2280 + /**
14.2281 + * Copies the specified array, truncating or padding with zeros (if necessary)
14.2282 + * so the copy has the specified length. For all indices that are
14.2283 + * valid in both the original array and the copy, the two arrays will
14.2284 + * contain identical values. For any indices that are valid in the
14.2285 + * copy but not the original, the copy will contain <tt>(short)0</tt>.
14.2286 + * Such indices will exist if and only if the specified length
14.2287 + * is greater than that of the original array.
14.2288 + *
14.2289 + * @param original the array to be copied
14.2290 + * @param newLength the length of the copy to be returned
14.2291 + * @return a copy of the original array, truncated or padded with zeros
14.2292 + * to obtain the specified length
14.2293 + * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
14.2294 + * @throws NullPointerException if <tt>original</tt> is null
14.2295 + * @since 1.6
14.2296 + */
14.2297 + public static short[] copyOf(short[] original, int newLength) {
14.2298 + short[] copy = new short[newLength];
14.2299 + System.arraycopy(original, 0, copy, 0,
14.2300 + Math.min(original.length, newLength));
14.2301 + return copy;
14.2302 + }
14.2303 +
14.2304 + /**
14.2305 + * Copies the specified array, truncating or padding with zeros (if necessary)
14.2306 + * so the copy has the specified length. For all indices that are
14.2307 + * valid in both the original array and the copy, the two arrays will
14.2308 + * contain identical values. For any indices that are valid in the
14.2309 + * copy but not the original, the copy will contain <tt>0</tt>.
14.2310 + * Such indices will exist if and only if the specified length
14.2311 + * is greater than that of the original array.
14.2312 + *
14.2313 + * @param original the array to be copied
14.2314 + * @param newLength the length of the copy to be returned
14.2315 + * @return a copy of the original array, truncated or padded with zeros
14.2316 + * to obtain the specified length
14.2317 + * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
14.2318 + * @throws NullPointerException if <tt>original</tt> is null
14.2319 + * @since 1.6
14.2320 + */
14.2321 + public static int[] copyOf(int[] original, int newLength) {
14.2322 + int[] copy = new int[newLength];
14.2323 + System.arraycopy(original, 0, copy, 0,
14.2324 + Math.min(original.length, newLength));
14.2325 + return copy;
14.2326 + }
14.2327 +
14.2328 + /**
14.2329 + * Copies the specified array, truncating or padding with zeros (if necessary)
14.2330 + * so the copy has the specified length. For all indices that are
14.2331 + * valid in both the original array and the copy, the two arrays will
14.2332 + * contain identical values. For any indices that are valid in the
14.2333 + * copy but not the original, the copy will contain <tt>0L</tt>.
14.2334 + * Such indices will exist if and only if the specified length
14.2335 + * is greater than that of the original array.
14.2336 + *
14.2337 + * @param original the array to be copied
14.2338 + * @param newLength the length of the copy to be returned
14.2339 + * @return a copy of the original array, truncated or padded with zeros
14.2340 + * to obtain the specified length
14.2341 + * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
14.2342 + * @throws NullPointerException if <tt>original</tt> is null
14.2343 + * @since 1.6
14.2344 + */
14.2345 + public static long[] copyOf(long[] original, int newLength) {
14.2346 + long[] copy = new long[newLength];
14.2347 + System.arraycopy(original, 0, copy, 0,
14.2348 + Math.min(original.length, newLength));
14.2349 + return copy;
14.2350 + }
14.2351 +
14.2352 + /**
14.2353 + * Copies the specified array, truncating or padding with null characters (if necessary)
14.2354 + * so the copy has the specified length. For all indices that are valid
14.2355 + * in both the original array and the copy, the two arrays will contain
14.2356 + * identical values. For any indices that are valid in the copy but not
14.2357 + * the original, the copy will contain <tt>'\\u000'</tt>. Such indices
14.2358 + * will exist if and only if the specified length is greater than that of
14.2359 + * the original array.
14.2360 + *
14.2361 + * @param original the array to be copied
14.2362 + * @param newLength the length of the copy to be returned
14.2363 + * @return a copy of the original array, truncated or padded with null characters
14.2364 + * to obtain the specified length
14.2365 + * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
14.2366 + * @throws NullPointerException if <tt>original</tt> is null
14.2367 + * @since 1.6
14.2368 + */
14.2369 + public static char[] copyOf(char[] original, int newLength) {
14.2370 + char[] copy = new char[newLength];
14.2371 + System.arraycopy(original, 0, copy, 0,
14.2372 + Math.min(original.length, newLength));
14.2373 + return copy;
14.2374 + }
14.2375 +
14.2376 + /**
14.2377 + * Copies the specified array, truncating or padding with zeros (if necessary)
14.2378 + * so the copy has the specified length. For all indices that are
14.2379 + * valid in both the original array and the copy, the two arrays will
14.2380 + * contain identical values. For any indices that are valid in the
14.2381 + * copy but not the original, the copy will contain <tt>0f</tt>.
14.2382 + * Such indices will exist if and only if the specified length
14.2383 + * is greater than that of the original array.
14.2384 + *
14.2385 + * @param original the array to be copied
14.2386 + * @param newLength the length of the copy to be returned
14.2387 + * @return a copy of the original array, truncated or padded with zeros
14.2388 + * to obtain the specified length
14.2389 + * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
14.2390 + * @throws NullPointerException if <tt>original</tt> is null
14.2391 + * @since 1.6
14.2392 + */
14.2393 + public static float[] copyOf(float[] original, int newLength) {
14.2394 + float[] copy = new float[newLength];
14.2395 + System.arraycopy(original, 0, copy, 0,
14.2396 + Math.min(original.length, newLength));
14.2397 + return copy;
14.2398 + }
14.2399 +
14.2400 + /**
14.2401 + * Copies the specified array, truncating or padding with zeros (if necessary)
14.2402 + * so the copy has the specified length. For all indices that are
14.2403 + * valid in both the original array and the copy, the two arrays will
14.2404 + * contain identical values. For any indices that are valid in the
14.2405 + * copy but not the original, the copy will contain <tt>0d</tt>.
14.2406 + * Such indices will exist if and only if the specified length
14.2407 + * is greater than that of the original array.
14.2408 + *
14.2409 + * @param original the array to be copied
14.2410 + * @param newLength the length of the copy to be returned
14.2411 + * @return a copy of the original array, truncated or padded with zeros
14.2412 + * to obtain the specified length
14.2413 + * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
14.2414 + * @throws NullPointerException if <tt>original</tt> is null
14.2415 + * @since 1.6
14.2416 + */
14.2417 + public static double[] copyOf(double[] original, int newLength) {
14.2418 + double[] copy = new double[newLength];
14.2419 + System.arraycopy(original, 0, copy, 0,
14.2420 + Math.min(original.length, newLength));
14.2421 + return copy;
14.2422 + }
14.2423 +
14.2424 + /**
14.2425 + * Copies the specified array, truncating or padding with <tt>false</tt> (if necessary)
14.2426 + * so the copy has the specified length. For all indices that are
14.2427 + * valid in both the original array and the copy, the two arrays will
14.2428 + * contain identical values. For any indices that are valid in the
14.2429 + * copy but not the original, the copy will contain <tt>false</tt>.
14.2430 + * Such indices will exist if and only if the specified length
14.2431 + * is greater than that of the original array.
14.2432 + *
14.2433 + * @param original the array to be copied
14.2434 + * @param newLength the length of the copy to be returned
14.2435 + * @return a copy of the original array, truncated or padded with false elements
14.2436 + * to obtain the specified length
14.2437 + * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
14.2438 + * @throws NullPointerException if <tt>original</tt> is null
14.2439 + * @since 1.6
14.2440 + */
14.2441 + public static boolean[] copyOf(boolean[] original, int newLength) {
14.2442 + boolean[] copy = new boolean[newLength];
14.2443 + System.arraycopy(original, 0, copy, 0,
14.2444 + Math.min(original.length, newLength));
14.2445 + return copy;
14.2446 + }
14.2447 +
14.2448 + /**
14.2449 + * Copies the specified range of the specified array into a new array.
14.2450 + * The initial index of the range (<tt>from</tt>) must lie between zero
14.2451 + * and <tt>original.length</tt>, inclusive. The value at
14.2452 + * <tt>original[from]</tt> is placed into the initial element of the copy
14.2453 + * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
14.2454 + * Values from subsequent elements in the original array are placed into
14.2455 + * subsequent elements in the copy. The final index of the range
14.2456 + * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
14.2457 + * may be greater than <tt>original.length</tt>, in which case
14.2458 + * <tt>null</tt> is placed in all elements of the copy whose index is
14.2459 + * greater than or equal to <tt>original.length - from</tt>. The length
14.2460 + * of the returned array will be <tt>to - from</tt>.
14.2461 + * <p>
14.2462 + * The resulting array is of exactly the same class as the original array.
14.2463 + *
14.2464 + * @param original the array from which a range is to be copied
14.2465 + * @param from the initial index of the range to be copied, inclusive
14.2466 + * @param to the final index of the range to be copied, exclusive.
14.2467 + * (This index may lie outside the array.)
14.2468 + * @return a new array containing the specified range from the original array,
14.2469 + * truncated or padded with nulls to obtain the required length
14.2470 + * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
14.2471 + * or {@code from > original.length}
14.2472 + * @throws IllegalArgumentException if <tt>from > to</tt>
14.2473 + * @throws NullPointerException if <tt>original</tt> is null
14.2474 + * @since 1.6
14.2475 + */
14.2476 + public static <T> T[] copyOfRange(T[] original, int from, int to) {
14.2477 + return copyOfRange(original, from, to, (Class<T[]>) original.getClass());
14.2478 + }
14.2479 +
14.2480 + /**
14.2481 + * Copies the specified range of the specified array into a new array.
14.2482 + * The initial index of the range (<tt>from</tt>) must lie between zero
14.2483 + * and <tt>original.length</tt>, inclusive. The value at
14.2484 + * <tt>original[from]</tt> is placed into the initial element of the copy
14.2485 + * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
14.2486 + * Values from subsequent elements in the original array are placed into
14.2487 + * subsequent elements in the copy. The final index of the range
14.2488 + * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
14.2489 + * may be greater than <tt>original.length</tt>, in which case
14.2490 + * <tt>null</tt> is placed in all elements of the copy whose index is
14.2491 + * greater than or equal to <tt>original.length - from</tt>. The length
14.2492 + * of the returned array will be <tt>to - from</tt>.
14.2493 + * The resulting array is of the class <tt>newType</tt>.
14.2494 + *
14.2495 + * @param original the array from which a range is to be copied
14.2496 + * @param from the initial index of the range to be copied, inclusive
14.2497 + * @param to the final index of the range to be copied, exclusive.
14.2498 + * (This index may lie outside the array.)
14.2499 + * @param newType the class of the copy to be returned
14.2500 + * @return a new array containing the specified range from the original array,
14.2501 + * truncated or padded with nulls to obtain the required length
14.2502 + * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
14.2503 + * or {@code from > original.length}
14.2504 + * @throws IllegalArgumentException if <tt>from > to</tt>
14.2505 + * @throws NullPointerException if <tt>original</tt> is null
14.2506 + * @throws ArrayStoreException if an element copied from
14.2507 + * <tt>original</tt> is not of a runtime type that can be stored in
14.2508 + * an array of class <tt>newType</tt>.
14.2509 + * @since 1.6
14.2510 + */
14.2511 + public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
14.2512 + int newLength = to - from;
14.2513 + if (newLength < 0)
14.2514 + throw new IllegalArgumentException(from + " > " + to);
14.2515 + T[] copy = ((Object)newType == (Object)Object[].class)
14.2516 + ? (T[]) new Object[newLength]
14.2517 + : (T[]) Array.newInstance(newType.getComponentType(), newLength);
14.2518 + System.arraycopy(original, from, copy, 0,
14.2519 + Math.min(original.length - from, newLength));
14.2520 + return copy;
14.2521 + }
14.2522 +
14.2523 + /**
14.2524 + * Copies the specified range of the specified array into a new array.
14.2525 + * The initial index of the range (<tt>from</tt>) must lie between zero
14.2526 + * and <tt>original.length</tt>, inclusive. The value at
14.2527 + * <tt>original[from]</tt> is placed into the initial element of the copy
14.2528 + * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
14.2529 + * Values from subsequent elements in the original array are placed into
14.2530 + * subsequent elements in the copy. The final index of the range
14.2531 + * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
14.2532 + * may be greater than <tt>original.length</tt>, in which case
14.2533 + * <tt>(byte)0</tt> is placed in all elements of the copy whose index is
14.2534 + * greater than or equal to <tt>original.length - from</tt>. The length
14.2535 + * of the returned array will be <tt>to - from</tt>.
14.2536 + *
14.2537 + * @param original the array from which a range is to be copied
14.2538 + * @param from the initial index of the range to be copied, inclusive
14.2539 + * @param to the final index of the range to be copied, exclusive.
14.2540 + * (This index may lie outside the array.)
14.2541 + * @return a new array containing the specified range from the original array,
14.2542 + * truncated or padded with zeros to obtain the required length
14.2543 + * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
14.2544 + * or {@code from > original.length}
14.2545 + * @throws IllegalArgumentException if <tt>from > to</tt>
14.2546 + * @throws NullPointerException if <tt>original</tt> is null
14.2547 + * @since 1.6
14.2548 + */
14.2549 + public static byte[] copyOfRange(byte[] original, int from, int to) {
14.2550 + int newLength = to - from;
14.2551 + if (newLength < 0)
14.2552 + throw new IllegalArgumentException(from + " > " + to);
14.2553 + byte[] copy = new byte[newLength];
14.2554 + System.arraycopy(original, from, copy, 0,
14.2555 + Math.min(original.length - from, newLength));
14.2556 + return copy;
14.2557 + }
14.2558 +
14.2559 + /**
14.2560 + * Copies the specified range of the specified array into a new array.
14.2561 + * The initial index of the range (<tt>from</tt>) must lie between zero
14.2562 + * and <tt>original.length</tt>, inclusive. The value at
14.2563 + * <tt>original[from]</tt> is placed into the initial element of the copy
14.2564 + * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
14.2565 + * Values from subsequent elements in the original array are placed into
14.2566 + * subsequent elements in the copy. The final index of the range
14.2567 + * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
14.2568 + * may be greater than <tt>original.length</tt>, in which case
14.2569 + * <tt>(short)0</tt> is placed in all elements of the copy whose index is
14.2570 + * greater than or equal to <tt>original.length - from</tt>. The length
14.2571 + * of the returned array will be <tt>to - from</tt>.
14.2572 + *
14.2573 + * @param original the array from which a range is to be copied
14.2574 + * @param from the initial index of the range to be copied, inclusive
14.2575 + * @param to the final index of the range to be copied, exclusive.
14.2576 + * (This index may lie outside the array.)
14.2577 + * @return a new array containing the specified range from the original array,
14.2578 + * truncated or padded with zeros to obtain the required length
14.2579 + * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
14.2580 + * or {@code from > original.length}
14.2581 + * @throws IllegalArgumentException if <tt>from > to</tt>
14.2582 + * @throws NullPointerException if <tt>original</tt> is null
14.2583 + * @since 1.6
14.2584 + */
14.2585 + public static short[] copyOfRange(short[] original, int from, int to) {
14.2586 + int newLength = to - from;
14.2587 + if (newLength < 0)
14.2588 + throw new IllegalArgumentException(from + " > " + to);
14.2589 + short[] copy = new short[newLength];
14.2590 + System.arraycopy(original, from, copy, 0,
14.2591 + Math.min(original.length - from, newLength));
14.2592 + return copy;
14.2593 + }
14.2594 +
14.2595 + /**
14.2596 + * Copies the specified range of the specified array into a new array.
14.2597 + * The initial index of the range (<tt>from</tt>) must lie between zero
14.2598 + * and <tt>original.length</tt>, inclusive. The value at
14.2599 + * <tt>original[from]</tt> is placed into the initial element of the copy
14.2600 + * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
14.2601 + * Values from subsequent elements in the original array are placed into
14.2602 + * subsequent elements in the copy. The final index of the range
14.2603 + * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
14.2604 + * may be greater than <tt>original.length</tt>, in which case
14.2605 + * <tt>0</tt> is placed in all elements of the copy whose index is
14.2606 + * greater than or equal to <tt>original.length - from</tt>. The length
14.2607 + * of the returned array will be <tt>to - from</tt>.
14.2608 + *
14.2609 + * @param original the array from which a range is to be copied
14.2610 + * @param from the initial index of the range to be copied, inclusive
14.2611 + * @param to the final index of the range to be copied, exclusive.
14.2612 + * (This index may lie outside the array.)
14.2613 + * @return a new array containing the specified range from the original array,
14.2614 + * truncated or padded with zeros to obtain the required length
14.2615 + * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
14.2616 + * or {@code from > original.length}
14.2617 + * @throws IllegalArgumentException if <tt>from > to</tt>
14.2618 + * @throws NullPointerException if <tt>original</tt> is null
14.2619 + * @since 1.6
14.2620 + */
14.2621 + public static int[] copyOfRange(int[] original, int from, int to) {
14.2622 + int newLength = to - from;
14.2623 + if (newLength < 0)
14.2624 + throw new IllegalArgumentException(from + " > " + to);
14.2625 + int[] copy = new int[newLength];
14.2626 + System.arraycopy(original, from, copy, 0,
14.2627 + Math.min(original.length - from, newLength));
14.2628 + return copy;
14.2629 + }
14.2630 +
14.2631 + /**
14.2632 + * Copies the specified range of the specified array into a new array.
14.2633 + * The initial index of the range (<tt>from</tt>) must lie between zero
14.2634 + * and <tt>original.length</tt>, inclusive. The value at
14.2635 + * <tt>original[from]</tt> is placed into the initial element of the copy
14.2636 + * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
14.2637 + * Values from subsequent elements in the original array are placed into
14.2638 + * subsequent elements in the copy. The final index of the range
14.2639 + * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
14.2640 + * may be greater than <tt>original.length</tt>, in which case
14.2641 + * <tt>0L</tt> is placed in all elements of the copy whose index is
14.2642 + * greater than or equal to <tt>original.length - from</tt>. The length
14.2643 + * of the returned array will be <tt>to - from</tt>.
14.2644 + *
14.2645 + * @param original the array from which a range is to be copied
14.2646 + * @param from the initial index of the range to be copied, inclusive
14.2647 + * @param to the final index of the range to be copied, exclusive.
14.2648 + * (This index may lie outside the array.)
14.2649 + * @return a new array containing the specified range from the original array,
14.2650 + * truncated or padded with zeros to obtain the required length
14.2651 + * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
14.2652 + * or {@code from > original.length}
14.2653 + * @throws IllegalArgumentException if <tt>from > to</tt>
14.2654 + * @throws NullPointerException if <tt>original</tt> is null
14.2655 + * @since 1.6
14.2656 + */
14.2657 + public static long[] copyOfRange(long[] original, int from, int to) {
14.2658 + int newLength = to - from;
14.2659 + if (newLength < 0)
14.2660 + throw new IllegalArgumentException(from + " > " + to);
14.2661 + long[] copy = new long[newLength];
14.2662 + System.arraycopy(original, from, copy, 0,
14.2663 + Math.min(original.length - from, newLength));
14.2664 + return copy;
14.2665 + }
14.2666 +
14.2667 + /**
14.2668 + * Copies the specified range of the specified array into a new array.
14.2669 + * The initial index of the range (<tt>from</tt>) must lie between zero
14.2670 + * and <tt>original.length</tt>, inclusive. The value at
14.2671 + * <tt>original[from]</tt> is placed into the initial element of the copy
14.2672 + * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
14.2673 + * Values from subsequent elements in the original array are placed into
14.2674 + * subsequent elements in the copy. The final index of the range
14.2675 + * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
14.2676 + * may be greater than <tt>original.length</tt>, in which case
14.2677 + * <tt>'\\u000'</tt> is placed in all elements of the copy whose index is
14.2678 + * greater than or equal to <tt>original.length - from</tt>. The length
14.2679 + * of the returned array will be <tt>to - from</tt>.
14.2680 + *
14.2681 + * @param original the array from which a range is to be copied
14.2682 + * @param from the initial index of the range to be copied, inclusive
14.2683 + * @param to the final index of the range to be copied, exclusive.
14.2684 + * (This index may lie outside the array.)
14.2685 + * @return a new array containing the specified range from the original array,
14.2686 + * truncated or padded with null characters to obtain the required length
14.2687 + * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
14.2688 + * or {@code from > original.length}
14.2689 + * @throws IllegalArgumentException if <tt>from > to</tt>
14.2690 + * @throws NullPointerException if <tt>original</tt> is null
14.2691 + * @since 1.6
14.2692 + */
14.2693 + public static char[] copyOfRange(char[] original, int from, int to) {
14.2694 + int newLength = to - from;
14.2695 + if (newLength < 0)
14.2696 + throw new IllegalArgumentException(from + " > " + to);
14.2697 + char[] copy = new char[newLength];
14.2698 + System.arraycopy(original, from, copy, 0,
14.2699 + Math.min(original.length - from, newLength));
14.2700 + return copy;
14.2701 + }
14.2702 +
14.2703 + /**
14.2704 + * Copies the specified range of the specified array into a new array.
14.2705 + * The initial index of the range (<tt>from</tt>) must lie between zero
14.2706 + * and <tt>original.length</tt>, inclusive. The value at
14.2707 + * <tt>original[from]</tt> is placed into the initial element of the copy
14.2708 + * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
14.2709 + * Values from subsequent elements in the original array are placed into
14.2710 + * subsequent elements in the copy. The final index of the range
14.2711 + * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
14.2712 + * may be greater than <tt>original.length</tt>, in which case
14.2713 + * <tt>0f</tt> is placed in all elements of the copy whose index is
14.2714 + * greater than or equal to <tt>original.length - from</tt>. The length
14.2715 + * of the returned array will be <tt>to - from</tt>.
14.2716 + *
14.2717 + * @param original the array from which a range is to be copied
14.2718 + * @param from the initial index of the range to be copied, inclusive
14.2719 + * @param to the final index of the range to be copied, exclusive.
14.2720 + * (This index may lie outside the array.)
14.2721 + * @return a new array containing the specified range from the original array,
14.2722 + * truncated or padded with zeros to obtain the required length
14.2723 + * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
14.2724 + * or {@code from > original.length}
14.2725 + * @throws IllegalArgumentException if <tt>from > to</tt>
14.2726 + * @throws NullPointerException if <tt>original</tt> is null
14.2727 + * @since 1.6
14.2728 + */
14.2729 + public static float[] copyOfRange(float[] original, int from, int to) {
14.2730 + int newLength = to - from;
14.2731 + if (newLength < 0)
14.2732 + throw new IllegalArgumentException(from + " > " + to);
14.2733 + float[] copy = new float[newLength];
14.2734 + System.arraycopy(original, from, copy, 0,
14.2735 + Math.min(original.length - from, newLength));
14.2736 + return copy;
14.2737 + }
14.2738 +
14.2739 + /**
14.2740 + * Copies the specified range of the specified array into a new array.
14.2741 + * The initial index of the range (<tt>from</tt>) must lie between zero
14.2742 + * and <tt>original.length</tt>, inclusive. The value at
14.2743 + * <tt>original[from]</tt> is placed into the initial element of the copy
14.2744 + * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
14.2745 + * Values from subsequent elements in the original array are placed into
14.2746 + * subsequent elements in the copy. The final index of the range
14.2747 + * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
14.2748 + * may be greater than <tt>original.length</tt>, in which case
14.2749 + * <tt>0d</tt> is placed in all elements of the copy whose index is
14.2750 + * greater than or equal to <tt>original.length - from</tt>. The length
14.2751 + * of the returned array will be <tt>to - from</tt>.
14.2752 + *
14.2753 + * @param original the array from which a range is to be copied
14.2754 + * @param from the initial index of the range to be copied, inclusive
14.2755 + * @param to the final index of the range to be copied, exclusive.
14.2756 + * (This index may lie outside the array.)
14.2757 + * @return a new array containing the specified range from the original array,
14.2758 + * truncated or padded with zeros to obtain the required length
14.2759 + * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
14.2760 + * or {@code from > original.length}
14.2761 + * @throws IllegalArgumentException if <tt>from > to</tt>
14.2762 + * @throws NullPointerException if <tt>original</tt> is null
14.2763 + * @since 1.6
14.2764 + */
14.2765 + public static double[] copyOfRange(double[] original, int from, int to) {
14.2766 + int newLength = to - from;
14.2767 + if (newLength < 0)
14.2768 + throw new IllegalArgumentException(from + " > " + to);
14.2769 + double[] copy = new double[newLength];
14.2770 + System.arraycopy(original, from, copy, 0,
14.2771 + Math.min(original.length - from, newLength));
14.2772 + return copy;
14.2773 + }
14.2774 +
14.2775 + /**
14.2776 + * Copies the specified range of the specified array into a new array.
14.2777 + * The initial index of the range (<tt>from</tt>) must lie between zero
14.2778 + * and <tt>original.length</tt>, inclusive. The value at
14.2779 + * <tt>original[from]</tt> is placed into the initial element of the copy
14.2780 + * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
14.2781 + * Values from subsequent elements in the original array are placed into
14.2782 + * subsequent elements in the copy. The final index of the range
14.2783 + * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
14.2784 + * may be greater than <tt>original.length</tt>, in which case
14.2785 + * <tt>false</tt> is placed in all elements of the copy whose index is
14.2786 + * greater than or equal to <tt>original.length - from</tt>. The length
14.2787 + * of the returned array will be <tt>to - from</tt>.
14.2788 + *
14.2789 + * @param original the array from which a range is to be copied
14.2790 + * @param from the initial index of the range to be copied, inclusive
14.2791 + * @param to the final index of the range to be copied, exclusive.
14.2792 + * (This index may lie outside the array.)
14.2793 + * @return a new array containing the specified range from the original array,
14.2794 + * truncated or padded with false elements to obtain the required length
14.2795 + * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
14.2796 + * or {@code from > original.length}
14.2797 + * @throws IllegalArgumentException if <tt>from > to</tt>
14.2798 + * @throws NullPointerException if <tt>original</tt> is null
14.2799 + * @since 1.6
14.2800 + */
14.2801 + public static boolean[] copyOfRange(boolean[] original, int from, int to) {
14.2802 + int newLength = to - from;
14.2803 + if (newLength < 0)
14.2804 + throw new IllegalArgumentException(from + " > " + to);
14.2805 + boolean[] copy = new boolean[newLength];
14.2806 + System.arraycopy(original, from, copy, 0,
14.2807 + Math.min(original.length - from, newLength));
14.2808 + return copy;
14.2809 + }
14.2810 +
14.2811 + // Misc
14.2812 +
14.2813 + /**
14.2814 + * Returns a fixed-size list backed by the specified array. (Changes to
14.2815 + * the returned list "write through" to the array.) This method acts
14.2816 + * as bridge between array-based and collection-based APIs, in
14.2817 + * combination with {@link Collection#toArray}. The returned list is
14.2818 + * serializable and implements {@link RandomAccess}.
14.2819 + *
14.2820 + * <p>This method also provides a convenient way to create a fixed-size
14.2821 + * list initialized to contain several elements:
14.2822 + * <pre>
14.2823 + * List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
14.2824 + * </pre>
14.2825 + *
14.2826 + * @param a the array by which the list will be backed
14.2827 + * @return a list view of the specified array
14.2828 + */
14.2829 + @SafeVarargs
14.2830 + public static <T> List<T> asList(T... a) {
14.2831 + return new ArrayList<>(a);
14.2832 + }
14.2833 +
14.2834 + /**
14.2835 + * @serial include
14.2836 + */
14.2837 + private static class ArrayList<E> extends AbstractList<E>
14.2838 + implements RandomAccess, java.io.Serializable
14.2839 + {
14.2840 + private static final long serialVersionUID = -2764017481108945198L;
14.2841 + private final E[] a;
14.2842 +
14.2843 + ArrayList(E[] array) {
14.2844 + if (array==null)
14.2845 + throw new NullPointerException();
14.2846 + a = array;
14.2847 + }
14.2848 +
14.2849 + public int size() {
14.2850 + return a.length;
14.2851 + }
14.2852 +
14.2853 + public Object[] toArray() {
14.2854 + return a.clone();
14.2855 + }
14.2856 +
14.2857 + public <T> T[] toArray(T[] a) {
14.2858 + int size = size();
14.2859 + if (a.length < size)
14.2860 + return Arrays.copyOf(this.a, size,
14.2861 + (Class<? extends T[]>) a.getClass());
14.2862 + System.arraycopy(this.a, 0, a, 0, size);
14.2863 + if (a.length > size)
14.2864 + a[size] = null;
14.2865 + return a;
14.2866 + }
14.2867 +
14.2868 + public E get(int index) {
14.2869 + return a[index];
14.2870 + }
14.2871 +
14.2872 + public E set(int index, E element) {
14.2873 + E oldValue = a[index];
14.2874 + a[index] = element;
14.2875 + return oldValue;
14.2876 + }
14.2877 +
14.2878 + public int indexOf(Object o) {
14.2879 + if (o==null) {
14.2880 + for (int i=0; i<a.length; i++)
14.2881 + if (a[i]==null)
14.2882 + return i;
14.2883 + } else {
14.2884 + for (int i=0; i<a.length; i++)
14.2885 + if (o.equals(a[i]))
14.2886 + return i;
14.2887 + }
14.2888 + return -1;
14.2889 + }
14.2890 +
14.2891 + public boolean contains(Object o) {
14.2892 + return indexOf(o) != -1;
14.2893 + }
14.2894 + }
14.2895 +
14.2896 + /**
14.2897 + * Returns a hash code based on the contents of the specified array.
14.2898 + * For any two <tt>long</tt> arrays <tt>a</tt> and <tt>b</tt>
14.2899 + * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
14.2900 + * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
14.2901 + *
14.2902 + * <p>The value returned by this method is the same value that would be
14.2903 + * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
14.2904 + * method on a {@link List} containing a sequence of {@link Long}
14.2905 + * instances representing the elements of <tt>a</tt> in the same order.
14.2906 + * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
14.2907 + *
14.2908 + * @param a the array whose hash value to compute
14.2909 + * @return a content-based hash code for <tt>a</tt>
14.2910 + * @since 1.5
14.2911 + */
14.2912 + public static int hashCode(long a[]) {
14.2913 + if (a == null)
14.2914 + return 0;
14.2915 +
14.2916 + int result = 1;
14.2917 + for (long element : a) {
14.2918 + int elementHash = (int)(element ^ (element >>> 32));
14.2919 + result = 31 * result + elementHash;
14.2920 + }
14.2921 +
14.2922 + return result;
14.2923 + }
14.2924 +
14.2925 + /**
14.2926 + * Returns a hash code based on the contents of the specified array.
14.2927 + * For any two non-null <tt>int</tt> arrays <tt>a</tt> and <tt>b</tt>
14.2928 + * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
14.2929 + * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
14.2930 + *
14.2931 + * <p>The value returned by this method is the same value that would be
14.2932 + * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
14.2933 + * method on a {@link List} containing a sequence of {@link Integer}
14.2934 + * instances representing the elements of <tt>a</tt> in the same order.
14.2935 + * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
14.2936 + *
14.2937 + * @param a the array whose hash value to compute
14.2938 + * @return a content-based hash code for <tt>a</tt>
14.2939 + * @since 1.5
14.2940 + */
14.2941 + public static int hashCode(int a[]) {
14.2942 + if (a == null)
14.2943 + return 0;
14.2944 +
14.2945 + int result = 1;
14.2946 + for (int element : a)
14.2947 + result = 31 * result + element;
14.2948 +
14.2949 + return result;
14.2950 + }
14.2951 +
14.2952 + /**
14.2953 + * Returns a hash code based on the contents of the specified array.
14.2954 + * For any two <tt>short</tt> arrays <tt>a</tt> and <tt>b</tt>
14.2955 + * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
14.2956 + * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
14.2957 + *
14.2958 + * <p>The value returned by this method is the same value that would be
14.2959 + * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
14.2960 + * method on a {@link List} containing a sequence of {@link Short}
14.2961 + * instances representing the elements of <tt>a</tt> in the same order.
14.2962 + * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
14.2963 + *
14.2964 + * @param a the array whose hash value to compute
14.2965 + * @return a content-based hash code for <tt>a</tt>
14.2966 + * @since 1.5
14.2967 + */
14.2968 + public static int hashCode(short a[]) {
14.2969 + if (a == null)
14.2970 + return 0;
14.2971 +
14.2972 + int result = 1;
14.2973 + for (short element : a)
14.2974 + result = 31 * result + element;
14.2975 +
14.2976 + return result;
14.2977 + }
14.2978 +
14.2979 + /**
14.2980 + * Returns a hash code based on the contents of the specified array.
14.2981 + * For any two <tt>char</tt> arrays <tt>a</tt> and <tt>b</tt>
14.2982 + * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
14.2983 + * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
14.2984 + *
14.2985 + * <p>The value returned by this method is the same value that would be
14.2986 + * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
14.2987 + * method on a {@link List} containing a sequence of {@link Character}
14.2988 + * instances representing the elements of <tt>a</tt> in the same order.
14.2989 + * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
14.2990 + *
14.2991 + * @param a the array whose hash value to compute
14.2992 + * @return a content-based hash code for <tt>a</tt>
14.2993 + * @since 1.5
14.2994 + */
14.2995 + public static int hashCode(char a[]) {
14.2996 + if (a == null)
14.2997 + return 0;
14.2998 +
14.2999 + int result = 1;
14.3000 + for (char element : a)
14.3001 + result = 31 * result + element;
14.3002 +
14.3003 + return result;
14.3004 + }
14.3005 +
14.3006 + /**
14.3007 + * Returns a hash code based on the contents of the specified array.
14.3008 + * For any two <tt>byte</tt> arrays <tt>a</tt> and <tt>b</tt>
14.3009 + * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
14.3010 + * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
14.3011 + *
14.3012 + * <p>The value returned by this method is the same value that would be
14.3013 + * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
14.3014 + * method on a {@link List} containing a sequence of {@link Byte}
14.3015 + * instances representing the elements of <tt>a</tt> in the same order.
14.3016 + * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
14.3017 + *
14.3018 + * @param a the array whose hash value to compute
14.3019 + * @return a content-based hash code for <tt>a</tt>
14.3020 + * @since 1.5
14.3021 + */
14.3022 + public static int hashCode(byte a[]) {
14.3023 + if (a == null)
14.3024 + return 0;
14.3025 +
14.3026 + int result = 1;
14.3027 + for (byte element : a)
14.3028 + result = 31 * result + element;
14.3029 +
14.3030 + return result;
14.3031 + }
14.3032 +
14.3033 + /**
14.3034 + * Returns a hash code based on the contents of the specified array.
14.3035 + * For any two <tt>boolean</tt> arrays <tt>a</tt> and <tt>b</tt>
14.3036 + * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
14.3037 + * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
14.3038 + *
14.3039 + * <p>The value returned by this method is the same value that would be
14.3040 + * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
14.3041 + * method on a {@link List} containing a sequence of {@link Boolean}
14.3042 + * instances representing the elements of <tt>a</tt> in the same order.
14.3043 + * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
14.3044 + *
14.3045 + * @param a the array whose hash value to compute
14.3046 + * @return a content-based hash code for <tt>a</tt>
14.3047 + * @since 1.5
14.3048 + */
14.3049 + public static int hashCode(boolean a[]) {
14.3050 + if (a == null)
14.3051 + return 0;
14.3052 +
14.3053 + int result = 1;
14.3054 + for (boolean element : a)
14.3055 + result = 31 * result + (element ? 1231 : 1237);
14.3056 +
14.3057 + return result;
14.3058 + }
14.3059 +
14.3060 + /**
14.3061 + * Returns a hash code based on the contents of the specified array.
14.3062 + * For any two <tt>float</tt> arrays <tt>a</tt> and <tt>b</tt>
14.3063 + * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
14.3064 + * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
14.3065 + *
14.3066 + * <p>The value returned by this method is the same value that would be
14.3067 + * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
14.3068 + * method on a {@link List} containing a sequence of {@link Float}
14.3069 + * instances representing the elements of <tt>a</tt> in the same order.
14.3070 + * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
14.3071 + *
14.3072 + * @param a the array whose hash value to compute
14.3073 + * @return a content-based hash code for <tt>a</tt>
14.3074 + * @since 1.5
14.3075 + */
14.3076 + public static int hashCode(float a[]) {
14.3077 + if (a == null)
14.3078 + return 0;
14.3079 +
14.3080 + int result = 1;
14.3081 + for (float element : a)
14.3082 + result = 31 * result + Float.floatToIntBits(element);
14.3083 +
14.3084 + return result;
14.3085 + }
14.3086 +
14.3087 + /**
14.3088 + * Returns a hash code based on the contents of the specified array.
14.3089 + * For any two <tt>double</tt> arrays <tt>a</tt> and <tt>b</tt>
14.3090 + * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
14.3091 + * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
14.3092 + *
14.3093 + * <p>The value returned by this method is the same value that would be
14.3094 + * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
14.3095 + * method on a {@link List} containing a sequence of {@link Double}
14.3096 + * instances representing the elements of <tt>a</tt> in the same order.
14.3097 + * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
14.3098 + *
14.3099 + * @param a the array whose hash value to compute
14.3100 + * @return a content-based hash code for <tt>a</tt>
14.3101 + * @since 1.5
14.3102 + */
14.3103 + public static int hashCode(double a[]) {
14.3104 + if (a == null)
14.3105 + return 0;
14.3106 +
14.3107 + int result = 1;
14.3108 + for (double element : a) {
14.3109 + long bits = Double.doubleToLongBits(element);
14.3110 + result = 31 * result + (int)(bits ^ (bits >>> 32));
14.3111 + }
14.3112 + return result;
14.3113 + }
14.3114 +
14.3115 + /**
14.3116 + * Returns a hash code based on the contents of the specified array. If
14.3117 + * the array contains other arrays as elements, the hash code is based on
14.3118 + * their identities rather than their contents. It is therefore
14.3119 + * acceptable to invoke this method on an array that contains itself as an
14.3120 + * element, either directly or indirectly through one or more levels of
14.3121 + * arrays.
14.3122 + *
14.3123 + * <p>For any two arrays <tt>a</tt> and <tt>b</tt> such that
14.3124 + * <tt>Arrays.equals(a, b)</tt>, it is also the case that
14.3125 + * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
14.3126 + *
14.3127 + * <p>The value returned by this method is equal to the value that would
14.3128 + * be returned by <tt>Arrays.asList(a).hashCode()</tt>, unless <tt>a</tt>
14.3129 + * is <tt>null</tt>, in which case <tt>0</tt> is returned.
14.3130 + *
14.3131 + * @param a the array whose content-based hash code to compute
14.3132 + * @return a content-based hash code for <tt>a</tt>
14.3133 + * @see #deepHashCode(Object[])
14.3134 + * @since 1.5
14.3135 + */
14.3136 + public static int hashCode(Object a[]) {
14.3137 + if (a == null)
14.3138 + return 0;
14.3139 +
14.3140 + int result = 1;
14.3141 +
14.3142 + for (Object element : a)
14.3143 + result = 31 * result + (element == null ? 0 : element.hashCode());
14.3144 +
14.3145 + return result;
14.3146 + }
14.3147 +
14.3148 + /**
14.3149 + * Returns a hash code based on the "deep contents" of the specified
14.3150 + * array. If the array contains other arrays as elements, the
14.3151 + * hash code is based on their contents and so on, ad infinitum.
14.3152 + * It is therefore unacceptable to invoke this method on an array that
14.3153 + * contains itself as an element, either directly or indirectly through
14.3154 + * one or more levels of arrays. The behavior of such an invocation is
14.3155 + * undefined.
14.3156 + *
14.3157 + * <p>For any two arrays <tt>a</tt> and <tt>b</tt> such that
14.3158 + * <tt>Arrays.deepEquals(a, b)</tt>, it is also the case that
14.3159 + * <tt>Arrays.deepHashCode(a) == Arrays.deepHashCode(b)</tt>.
14.3160 + *
14.3161 + * <p>The computation of the value returned by this method is similar to
14.3162 + * that of the value returned by {@link List#hashCode()} on a list
14.3163 + * containing the same elements as <tt>a</tt> in the same order, with one
14.3164 + * difference: If an element <tt>e</tt> of <tt>a</tt> is itself an array,
14.3165 + * its hash code is computed not by calling <tt>e.hashCode()</tt>, but as
14.3166 + * by calling the appropriate overloading of <tt>Arrays.hashCode(e)</tt>
14.3167 + * if <tt>e</tt> is an array of a primitive type, or as by calling
14.3168 + * <tt>Arrays.deepHashCode(e)</tt> recursively if <tt>e</tt> is an array
14.3169 + * of a reference type. If <tt>a</tt> is <tt>null</tt>, this method
14.3170 + * returns 0.
14.3171 + *
14.3172 + * @param a the array whose deep-content-based hash code to compute
14.3173 + * @return a deep-content-based hash code for <tt>a</tt>
14.3174 + * @see #hashCode(Object[])
14.3175 + * @since 1.5
14.3176 + */
14.3177 + public static int deepHashCode(Object a[]) {
14.3178 + if (a == null)
14.3179 + return 0;
14.3180 +
14.3181 + int result = 1;
14.3182 +
14.3183 + for (Object element : a) {
14.3184 + int elementHash = 0;
14.3185 + if (element instanceof Object[])
14.3186 + elementHash = deepHashCode((Object[]) element);
14.3187 + else if (element instanceof byte[])
14.3188 + elementHash = hashCode((byte[]) element);
14.3189 + else if (element instanceof short[])
14.3190 + elementHash = hashCode((short[]) element);
14.3191 + else if (element instanceof int[])
14.3192 + elementHash = hashCode((int[]) element);
14.3193 + else if (element instanceof long[])
14.3194 + elementHash = hashCode((long[]) element);
14.3195 + else if (element instanceof char[])
14.3196 + elementHash = hashCode((char[]) element);
14.3197 + else if (element instanceof float[])
14.3198 + elementHash = hashCode((float[]) element);
14.3199 + else if (element instanceof double[])
14.3200 + elementHash = hashCode((double[]) element);
14.3201 + else if (element instanceof boolean[])
14.3202 + elementHash = hashCode((boolean[]) element);
14.3203 + else if (element != null)
14.3204 + elementHash = element.hashCode();
14.3205 +
14.3206 + result = 31 * result + elementHash;
14.3207 + }
14.3208 +
14.3209 + return result;
14.3210 + }
14.3211 +
14.3212 + /**
14.3213 + * Returns <tt>true</tt> if the two specified arrays are <i>deeply
14.3214 + * equal</i> to one another. Unlike the {@link #equals(Object[],Object[])}
14.3215 + * method, this method is appropriate for use with nested arrays of
14.3216 + * arbitrary depth.
14.3217 + *
14.3218 + * <p>Two array references are considered deeply equal if both
14.3219 + * are <tt>null</tt>, or if they refer to arrays that contain the same
14.3220 + * number of elements and all corresponding pairs of elements in the two
14.3221 + * arrays are deeply equal.
14.3222 + *
14.3223 + * <p>Two possibly <tt>null</tt> elements <tt>e1</tt> and <tt>e2</tt> are
14.3224 + * deeply equal if any of the following conditions hold:
14.3225 + * <ul>
14.3226 + * <li> <tt>e1</tt> and <tt>e2</tt> are both arrays of object reference
14.3227 + * types, and <tt>Arrays.deepEquals(e1, e2) would return true</tt>
14.3228 + * <li> <tt>e1</tt> and <tt>e2</tt> are arrays of the same primitive
14.3229 + * type, and the appropriate overloading of
14.3230 + * <tt>Arrays.equals(e1, e2)</tt> would return true.
14.3231 + * <li> <tt>e1 == e2</tt>
14.3232 + * <li> <tt>e1.equals(e2)</tt> would return true.
14.3233 + * </ul>
14.3234 + * Note that this definition permits <tt>null</tt> elements at any depth.
14.3235 + *
14.3236 + * <p>If either of the specified arrays contain themselves as elements
14.3237 + * either directly or indirectly through one or more levels of arrays,
14.3238 + * the behavior of this method is undefined.
14.3239 + *
14.3240 + * @param a1 one array to be tested for equality
14.3241 + * @param a2 the other array to be tested for equality
14.3242 + * @return <tt>true</tt> if the two arrays are equal
14.3243 + * @see #equals(Object[],Object[])
14.3244 + * @see Objects#deepEquals(Object, Object)
14.3245 + * @since 1.5
14.3246 + */
14.3247 + public static boolean deepEquals(Object[] a1, Object[] a2) {
14.3248 + if (a1 == a2)
14.3249 + return true;
14.3250 + if (a1 == null || a2==null)
14.3251 + return false;
14.3252 + int length = a1.length;
14.3253 + if (a2.length != length)
14.3254 + return false;
14.3255 +
14.3256 + for (int i = 0; i < length; i++) {
14.3257 + Object e1 = a1[i];
14.3258 + Object e2 = a2[i];
14.3259 +
14.3260 + if (e1 == e2)
14.3261 + continue;
14.3262 + if (e1 == null)
14.3263 + return false;
14.3264 +
14.3265 + // Figure out whether the two elements are equal
14.3266 + boolean eq = deepEquals0(e1, e2);
14.3267 +
14.3268 + if (!eq)
14.3269 + return false;
14.3270 + }
14.3271 + return true;
14.3272 + }
14.3273 +
14.3274 + static boolean deepEquals0(Object e1, Object e2) {
14.3275 + assert e1 != null;
14.3276 + boolean eq;
14.3277 + if (e1 instanceof Object[] && e2 instanceof Object[])
14.3278 + eq = deepEquals ((Object[]) e1, (Object[]) e2);
14.3279 + else if (e1 instanceof byte[] && e2 instanceof byte[])
14.3280 + eq = equals((byte[]) e1, (byte[]) e2);
14.3281 + else if (e1 instanceof short[] && e2 instanceof short[])
14.3282 + eq = equals((short[]) e1, (short[]) e2);
14.3283 + else if (e1 instanceof int[] && e2 instanceof int[])
14.3284 + eq = equals((int[]) e1, (int[]) e2);
14.3285 + else if (e1 instanceof long[] && e2 instanceof long[])
14.3286 + eq = equals((long[]) e1, (long[]) e2);
14.3287 + else if (e1 instanceof char[] && e2 instanceof char[])
14.3288 + eq = equals((char[]) e1, (char[]) e2);
14.3289 + else if (e1 instanceof float[] && e2 instanceof float[])
14.3290 + eq = equals((float[]) e1, (float[]) e2);
14.3291 + else if (e1 instanceof double[] && e2 instanceof double[])
14.3292 + eq = equals((double[]) e1, (double[]) e2);
14.3293 + else if (e1 instanceof boolean[] && e2 instanceof boolean[])
14.3294 + eq = equals((boolean[]) e1, (boolean[]) e2);
14.3295 + else
14.3296 + eq = e1.equals(e2);
14.3297 + return eq;
14.3298 + }
14.3299 +
14.3300 + /**
14.3301 + * Returns a string representation of the contents of the specified array.
14.3302 + * The string representation consists of a list of the array's elements,
14.3303 + * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are
14.3304 + * separated by the characters <tt>", "</tt> (a comma followed by a
14.3305 + * space). Elements are converted to strings as by
14.3306 + * <tt>String.valueOf(long)</tt>. Returns <tt>"null"</tt> if <tt>a</tt>
14.3307 + * is <tt>null</tt>.
14.3308 + *
14.3309 + * @param a the array whose string representation to return
14.3310 + * @return a string representation of <tt>a</tt>
14.3311 + * @since 1.5
14.3312 + */
14.3313 + public static String toString(long[] a) {
14.3314 + if (a == null)
14.3315 + return "null";
14.3316 + int iMax = a.length - 1;
14.3317 + if (iMax == -1)
14.3318 + return "[]";
14.3319 +
14.3320 + StringBuilder b = new StringBuilder();
14.3321 + b.append('[');
14.3322 + for (int i = 0; ; i++) {
14.3323 + b.append(a[i]);
14.3324 + if (i == iMax)
14.3325 + return b.append(']').toString();
14.3326 + b.append(", ");
14.3327 + }
14.3328 + }
14.3329 +
14.3330 + /**
14.3331 + * Returns a string representation of the contents of the specified array.
14.3332 + * The string representation consists of a list of the array's elements,
14.3333 + * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are
14.3334 + * separated by the characters <tt>", "</tt> (a comma followed by a
14.3335 + * space). Elements are converted to strings as by
14.3336 + * <tt>String.valueOf(int)</tt>. Returns <tt>"null"</tt> if <tt>a</tt> is
14.3337 + * <tt>null</tt>.
14.3338 + *
14.3339 + * @param a the array whose string representation to return
14.3340 + * @return a string representation of <tt>a</tt>
14.3341 + * @since 1.5
14.3342 + */
14.3343 + public static String toString(int[] a) {
14.3344 + if (a == null)
14.3345 + return "null";
14.3346 + int iMax = a.length - 1;
14.3347 + if (iMax == -1)
14.3348 + return "[]";
14.3349 +
14.3350 + StringBuilder b = new StringBuilder();
14.3351 + b.append('[');
14.3352 + for (int i = 0; ; i++) {
14.3353 + b.append(a[i]);
14.3354 + if (i == iMax)
14.3355 + return b.append(']').toString();
14.3356 + b.append(", ");
14.3357 + }
14.3358 + }
14.3359 +
14.3360 + /**
14.3361 + * Returns a string representation of the contents of the specified array.
14.3362 + * The string representation consists of a list of the array's elements,
14.3363 + * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are
14.3364 + * separated by the characters <tt>", "</tt> (a comma followed by a
14.3365 + * space). Elements are converted to strings as by
14.3366 + * <tt>String.valueOf(short)</tt>. Returns <tt>"null"</tt> if <tt>a</tt>
14.3367 + * is <tt>null</tt>.
14.3368 + *
14.3369 + * @param a the array whose string representation to return
14.3370 + * @return a string representation of <tt>a</tt>
14.3371 + * @since 1.5
14.3372 + */
14.3373 + public static String toString(short[] a) {
14.3374 + if (a == null)
14.3375 + return "null";
14.3376 + int iMax = a.length - 1;
14.3377 + if (iMax == -1)
14.3378 + return "[]";
14.3379 +
14.3380 + StringBuilder b = new StringBuilder();
14.3381 + b.append('[');
14.3382 + for (int i = 0; ; i++) {
14.3383 + b.append(a[i]);
14.3384 + if (i == iMax)
14.3385 + return b.append(']').toString();
14.3386 + b.append(", ");
14.3387 + }
14.3388 + }
14.3389 +
14.3390 + /**
14.3391 + * Returns a string representation of the contents of the specified array.
14.3392 + * The string representation consists of a list of the array's elements,
14.3393 + * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are
14.3394 + * separated by the characters <tt>", "</tt> (a comma followed by a
14.3395 + * space). Elements are converted to strings as by
14.3396 + * <tt>String.valueOf(char)</tt>. Returns <tt>"null"</tt> if <tt>a</tt>
14.3397 + * is <tt>null</tt>.
14.3398 + *
14.3399 + * @param a the array whose string representation to return
14.3400 + * @return a string representation of <tt>a</tt>
14.3401 + * @since 1.5
14.3402 + */
14.3403 + public static String toString(char[] a) {
14.3404 + if (a == null)
14.3405 + return "null";
14.3406 + int iMax = a.length - 1;
14.3407 + if (iMax == -1)
14.3408 + return "[]";
14.3409 +
14.3410 + StringBuilder b = new StringBuilder();
14.3411 + b.append('[');
14.3412 + for (int i = 0; ; i++) {
14.3413 + b.append(a[i]);
14.3414 + if (i == iMax)
14.3415 + return b.append(']').toString();
14.3416 + b.append(", ");
14.3417 + }
14.3418 + }
14.3419 +
14.3420 + /**
14.3421 + * Returns a string representation of the contents of the specified array.
14.3422 + * The string representation consists of a list of the array's elements,
14.3423 + * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements
14.3424 + * are separated by the characters <tt>", "</tt> (a comma followed
14.3425 + * by a space). Elements are converted to strings as by
14.3426 + * <tt>String.valueOf(byte)</tt>. Returns <tt>"null"</tt> if
14.3427 + * <tt>a</tt> is <tt>null</tt>.
14.3428 + *
14.3429 + * @param a the array whose string representation to return
14.3430 + * @return a string representation of <tt>a</tt>
14.3431 + * @since 1.5
14.3432 + */
14.3433 + public static String toString(byte[] a) {
14.3434 + if (a == null)
14.3435 + return "null";
14.3436 + int iMax = a.length - 1;
14.3437 + if (iMax == -1)
14.3438 + return "[]";
14.3439 +
14.3440 + StringBuilder b = new StringBuilder();
14.3441 + b.append('[');
14.3442 + for (int i = 0; ; i++) {
14.3443 + b.append(a[i]);
14.3444 + if (i == iMax)
14.3445 + return b.append(']').toString();
14.3446 + b.append(", ");
14.3447 + }
14.3448 + }
14.3449 +
14.3450 + /**
14.3451 + * Returns a string representation of the contents of the specified array.
14.3452 + * The string representation consists of a list of the array's elements,
14.3453 + * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are
14.3454 + * separated by the characters <tt>", "</tt> (a comma followed by a
14.3455 + * space). Elements are converted to strings as by
14.3456 + * <tt>String.valueOf(boolean)</tt>. Returns <tt>"null"</tt> if
14.3457 + * <tt>a</tt> is <tt>null</tt>.
14.3458 + *
14.3459 + * @param a the array whose string representation to return
14.3460 + * @return a string representation of <tt>a</tt>
14.3461 + * @since 1.5
14.3462 + */
14.3463 + public static String toString(boolean[] a) {
14.3464 + if (a == null)
14.3465 + return "null";
14.3466 + int iMax = a.length - 1;
14.3467 + if (iMax == -1)
14.3468 + return "[]";
14.3469 +
14.3470 + StringBuilder b = new StringBuilder();
14.3471 + b.append('[');
14.3472 + for (int i = 0; ; i++) {
14.3473 + b.append(a[i]);
14.3474 + if (i == iMax)
14.3475 + return b.append(']').toString();
14.3476 + b.append(", ");
14.3477 + }
14.3478 + }
14.3479 +
14.3480 + /**
14.3481 + * Returns a string representation of the contents of the specified array.
14.3482 + * The string representation consists of a list of the array's elements,
14.3483 + * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are
14.3484 + * separated by the characters <tt>", "</tt> (a comma followed by a
14.3485 + * space). Elements are converted to strings as by
14.3486 + * <tt>String.valueOf(float)</tt>. Returns <tt>"null"</tt> if <tt>a</tt>
14.3487 + * is <tt>null</tt>.
14.3488 + *
14.3489 + * @param a the array whose string representation to return
14.3490 + * @return a string representation of <tt>a</tt>
14.3491 + * @since 1.5
14.3492 + */
14.3493 + public static String toString(float[] a) {
14.3494 + if (a == null)
14.3495 + return "null";
14.3496 +
14.3497 + int iMax = a.length - 1;
14.3498 + if (iMax == -1)
14.3499 + return "[]";
14.3500 +
14.3501 + StringBuilder b = new StringBuilder();
14.3502 + b.append('[');
14.3503 + for (int i = 0; ; i++) {
14.3504 + b.append(a[i]);
14.3505 + if (i == iMax)
14.3506 + return b.append(']').toString();
14.3507 + b.append(", ");
14.3508 + }
14.3509 + }
14.3510 +
14.3511 + /**
14.3512 + * Returns a string representation of the contents of the specified array.
14.3513 + * The string representation consists of a list of the array's elements,
14.3514 + * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are
14.3515 + * separated by the characters <tt>", "</tt> (a comma followed by a
14.3516 + * space). Elements are converted to strings as by
14.3517 + * <tt>String.valueOf(double)</tt>. Returns <tt>"null"</tt> if <tt>a</tt>
14.3518 + * is <tt>null</tt>.
14.3519 + *
14.3520 + * @param a the array whose string representation to return
14.3521 + * @return a string representation of <tt>a</tt>
14.3522 + * @since 1.5
14.3523 + */
14.3524 + public static String toString(double[] a) {
14.3525 + if (a == null)
14.3526 + return "null";
14.3527 + int iMax = a.length - 1;
14.3528 + if (iMax == -1)
14.3529 + return "[]";
14.3530 +
14.3531 + StringBuilder b = new StringBuilder();
14.3532 + b.append('[');
14.3533 + for (int i = 0; ; i++) {
14.3534 + b.append(a[i]);
14.3535 + if (i == iMax)
14.3536 + return b.append(']').toString();
14.3537 + b.append(", ");
14.3538 + }
14.3539 + }
14.3540 +
14.3541 + /**
14.3542 + * Returns a string representation of the contents of the specified array.
14.3543 + * If the array contains other arrays as elements, they are converted to
14.3544 + * strings by the {@link Object#toString} method inherited from
14.3545 + * <tt>Object</tt>, which describes their <i>identities</i> rather than
14.3546 + * their contents.
14.3547 + *
14.3548 + * <p>The value returned by this method is equal to the value that would
14.3549 + * be returned by <tt>Arrays.asList(a).toString()</tt>, unless <tt>a</tt>
14.3550 + * is <tt>null</tt>, in which case <tt>"null"</tt> is returned.
14.3551 + *
14.3552 + * @param a the array whose string representation to return
14.3553 + * @return a string representation of <tt>a</tt>
14.3554 + * @see #deepToString(Object[])
14.3555 + * @since 1.5
14.3556 + */
14.3557 + public static String toString(Object[] a) {
14.3558 + if (a == null)
14.3559 + return "null";
14.3560 +
14.3561 + int iMax = a.length - 1;
14.3562 + if (iMax == -1)
14.3563 + return "[]";
14.3564 +
14.3565 + StringBuilder b = new StringBuilder();
14.3566 + b.append('[');
14.3567 + for (int i = 0; ; i++) {
14.3568 + b.append(String.valueOf(a[i]));
14.3569 + if (i == iMax)
14.3570 + return b.append(']').toString();
14.3571 + b.append(", ");
14.3572 + }
14.3573 + }
14.3574 +
14.3575 + /**
14.3576 + * Returns a string representation of the "deep contents" of the specified
14.3577 + * array. If the array contains other arrays as elements, the string
14.3578 + * representation contains their contents and so on. This method is
14.3579 + * designed for converting multidimensional arrays to strings.
14.3580 + *
14.3581 + * <p>The string representation consists of a list of the array's
14.3582 + * elements, enclosed in square brackets (<tt>"[]"</tt>). Adjacent
14.3583 + * elements are separated by the characters <tt>", "</tt> (a comma
14.3584 + * followed by a space). Elements are converted to strings as by
14.3585 + * <tt>String.valueOf(Object)</tt>, unless they are themselves
14.3586 + * arrays.
14.3587 + *
14.3588 + * <p>If an element <tt>e</tt> is an array of a primitive type, it is
14.3589 + * converted to a string as by invoking the appropriate overloading of
14.3590 + * <tt>Arrays.toString(e)</tt>. If an element <tt>e</tt> is an array of a
14.3591 + * reference type, it is converted to a string as by invoking
14.3592 + * this method recursively.
14.3593 + *
14.3594 + * <p>To avoid infinite recursion, if the specified array contains itself
14.3595 + * as an element, or contains an indirect reference to itself through one
14.3596 + * or more levels of arrays, the self-reference is converted to the string
14.3597 + * <tt>"[...]"</tt>. For example, an array containing only a reference
14.3598 + * to itself would be rendered as <tt>"[[...]]"</tt>.
14.3599 + *
14.3600 + * <p>This method returns <tt>"null"</tt> if the specified array
14.3601 + * is <tt>null</tt>.
14.3602 + *
14.3603 + * @param a the array whose string representation to return
14.3604 + * @return a string representation of <tt>a</tt>
14.3605 + * @see #toString(Object[])
14.3606 + * @since 1.5
14.3607 + */
14.3608 + public static String deepToString(Object[] a) {
14.3609 + if (a == null)
14.3610 + return "null";
14.3611 +
14.3612 + int bufLen = 20 * a.length;
14.3613 + if (a.length != 0 && bufLen <= 0)
14.3614 + bufLen = Integer.MAX_VALUE;
14.3615 + StringBuilder buf = new StringBuilder(bufLen);
14.3616 + deepToString(a, buf, new HashSet<Object[]>());
14.3617 + return buf.toString();
14.3618 + }
14.3619 +
14.3620 + private static void deepToString(Object[] a, StringBuilder buf,
14.3621 + Set<Object[]> dejaVu) {
14.3622 + if (a == null) {
14.3623 + buf.append("null");
14.3624 + return;
14.3625 + }
14.3626 + int iMax = a.length - 1;
14.3627 + if (iMax == -1) {
14.3628 + buf.append("[]");
14.3629 + return;
14.3630 + }
14.3631 +
14.3632 + dejaVu.add(a);
14.3633 + buf.append('[');
14.3634 + for (int i = 0; ; i++) {
14.3635 +
14.3636 + Object element = a[i];
14.3637 + if (element == null) {
14.3638 + buf.append("null");
14.3639 + } else {
14.3640 + Class eClass = element.getClass();
14.3641 +
14.3642 + if (eClass.isArray()) {
14.3643 + if (eClass == byte[].class)
14.3644 + buf.append(toString((byte[]) element));
14.3645 + else if (eClass == short[].class)
14.3646 + buf.append(toString((short[]) element));
14.3647 + else if (eClass == int[].class)
14.3648 + buf.append(toString((int[]) element));
14.3649 + else if (eClass == long[].class)
14.3650 + buf.append(toString((long[]) element));
14.3651 + else if (eClass == char[].class)
14.3652 + buf.append(toString((char[]) element));
14.3653 + else if (eClass == float[].class)
14.3654 + buf.append(toString((float[]) element));
14.3655 + else if (eClass == double[].class)
14.3656 + buf.append(toString((double[]) element));
14.3657 + else if (eClass == boolean[].class)
14.3658 + buf.append(toString((boolean[]) element));
14.3659 + else { // element is an array of object references
14.3660 + if (dejaVu.contains(element))
14.3661 + buf.append("[...]");
14.3662 + else
14.3663 + deepToString((Object[])element, buf, dejaVu);
14.3664 + }
14.3665 + } else { // element is non-null and not an array
14.3666 + buf.append(element.toString());
14.3667 + }
14.3668 + }
14.3669 + if (i == iMax)
14.3670 + break;
14.3671 + buf.append(", ");
14.3672 + }
14.3673 + buf.append(']');
14.3674 + dejaVu.remove(a);
14.3675 + }
14.3676 +}
15.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
15.2 +++ b/emul/compact/src/main/java/java/util/Collection.java Wed Jan 23 22:33:45 2013 +0100
15.3 @@ -0,0 +1,456 @@
15.4 +/*
15.5 + * Copyright (c) 1997, 2010, 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 + * The root interface in the <i>collection hierarchy</i>. A collection
15.33 + * represents a group of objects, known as its <i>elements</i>. Some
15.34 + * collections allow duplicate elements and others do not. Some are ordered
15.35 + * and others unordered. The JDK does not provide any <i>direct</i>
15.36 + * implementations of this interface: it provides implementations of more
15.37 + * specific subinterfaces like <tt>Set</tt> and <tt>List</tt>. This interface
15.38 + * is typically used to pass collections around and manipulate them where
15.39 + * maximum generality is desired.
15.40 + *
15.41 + * <p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain
15.42 + * duplicate elements) should implement this interface directly.
15.43 + *
15.44 + * <p>All general-purpose <tt>Collection</tt> implementation classes (which
15.45 + * typically implement <tt>Collection</tt> indirectly through one of its
15.46 + * subinterfaces) should provide two "standard" constructors: a void (no
15.47 + * arguments) constructor, which creates an empty collection, and a
15.48 + * constructor with a single argument of type <tt>Collection</tt>, which
15.49 + * creates a new collection with the same elements as its argument. In
15.50 + * effect, the latter constructor allows the user to copy any collection,
15.51 + * producing an equivalent collection of the desired implementation type.
15.52 + * There is no way to enforce this convention (as interfaces cannot contain
15.53 + * constructors) but all of the general-purpose <tt>Collection</tt>
15.54 + * implementations in the Java platform libraries comply.
15.55 + *
15.56 + * <p>The "destructive" methods contained in this interface, that is, the
15.57 + * methods that modify the collection on which they operate, are specified to
15.58 + * throw <tt>UnsupportedOperationException</tt> if this collection does not
15.59 + * support the operation. If this is the case, these methods may, but are not
15.60 + * required to, throw an <tt>UnsupportedOperationException</tt> if the
15.61 + * invocation would have no effect on the collection. For example, invoking
15.62 + * the {@link #addAll(Collection)} method on an unmodifiable collection may,
15.63 + * but is not required to, throw the exception if the collection to be added
15.64 + * is empty.
15.65 + *
15.66 + * <p><a name="optional-restrictions"/>
15.67 + * Some collection implementations have restrictions on the elements that
15.68 + * they may contain. For example, some implementations prohibit null elements,
15.69 + * and some have restrictions on the types of their elements. Attempting to
15.70 + * add an ineligible element throws an unchecked exception, typically
15.71 + * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting
15.72 + * to query the presence of an ineligible element may throw an exception,
15.73 + * or it may simply return false; some implementations will exhibit the former
15.74 + * behavior and some will exhibit the latter. More generally, attempting an
15.75 + * operation on an ineligible element whose completion would not result in
15.76 + * the insertion of an ineligible element into the collection may throw an
15.77 + * exception or it may succeed, at the option of the implementation.
15.78 + * Such exceptions are marked as "optional" in the specification for this
15.79 + * interface.
15.80 + *
15.81 + * <p>It is up to each collection to determine its own synchronization
15.82 + * policy. In the absence of a stronger guarantee by the
15.83 + * implementation, undefined behavior may result from the invocation
15.84 + * of any method on a collection that is being mutated by another
15.85 + * thread; this includes direct invocations, passing the collection to
15.86 + * a method that might perform invocations, and using an existing
15.87 + * iterator to examine the collection.
15.88 + *
15.89 + * <p>Many methods in Collections Framework interfaces are defined in
15.90 + * terms of the {@link Object#equals(Object) equals} method. For example,
15.91 + * the specification for the {@link #contains(Object) contains(Object o)}
15.92 + * method says: "returns <tt>true</tt> if and only if this collection
15.93 + * contains at least one element <tt>e</tt> such that
15.94 + * <tt>(o==null ? e==null : o.equals(e))</tt>." This specification should
15.95 + * <i>not</i> be construed to imply that invoking <tt>Collection.contains</tt>
15.96 + * with a non-null argument <tt>o</tt> will cause <tt>o.equals(e)</tt> to be
15.97 + * invoked for any element <tt>e</tt>. Implementations are free to implement
15.98 + * optimizations whereby the <tt>equals</tt> invocation is avoided, for
15.99 + * example, by first comparing the hash codes of the two elements. (The
15.100 + * {@link Object#hashCode()} specification guarantees that two objects with
15.101 + * unequal hash codes cannot be equal.) More generally, implementations of
15.102 + * the various Collections Framework interfaces are free to take advantage of
15.103 + * the specified behavior of underlying {@link Object} methods wherever the
15.104 + * implementor deems it appropriate.
15.105 + *
15.106 + * <p>This interface is a member of the
15.107 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
15.108 + * Java Collections Framework</a>.
15.109 + *
15.110 + * @param <E> the type of elements in this collection
15.111 + *
15.112 + * @author Josh Bloch
15.113 + * @author Neal Gafter
15.114 + * @see Set
15.115 + * @see List
15.116 + * @see Map
15.117 + * @see SortedSet
15.118 + * @see SortedMap
15.119 + * @see HashSet
15.120 + * @see TreeSet
15.121 + * @see ArrayList
15.122 + * @see LinkedList
15.123 + * @see Vector
15.124 + * @see Collections
15.125 + * @see Arrays
15.126 + * @see AbstractCollection
15.127 + * @since 1.2
15.128 + */
15.129 +
15.130 +public interface Collection<E> extends Iterable<E> {
15.131 + // Query Operations
15.132 +
15.133 + /**
15.134 + * Returns the number of elements in this collection. If this collection
15.135 + * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
15.136 + * <tt>Integer.MAX_VALUE</tt>.
15.137 + *
15.138 + * @return the number of elements in this collection
15.139 + */
15.140 + int size();
15.141 +
15.142 + /**
15.143 + * Returns <tt>true</tt> if this collection contains no elements.
15.144 + *
15.145 + * @return <tt>true</tt> if this collection contains no elements
15.146 + */
15.147 + boolean isEmpty();
15.148 +
15.149 + /**
15.150 + * Returns <tt>true</tt> if this collection contains the specified element.
15.151 + * More formally, returns <tt>true</tt> if and only if this collection
15.152 + * contains at least one element <tt>e</tt> such that
15.153 + * <tt>(o==null ? e==null : o.equals(e))</tt>.
15.154 + *
15.155 + * @param o element whose presence in this collection is to be tested
15.156 + * @return <tt>true</tt> if this collection contains the specified
15.157 + * element
15.158 + * @throws ClassCastException if the type of the specified element
15.159 + * is incompatible with this collection
15.160 + * (<a href="#optional-restrictions">optional</a>)
15.161 + * @throws NullPointerException if the specified element is null and this
15.162 + * collection does not permit null elements
15.163 + * (<a href="#optional-restrictions">optional</a>)
15.164 + */
15.165 + boolean contains(Object o);
15.166 +
15.167 + /**
15.168 + * Returns an iterator over the elements in this collection. There are no
15.169 + * guarantees concerning the order in which the elements are returned
15.170 + * (unless this collection is an instance of some class that provides a
15.171 + * guarantee).
15.172 + *
15.173 + * @return an <tt>Iterator</tt> over the elements in this collection
15.174 + */
15.175 + Iterator<E> iterator();
15.176 +
15.177 + /**
15.178 + * Returns an array containing all of the elements in this collection.
15.179 + * If this collection makes any guarantees as to what order its elements
15.180 + * are returned by its iterator, this method must return the elements in
15.181 + * the same order.
15.182 + *
15.183 + * <p>The returned array will be "safe" in that no references to it are
15.184 + * maintained by this collection. (In other words, this method must
15.185 + * allocate a new array even if this collection is backed by an array).
15.186 + * The caller is thus free to modify the returned array.
15.187 + *
15.188 + * <p>This method acts as bridge between array-based and collection-based
15.189 + * APIs.
15.190 + *
15.191 + * @return an array containing all of the elements in this collection
15.192 + */
15.193 + Object[] toArray();
15.194 +
15.195 + /**
15.196 + * Returns an array containing all of the elements in this collection;
15.197 + * the runtime type of the returned array is that of the specified array.
15.198 + * If the collection fits in the specified array, it is returned therein.
15.199 + * Otherwise, a new array is allocated with the runtime type of the
15.200 + * specified array and the size of this collection.
15.201 + *
15.202 + * <p>If this collection fits in the specified array with room to spare
15.203 + * (i.e., the array has more elements than this collection), the element
15.204 + * in the array immediately following the end of the collection is set to
15.205 + * <tt>null</tt>. (This is useful in determining the length of this
15.206 + * collection <i>only</i> if the caller knows that this collection does
15.207 + * not contain any <tt>null</tt> elements.)
15.208 + *
15.209 + * <p>If this collection makes any guarantees as to what order its elements
15.210 + * are returned by its iterator, this method must return the elements in
15.211 + * the same order.
15.212 + *
15.213 + * <p>Like the {@link #toArray()} method, this method acts as bridge between
15.214 + * array-based and collection-based APIs. Further, this method allows
15.215 + * precise control over the runtime type of the output array, and may,
15.216 + * under certain circumstances, be used to save allocation costs.
15.217 + *
15.218 + * <p>Suppose <tt>x</tt> is a collection known to contain only strings.
15.219 + * The following code can be used to dump the collection into a newly
15.220 + * allocated array of <tt>String</tt>:
15.221 + *
15.222 + * <pre>
15.223 + * String[] y = x.toArray(new String[0]);</pre>
15.224 + *
15.225 + * Note that <tt>toArray(new Object[0])</tt> is identical in function to
15.226 + * <tt>toArray()</tt>.
15.227 + *
15.228 + * @param a the array into which the elements of this collection are to be
15.229 + * stored, if it is big enough; otherwise, a new array of the same
15.230 + * runtime type is allocated for this purpose.
15.231 + * @return an array containing all of the elements in this collection
15.232 + * @throws ArrayStoreException if the runtime type of the specified array
15.233 + * is not a supertype of the runtime type of every element in
15.234 + * this collection
15.235 + * @throws NullPointerException if the specified array is null
15.236 + */
15.237 + <T> T[] toArray(T[] a);
15.238 +
15.239 + // Modification Operations
15.240 +
15.241 + /**
15.242 + * Ensures that this collection contains the specified element (optional
15.243 + * operation). Returns <tt>true</tt> if this collection changed as a
15.244 + * result of the call. (Returns <tt>false</tt> if this collection does
15.245 + * not permit duplicates and already contains the specified element.)<p>
15.246 + *
15.247 + * Collections that support this operation may place limitations on what
15.248 + * elements may be added to this collection. In particular, some
15.249 + * collections will refuse to add <tt>null</tt> elements, and others will
15.250 + * impose restrictions on the type of elements that may be added.
15.251 + * Collection classes should clearly specify in their documentation any
15.252 + * restrictions on what elements may be added.<p>
15.253 + *
15.254 + * If a collection refuses to add a particular element for any reason
15.255 + * other than that it already contains the element, it <i>must</i> throw
15.256 + * an exception (rather than returning <tt>false</tt>). This preserves
15.257 + * the invariant that a collection always contains the specified element
15.258 + * after this call returns.
15.259 + *
15.260 + * @param e element whose presence in this collection is to be ensured
15.261 + * @return <tt>true</tt> if this collection changed as a result of the
15.262 + * call
15.263 + * @throws UnsupportedOperationException if the <tt>add</tt> operation
15.264 + * is not supported by this collection
15.265 + * @throws ClassCastException if the class of the specified element
15.266 + * prevents it from being added to this collection
15.267 + * @throws NullPointerException if the specified element is null and this
15.268 + * collection does not permit null elements
15.269 + * @throws IllegalArgumentException if some property of the element
15.270 + * prevents it from being added to this collection
15.271 + * @throws IllegalStateException if the element cannot be added at this
15.272 + * time due to insertion restrictions
15.273 + */
15.274 + boolean add(E e);
15.275 +
15.276 + /**
15.277 + * Removes a single instance of the specified element from this
15.278 + * collection, if it is present (optional operation). More formally,
15.279 + * removes an element <tt>e</tt> such that
15.280 + * <tt>(o==null ? e==null : o.equals(e))</tt>, if
15.281 + * this collection contains one or more such elements. Returns
15.282 + * <tt>true</tt> if this collection contained the specified element (or
15.283 + * equivalently, if this collection changed as a result of the call).
15.284 + *
15.285 + * @param o element to be removed from this collection, if present
15.286 + * @return <tt>true</tt> if an element was removed as a result of this call
15.287 + * @throws ClassCastException if the type of the specified element
15.288 + * is incompatible with this collection
15.289 + * (<a href="#optional-restrictions">optional</a>)
15.290 + * @throws NullPointerException if the specified element is null and this
15.291 + * collection does not permit null elements
15.292 + * (<a href="#optional-restrictions">optional</a>)
15.293 + * @throws UnsupportedOperationException if the <tt>remove</tt> operation
15.294 + * is not supported by this collection
15.295 + */
15.296 + boolean remove(Object o);
15.297 +
15.298 +
15.299 + // Bulk Operations
15.300 +
15.301 + /**
15.302 + * Returns <tt>true</tt> if this collection contains all of the elements
15.303 + * in the specified collection.
15.304 + *
15.305 + * @param c collection to be checked for containment in this collection
15.306 + * @return <tt>true</tt> if this collection contains all of the elements
15.307 + * in the specified collection
15.308 + * @throws ClassCastException if the types of one or more elements
15.309 + * in the specified collection are incompatible with this
15.310 + * collection
15.311 + * (<a href="#optional-restrictions">optional</a>)
15.312 + * @throws NullPointerException if the specified collection contains one
15.313 + * or more null elements and this collection does not permit null
15.314 + * elements
15.315 + * (<a href="#optional-restrictions">optional</a>),
15.316 + * or if the specified collection is null.
15.317 + * @see #contains(Object)
15.318 + */
15.319 + boolean containsAll(Collection<?> c);
15.320 +
15.321 + /**
15.322 + * Adds all of the elements in the specified collection to this collection
15.323 + * (optional operation). The behavior of this operation is undefined if
15.324 + * the specified collection is modified while the operation is in progress.
15.325 + * (This implies that the behavior of this call is undefined if the
15.326 + * specified collection is this collection, and this collection is
15.327 + * nonempty.)
15.328 + *
15.329 + * @param c collection containing elements to be added to this collection
15.330 + * @return <tt>true</tt> if this collection changed as a result of the call
15.331 + * @throws UnsupportedOperationException if the <tt>addAll</tt> operation
15.332 + * is not supported by this collection
15.333 + * @throws ClassCastException if the class of an element of the specified
15.334 + * collection prevents it from being added to this collection
15.335 + * @throws NullPointerException if the specified collection contains a
15.336 + * null element and this collection does not permit null elements,
15.337 + * or if the specified collection is null
15.338 + * @throws IllegalArgumentException if some property of an element of the
15.339 + * specified collection prevents it from being added to this
15.340 + * collection
15.341 + * @throws IllegalStateException if not all the elements can be added at
15.342 + * this time due to insertion restrictions
15.343 + * @see #add(Object)
15.344 + */
15.345 + boolean addAll(Collection<? extends E> c);
15.346 +
15.347 + /**
15.348 + * Removes all of this collection's elements that are also contained in the
15.349 + * specified collection (optional operation). After this call returns,
15.350 + * this collection will contain no elements in common with the specified
15.351 + * collection.
15.352 + *
15.353 + * @param c collection containing elements to be removed from this collection
15.354 + * @return <tt>true</tt> if this collection changed as a result of the
15.355 + * call
15.356 + * @throws UnsupportedOperationException if the <tt>removeAll</tt> method
15.357 + * is not supported by this collection
15.358 + * @throws ClassCastException if the types of one or more elements
15.359 + * in this collection are incompatible with the specified
15.360 + * collection
15.361 + * (<a href="#optional-restrictions">optional</a>)
15.362 + * @throws NullPointerException if this collection contains one or more
15.363 + * null elements and the specified collection does not support
15.364 + * null elements
15.365 + * (<a href="#optional-restrictions">optional</a>),
15.366 + * or if the specified collection is null
15.367 + * @see #remove(Object)
15.368 + * @see #contains(Object)
15.369 + */
15.370 + boolean removeAll(Collection<?> c);
15.371 +
15.372 + /**
15.373 + * Retains only the elements in this collection that are contained in the
15.374 + * specified collection (optional operation). In other words, removes from
15.375 + * this collection all of its elements that are not contained in the
15.376 + * specified collection.
15.377 + *
15.378 + * @param c collection containing elements to be retained in this collection
15.379 + * @return <tt>true</tt> if this collection changed as a result of the call
15.380 + * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
15.381 + * is not supported by this collection
15.382 + * @throws ClassCastException if the types of one or more elements
15.383 + * in this collection are incompatible with the specified
15.384 + * collection
15.385 + * (<a href="#optional-restrictions">optional</a>)
15.386 + * @throws NullPointerException if this collection contains one or more
15.387 + * null elements and the specified collection does not permit null
15.388 + * elements
15.389 + * (<a href="#optional-restrictions">optional</a>),
15.390 + * or if the specified collection is null
15.391 + * @see #remove(Object)
15.392 + * @see #contains(Object)
15.393 + */
15.394 + boolean retainAll(Collection<?> c);
15.395 +
15.396 + /**
15.397 + * Removes all of the elements from this collection (optional operation).
15.398 + * The collection will be empty after this method returns.
15.399 + *
15.400 + * @throws UnsupportedOperationException if the <tt>clear</tt> operation
15.401 + * is not supported by this collection
15.402 + */
15.403 + void clear();
15.404 +
15.405 +
15.406 + // Comparison and hashing
15.407 +
15.408 + /**
15.409 + * Compares the specified object with this collection for equality. <p>
15.410 + *
15.411 + * While the <tt>Collection</tt> interface adds no stipulations to the
15.412 + * general contract for the <tt>Object.equals</tt>, programmers who
15.413 + * implement the <tt>Collection</tt> interface "directly" (in other words,
15.414 + * create a class that is a <tt>Collection</tt> but is not a <tt>Set</tt>
15.415 + * or a <tt>List</tt>) must exercise care if they choose to override the
15.416 + * <tt>Object.equals</tt>. It is not necessary to do so, and the simplest
15.417 + * course of action is to rely on <tt>Object</tt>'s implementation, but
15.418 + * the implementor may wish to implement a "value comparison" in place of
15.419 + * the default "reference comparison." (The <tt>List</tt> and
15.420 + * <tt>Set</tt> interfaces mandate such value comparisons.)<p>
15.421 + *
15.422 + * The general contract for the <tt>Object.equals</tt> method states that
15.423 + * equals must be symmetric (in other words, <tt>a.equals(b)</tt> if and
15.424 + * only if <tt>b.equals(a)</tt>). The contracts for <tt>List.equals</tt>
15.425 + * and <tt>Set.equals</tt> state that lists are only equal to other lists,
15.426 + * and sets to other sets. Thus, a custom <tt>equals</tt> method for a
15.427 + * collection class that implements neither the <tt>List</tt> nor
15.428 + * <tt>Set</tt> interface must return <tt>false</tt> when this collection
15.429 + * is compared to any list or set. (By the same logic, it is not possible
15.430 + * to write a class that correctly implements both the <tt>Set</tt> and
15.431 + * <tt>List</tt> interfaces.)
15.432 + *
15.433 + * @param o object to be compared for equality with this collection
15.434 + * @return <tt>true</tt> if the specified object is equal to this
15.435 + * collection
15.436 + *
15.437 + * @see Object#equals(Object)
15.438 + * @see Set#equals(Object)
15.439 + * @see List#equals(Object)
15.440 + */
15.441 + boolean equals(Object o);
15.442 +
15.443 + /**
15.444 + * Returns the hash code value for this collection. While the
15.445 + * <tt>Collection</tt> interface adds no stipulations to the general
15.446 + * contract for the <tt>Object.hashCode</tt> method, programmers should
15.447 + * take note that any class that overrides the <tt>Object.equals</tt>
15.448 + * method must also override the <tt>Object.hashCode</tt> method in order
15.449 + * to satisfy the general contract for the <tt>Object.hashCode</tt> method.
15.450 + * In particular, <tt>c1.equals(c2)</tt> implies that
15.451 + * <tt>c1.hashCode()==c2.hashCode()</tt>.
15.452 + *
15.453 + * @return the hash code value for this collection
15.454 + *
15.455 + * @see Object#hashCode()
15.456 + * @see Object#equals(Object)
15.457 + */
15.458 + int hashCode();
15.459 +}
16.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
16.2 +++ b/emul/compact/src/main/java/java/util/ConcurrentModificationException.java Wed Jan 23 22:33:45 2013 +0100
16.3 @@ -0,0 +1,123 @@
16.4 +/*
16.5 + * Copyright (c) 1997, 2010, 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 + * This exception may be thrown by methods that have detected concurrent
16.33 + * modification of an object when such modification is not permissible.
16.34 + * <p>
16.35 + * For example, it is not generally permissible for one thread to modify a Collection
16.36 + * while another thread is iterating over it. In general, the results of the
16.37 + * iteration are undefined under these circumstances. Some Iterator
16.38 + * implementations (including those of all the general purpose collection implementations
16.39 + * provided by the JRE) may choose to throw this exception if this behavior is
16.40 + * detected. Iterators that do this are known as <i>fail-fast</i> iterators,
16.41 + * as they fail quickly and cleanly, rather that risking arbitrary,
16.42 + * non-deterministic behavior at an undetermined time in the future.
16.43 + * <p>
16.44 + * Note that this exception does not always indicate that an object has
16.45 + * been concurrently modified by a <i>different</i> thread. If a single
16.46 + * thread issues a sequence of method invocations that violates the
16.47 + * contract of an object, the object may throw this exception. For
16.48 + * example, if a thread modifies a collection directly while it is
16.49 + * iterating over the collection with a fail-fast iterator, the iterator
16.50 + * will throw this exception.
16.51 + *
16.52 + * <p>Note that fail-fast behavior cannot be guaranteed as it is, generally
16.53 + * speaking, impossible to make any hard guarantees in the presence of
16.54 + * unsynchronized concurrent modification. Fail-fast operations
16.55 + * throw {@code ConcurrentModificationException} on a best-effort basis.
16.56 + * Therefore, it would be wrong to write a program that depended on this
16.57 + * exception for its correctness: <i>{@code ConcurrentModificationException}
16.58 + * should be used only to detect bugs.</i>
16.59 + *
16.60 + * @author Josh Bloch
16.61 + * @see Collection
16.62 + * @see Iterator
16.63 + * @see ListIterator
16.64 + * @see Vector
16.65 + * @see LinkedList
16.66 + * @see HashSet
16.67 + * @see Hashtable
16.68 + * @see TreeMap
16.69 + * @see AbstractList
16.70 + * @since 1.2
16.71 + */
16.72 +public class ConcurrentModificationException extends RuntimeException {
16.73 + private static final long serialVersionUID = -3666751008965953603L;
16.74 +
16.75 + /**
16.76 + * Constructs a ConcurrentModificationException with no
16.77 + * detail message.
16.78 + */
16.79 + public ConcurrentModificationException() {
16.80 + }
16.81 +
16.82 + /**
16.83 + * Constructs a {@code ConcurrentModificationException} with the
16.84 + * specified detail message.
16.85 + *
16.86 + * @param message the detail message pertaining to this exception.
16.87 + */
16.88 + public ConcurrentModificationException(String message) {
16.89 + super(message);
16.90 + }
16.91 +
16.92 + /**
16.93 + * Constructs a new exception with the specified cause and a detail
16.94 + * message of {@code (cause==null ? null : cause.toString())} (which
16.95 + * typically contains the class and detail message of {@code cause}.
16.96 + *
16.97 + * @param cause the cause (which is saved for later retrieval by the
16.98 + * {@link Throwable#getCause()} method). (A {@code null} value is
16.99 + * permitted, and indicates that the cause is nonexistent or
16.100 + * unknown.)
16.101 + * @since 1.7
16.102 + */
16.103 + public ConcurrentModificationException(Throwable cause) {
16.104 + super(cause);
16.105 + }
16.106 +
16.107 + /**
16.108 + * Constructs a new exception with the specified detail message and
16.109 + * cause.
16.110 + *
16.111 + * <p>Note that the detail message associated with <code>cause</code> is
16.112 + * <i>not</i> automatically incorporated in this exception's detail
16.113 + * message.
16.114 + *
16.115 + * @param message the detail message (which is saved for later retrieval
16.116 + * by the {@link Throwable#getMessage()} method).
16.117 + * @param cause the cause (which is saved for later retrieval by the
16.118 + * {@link Throwable#getCause()} method). (A {@code null} value
16.119 + * is permitted, and indicates that the cause is nonexistent or
16.120 + * unknown.)
16.121 + * @since 1.7
16.122 + */
16.123 + public ConcurrentModificationException(String message, Throwable cause) {
16.124 + super(message, cause);
16.125 + }
16.126 +}
17.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
17.2 +++ b/emul/compact/src/main/java/java/util/HashMap.java Wed Jan 23 22:33:45 2013 +0100
17.3 @@ -0,0 +1,1051 @@
17.4 +/*
17.5 + * Copyright (c) 1997, 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 +import java.io.*;
17.31 +
17.32 +/**
17.33 + * Hash table based implementation of the <tt>Map</tt> interface. This
17.34 + * implementation provides all of the optional map operations, and permits
17.35 + * <tt>null</tt> values and the <tt>null</tt> key. (The <tt>HashMap</tt>
17.36 + * class is roughly equivalent to <tt>Hashtable</tt>, except that it is
17.37 + * unsynchronized and permits nulls.) This class makes no guarantees as to
17.38 + * the order of the map; in particular, it does not guarantee that the order
17.39 + * will remain constant over time.
17.40 + *
17.41 + * <p>This implementation provides constant-time performance for the basic
17.42 + * operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function
17.43 + * disperses the elements properly among the buckets. Iteration over
17.44 + * collection views requires time proportional to the "capacity" of the
17.45 + * <tt>HashMap</tt> instance (the number of buckets) plus its size (the number
17.46 + * of key-value mappings). Thus, it's very important not to set the initial
17.47 + * capacity too high (or the load factor too low) if iteration performance is
17.48 + * important.
17.49 + *
17.50 + * <p>An instance of <tt>HashMap</tt> has two parameters that affect its
17.51 + * performance: <i>initial capacity</i> and <i>load factor</i>. The
17.52 + * <i>capacity</i> is the number of buckets in the hash table, and the initial
17.53 + * capacity is simply the capacity at the time the hash table is created. The
17.54 + * <i>load factor</i> is a measure of how full the hash table is allowed to
17.55 + * get before its capacity is automatically increased. When the number of
17.56 + * entries in the hash table exceeds the product of the load factor and the
17.57 + * current capacity, the hash table is <i>rehashed</i> (that is, internal data
17.58 + * structures are rebuilt) so that the hash table has approximately twice the
17.59 + * number of buckets.
17.60 + *
17.61 + * <p>As a general rule, the default load factor (.75) offers a good tradeoff
17.62 + * between time and space costs. Higher values decrease the space overhead
17.63 + * but increase the lookup cost (reflected in most of the operations of the
17.64 + * <tt>HashMap</tt> class, including <tt>get</tt> and <tt>put</tt>). The
17.65 + * expected number of entries in the map and its load factor should be taken
17.66 + * into account when setting its initial capacity, so as to minimize the
17.67 + * number of rehash operations. If the initial capacity is greater
17.68 + * than the maximum number of entries divided by the load factor, no
17.69 + * rehash operations will ever occur.
17.70 + *
17.71 + * <p>If many mappings are to be stored in a <tt>HashMap</tt> instance,
17.72 + * creating it with a sufficiently large capacity will allow the mappings to
17.73 + * be stored more efficiently than letting it perform automatic rehashing as
17.74 + * needed to grow the table.
17.75 + *
17.76 + * <p><strong>Note that this implementation is not synchronized.</strong>
17.77 + * If multiple threads access a hash map concurrently, and at least one of
17.78 + * the threads modifies the map structurally, it <i>must</i> be
17.79 + * synchronized externally. (A structural modification is any operation
17.80 + * that adds or deletes one or more mappings; merely changing the value
17.81 + * associated with a key that an instance already contains is not a
17.82 + * structural modification.) This is typically accomplished by
17.83 + * synchronizing on some object that naturally encapsulates the map.
17.84 + *
17.85 + * If no such object exists, the map should be "wrapped" using the
17.86 + * {@link Collections#synchronizedMap Collections.synchronizedMap}
17.87 + * method. This is best done at creation time, to prevent accidental
17.88 + * unsynchronized access to the map:<pre>
17.89 + * Map m = Collections.synchronizedMap(new HashMap(...));</pre>
17.90 + *
17.91 + * <p>The iterators returned by all of this class's "collection view methods"
17.92 + * are <i>fail-fast</i>: if the map is structurally modified at any time after
17.93 + * the iterator is created, in any way except through the iterator's own
17.94 + * <tt>remove</tt> method, the iterator will throw a
17.95 + * {@link ConcurrentModificationException}. Thus, in the face of concurrent
17.96 + * modification, the iterator fails quickly and cleanly, rather than risking
17.97 + * arbitrary, non-deterministic behavior at an undetermined time in the
17.98 + * future.
17.99 + *
17.100 + * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
17.101 + * as it is, generally speaking, impossible to make any hard guarantees in the
17.102 + * presence of unsynchronized concurrent modification. Fail-fast iterators
17.103 + * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
17.104 + * Therefore, it would be wrong to write a program that depended on this
17.105 + * exception for its correctness: <i>the fail-fast behavior of iterators
17.106 + * should be used only to detect bugs.</i>
17.107 + *
17.108 + * <p>This class is a member of the
17.109 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
17.110 + * Java Collections Framework</a>.
17.111 + *
17.112 + * @param <K> the type of keys maintained by this map
17.113 + * @param <V> the type of mapped values
17.114 + *
17.115 + * @author Doug Lea
17.116 + * @author Josh Bloch
17.117 + * @author Arthur van Hoff
17.118 + * @author Neal Gafter
17.119 + * @see Object#hashCode()
17.120 + * @see Collection
17.121 + * @see Map
17.122 + * @see TreeMap
17.123 + * @see Hashtable
17.124 + * @since 1.2
17.125 + */
17.126 +
17.127 +public class HashMap<K,V>
17.128 + extends AbstractMap<K,V>
17.129 + implements Map<K,V>, Cloneable, Serializable
17.130 +{
17.131 +
17.132 + /**
17.133 + * The default initial capacity - MUST be a power of two.
17.134 + */
17.135 + static final int DEFAULT_INITIAL_CAPACITY = 16;
17.136 +
17.137 + /**
17.138 + * The maximum capacity, used if a higher value is implicitly specified
17.139 + * by either of the constructors with arguments.
17.140 + * MUST be a power of two <= 1<<30.
17.141 + */
17.142 + static final int MAXIMUM_CAPACITY = 1 << 30;
17.143 +
17.144 + /**
17.145 + * The load factor used when none specified in constructor.
17.146 + */
17.147 + static final float DEFAULT_LOAD_FACTOR = 0.75f;
17.148 +
17.149 + /**
17.150 + * The table, resized as necessary. Length MUST Always be a power of two.
17.151 + */
17.152 + transient Entry[] table;
17.153 +
17.154 + /**
17.155 + * The number of key-value mappings contained in this map.
17.156 + */
17.157 + transient int size;
17.158 +
17.159 + /**
17.160 + * The next size value at which to resize (capacity * load factor).
17.161 + * @serial
17.162 + */
17.163 + int threshold;
17.164 +
17.165 + /**
17.166 + * The load factor for the hash table.
17.167 + *
17.168 + * @serial
17.169 + */
17.170 + final float loadFactor;
17.171 +
17.172 + /**
17.173 + * The number of times this HashMap has been structurally modified
17.174 + * Structural modifications are those that change the number of mappings in
17.175 + * the HashMap or otherwise modify its internal structure (e.g.,
17.176 + * rehash). This field is used to make iterators on Collection-views of
17.177 + * the HashMap fail-fast. (See ConcurrentModificationException).
17.178 + */
17.179 + transient int modCount;
17.180 +
17.181 + /**
17.182 + * Constructs an empty <tt>HashMap</tt> with the specified initial
17.183 + * capacity and load factor.
17.184 + *
17.185 + * @param initialCapacity the initial capacity
17.186 + * @param loadFactor the load factor
17.187 + * @throws IllegalArgumentException if the initial capacity is negative
17.188 + * or the load factor is nonpositive
17.189 + */
17.190 + public HashMap(int initialCapacity, float loadFactor) {
17.191 + if (initialCapacity < 0)
17.192 + throw new IllegalArgumentException("Illegal initial capacity: " +
17.193 + initialCapacity);
17.194 + if (initialCapacity > MAXIMUM_CAPACITY)
17.195 + initialCapacity = MAXIMUM_CAPACITY;
17.196 + if (loadFactor <= 0 || Float.isNaN(loadFactor))
17.197 + throw new IllegalArgumentException("Illegal load factor: " +
17.198 + loadFactor);
17.199 +
17.200 + // Find a power of 2 >= initialCapacity
17.201 + int capacity = 1;
17.202 + while (capacity < initialCapacity)
17.203 + capacity <<= 1;
17.204 +
17.205 + this.loadFactor = loadFactor;
17.206 + threshold = (int)(capacity * loadFactor);
17.207 + table = new Entry[capacity];
17.208 + init();
17.209 + }
17.210 +
17.211 + /**
17.212 + * Constructs an empty <tt>HashMap</tt> with the specified initial
17.213 + * capacity and the default load factor (0.75).
17.214 + *
17.215 + * @param initialCapacity the initial capacity.
17.216 + * @throws IllegalArgumentException if the initial capacity is negative.
17.217 + */
17.218 + public HashMap(int initialCapacity) {
17.219 + this(initialCapacity, DEFAULT_LOAD_FACTOR);
17.220 + }
17.221 +
17.222 + /**
17.223 + * Constructs an empty <tt>HashMap</tt> with the default initial capacity
17.224 + * (16) and the default load factor (0.75).
17.225 + */
17.226 + public HashMap() {
17.227 + this.loadFactor = DEFAULT_LOAD_FACTOR;
17.228 + threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
17.229 + table = new Entry[DEFAULT_INITIAL_CAPACITY];
17.230 + init();
17.231 + }
17.232 +
17.233 + /**
17.234 + * Constructs a new <tt>HashMap</tt> with the same mappings as the
17.235 + * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
17.236 + * default load factor (0.75) and an initial capacity sufficient to
17.237 + * hold the mappings in the specified <tt>Map</tt>.
17.238 + *
17.239 + * @param m the map whose mappings are to be placed in this map
17.240 + * @throws NullPointerException if the specified map is null
17.241 + */
17.242 + public HashMap(Map<? extends K, ? extends V> m) {
17.243 + this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
17.244 + DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
17.245 + putAllForCreate(m);
17.246 + }
17.247 +
17.248 + // internal utilities
17.249 +
17.250 + /**
17.251 + * Initialization hook for subclasses. This method is called
17.252 + * in all constructors and pseudo-constructors (clone, readObject)
17.253 + * after HashMap has been initialized but before any entries have
17.254 + * been inserted. (In the absence of this method, readObject would
17.255 + * require explicit knowledge of subclasses.)
17.256 + */
17.257 + void init() {
17.258 + }
17.259 +
17.260 + /**
17.261 + * Applies a supplemental hash function to a given hashCode, which
17.262 + * defends against poor quality hash functions. This is critical
17.263 + * because HashMap uses power-of-two length hash tables, that
17.264 + * otherwise encounter collisions for hashCodes that do not differ
17.265 + * in lower bits. Note: Null keys always map to hash 0, thus index 0.
17.266 + */
17.267 + static int hash(int h) {
17.268 + // This function ensures that hashCodes that differ only by
17.269 + // constant multiples at each bit position have a bounded
17.270 + // number of collisions (approximately 8 at default load factor).
17.271 + h ^= (h >>> 20) ^ (h >>> 12);
17.272 + return h ^ (h >>> 7) ^ (h >>> 4);
17.273 + }
17.274 +
17.275 + /**
17.276 + * Returns index for hash code h.
17.277 + */
17.278 + static int indexFor(int h, int length) {
17.279 + return h & (length-1);
17.280 + }
17.281 +
17.282 + /**
17.283 + * Returns the number of key-value mappings in this map.
17.284 + *
17.285 + * @return the number of key-value mappings in this map
17.286 + */
17.287 + public int size() {
17.288 + return size;
17.289 + }
17.290 +
17.291 + /**
17.292 + * Returns <tt>true</tt> if this map contains no key-value mappings.
17.293 + *
17.294 + * @return <tt>true</tt> if this map contains no key-value mappings
17.295 + */
17.296 + public boolean isEmpty() {
17.297 + return size == 0;
17.298 + }
17.299 +
17.300 + /**
17.301 + * Returns the value to which the specified key is mapped,
17.302 + * or {@code null} if this map contains no mapping for the key.
17.303 + *
17.304 + * <p>More formally, if this map contains a mapping from a key
17.305 + * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
17.306 + * key.equals(k))}, then this method returns {@code v}; otherwise
17.307 + * it returns {@code null}. (There can be at most one such mapping.)
17.308 + *
17.309 + * <p>A return value of {@code null} does not <i>necessarily</i>
17.310 + * indicate that the map contains no mapping for the key; it's also
17.311 + * possible that the map explicitly maps the key to {@code null}.
17.312 + * The {@link #containsKey containsKey} operation may be used to
17.313 + * distinguish these two cases.
17.314 + *
17.315 + * @see #put(Object, Object)
17.316 + */
17.317 + public V get(Object key) {
17.318 + if (key == null)
17.319 + return getForNullKey();
17.320 + int hash = hash(key.hashCode());
17.321 + for (Entry<K,V> e = table[indexFor(hash, table.length)];
17.322 + e != null;
17.323 + e = e.next) {
17.324 + Object k;
17.325 + if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
17.326 + return e.value;
17.327 + }
17.328 + return null;
17.329 + }
17.330 +
17.331 + /**
17.332 + * Offloaded version of get() to look up null keys. Null keys map
17.333 + * to index 0. This null case is split out into separate methods
17.334 + * for the sake of performance in the two most commonly used
17.335 + * operations (get and put), but incorporated with conditionals in
17.336 + * others.
17.337 + */
17.338 + private V getForNullKey() {
17.339 + for (Entry<K,V> e = table[0]; e != null; e = e.next) {
17.340 + if (e.key == null)
17.341 + return e.value;
17.342 + }
17.343 + return null;
17.344 + }
17.345 +
17.346 + /**
17.347 + * Returns <tt>true</tt> if this map contains a mapping for the
17.348 + * specified key.
17.349 + *
17.350 + * @param key The key whose presence in this map is to be tested
17.351 + * @return <tt>true</tt> if this map contains a mapping for the specified
17.352 + * key.
17.353 + */
17.354 + public boolean containsKey(Object key) {
17.355 + return getEntry(key) != null;
17.356 + }
17.357 +
17.358 + /**
17.359 + * Returns the entry associated with the specified key in the
17.360 + * HashMap. Returns null if the HashMap contains no mapping
17.361 + * for the key.
17.362 + */
17.363 + final Entry<K,V> getEntry(Object key) {
17.364 + int hash = (key == null) ? 0 : hash(key.hashCode());
17.365 + for (Entry<K,V> e = table[indexFor(hash, table.length)];
17.366 + e != null;
17.367 + e = e.next) {
17.368 + Object k;
17.369 + if (e.hash == hash &&
17.370 + ((k = e.key) == key || (key != null && key.equals(k))))
17.371 + return e;
17.372 + }
17.373 + return null;
17.374 + }
17.375 +
17.376 +
17.377 + /**
17.378 + * Associates the specified value with the specified key in this map.
17.379 + * If the map previously contained a mapping for the key, the old
17.380 + * value is replaced.
17.381 + *
17.382 + * @param key key with which the specified value is to be associated
17.383 + * @param value value to be associated with the specified key
17.384 + * @return the previous value associated with <tt>key</tt>, or
17.385 + * <tt>null</tt> if there was no mapping for <tt>key</tt>.
17.386 + * (A <tt>null</tt> return can also indicate that the map
17.387 + * previously associated <tt>null</tt> with <tt>key</tt>.)
17.388 + */
17.389 + public V put(K key, V value) {
17.390 + if (key == null)
17.391 + return putForNullKey(value);
17.392 + int hash = hash(key.hashCode());
17.393 + int i = indexFor(hash, table.length);
17.394 + for (Entry<K,V> e = table[i]; e != null; e = e.next) {
17.395 + Object k;
17.396 + if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
17.397 + V oldValue = e.value;
17.398 + e.value = value;
17.399 + e.recordAccess(this);
17.400 + return oldValue;
17.401 + }
17.402 + }
17.403 +
17.404 + modCount++;
17.405 + addEntry(hash, key, value, i);
17.406 + return null;
17.407 + }
17.408 +
17.409 + /**
17.410 + * Offloaded version of put for null keys
17.411 + */
17.412 + private V putForNullKey(V value) {
17.413 + for (Entry<K,V> e = table[0]; e != null; e = e.next) {
17.414 + if (e.key == null) {
17.415 + V oldValue = e.value;
17.416 + e.value = value;
17.417 + e.recordAccess(this);
17.418 + return oldValue;
17.419 + }
17.420 + }
17.421 + modCount++;
17.422 + addEntry(0, null, value, 0);
17.423 + return null;
17.424 + }
17.425 +
17.426 + /**
17.427 + * This method is used instead of put by constructors and
17.428 + * pseudoconstructors (clone, readObject). It does not resize the table,
17.429 + * check for comodification, etc. It calls createEntry rather than
17.430 + * addEntry.
17.431 + */
17.432 + private void putForCreate(K key, V value) {
17.433 + int hash = (key == null) ? 0 : hash(key.hashCode());
17.434 + int i = indexFor(hash, table.length);
17.435 +
17.436 + /**
17.437 + * Look for preexisting entry for key. This will never happen for
17.438 + * clone or deserialize. It will only happen for construction if the
17.439 + * input Map is a sorted map whose ordering is inconsistent w/ equals.
17.440 + */
17.441 + for (Entry<K,V> e = table[i]; e != null; e = e.next) {
17.442 + Object k;
17.443 + if (e.hash == hash &&
17.444 + ((k = e.key) == key || (key != null && key.equals(k)))) {
17.445 + e.value = value;
17.446 + return;
17.447 + }
17.448 + }
17.449 +
17.450 + createEntry(hash, key, value, i);
17.451 + }
17.452 +
17.453 + private void putAllForCreate(Map<? extends K, ? extends V> m) {
17.454 + for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
17.455 + putForCreate(e.getKey(), e.getValue());
17.456 + }
17.457 +
17.458 + /**
17.459 + * Rehashes the contents of this map into a new array with a
17.460 + * larger capacity. This method is called automatically when the
17.461 + * number of keys in this map reaches its threshold.
17.462 + *
17.463 + * If current capacity is MAXIMUM_CAPACITY, this method does not
17.464 + * resize the map, but sets threshold to Integer.MAX_VALUE.
17.465 + * This has the effect of preventing future calls.
17.466 + *
17.467 + * @param newCapacity the new capacity, MUST be a power of two;
17.468 + * must be greater than current capacity unless current
17.469 + * capacity is MAXIMUM_CAPACITY (in which case value
17.470 + * is irrelevant).
17.471 + */
17.472 + void resize(int newCapacity) {
17.473 + Entry[] oldTable = table;
17.474 + int oldCapacity = oldTable.length;
17.475 + if (oldCapacity == MAXIMUM_CAPACITY) {
17.476 + threshold = Integer.MAX_VALUE;
17.477 + return;
17.478 + }
17.479 +
17.480 + Entry[] newTable = new Entry[newCapacity];
17.481 + transfer(newTable);
17.482 + table = newTable;
17.483 + threshold = (int)(newCapacity * loadFactor);
17.484 + }
17.485 +
17.486 + /**
17.487 + * Transfers all entries from current table to newTable.
17.488 + */
17.489 + void transfer(Entry[] newTable) {
17.490 + Entry[] src = table;
17.491 + int newCapacity = newTable.length;
17.492 + for (int j = 0; j < src.length; j++) {
17.493 + Entry<K,V> e = src[j];
17.494 + if (e != null) {
17.495 + src[j] = null;
17.496 + do {
17.497 + Entry<K,V> next = e.next;
17.498 + int i = indexFor(e.hash, newCapacity);
17.499 + e.next = newTable[i];
17.500 + newTable[i] = e;
17.501 + e = next;
17.502 + } while (e != null);
17.503 + }
17.504 + }
17.505 + }
17.506 +
17.507 + /**
17.508 + * Copies all of the mappings from the specified map to this map.
17.509 + * These mappings will replace any mappings that this map had for
17.510 + * any of the keys currently in the specified map.
17.511 + *
17.512 + * @param m mappings to be stored in this map
17.513 + * @throws NullPointerException if the specified map is null
17.514 + */
17.515 + public void putAll(Map<? extends K, ? extends V> m) {
17.516 + int numKeysToBeAdded = m.size();
17.517 + if (numKeysToBeAdded == 0)
17.518 + return;
17.519 +
17.520 + /*
17.521 + * Expand the map if the map if the number of mappings to be added
17.522 + * is greater than or equal to threshold. This is conservative; the
17.523 + * obvious condition is (m.size() + size) >= threshold, but this
17.524 + * condition could result in a map with twice the appropriate capacity,
17.525 + * if the keys to be added overlap with the keys already in this map.
17.526 + * By using the conservative calculation, we subject ourself
17.527 + * to at most one extra resize.
17.528 + */
17.529 + if (numKeysToBeAdded > threshold) {
17.530 + int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
17.531 + if (targetCapacity > MAXIMUM_CAPACITY)
17.532 + targetCapacity = MAXIMUM_CAPACITY;
17.533 + int newCapacity = table.length;
17.534 + while (newCapacity < targetCapacity)
17.535 + newCapacity <<= 1;
17.536 + if (newCapacity > table.length)
17.537 + resize(newCapacity);
17.538 + }
17.539 +
17.540 + for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
17.541 + put(e.getKey(), e.getValue());
17.542 + }
17.543 +
17.544 + /**
17.545 + * Removes the mapping for the specified key from this map if present.
17.546 + *
17.547 + * @param key key whose mapping is to be removed from the map
17.548 + * @return the previous value associated with <tt>key</tt>, or
17.549 + * <tt>null</tt> if there was no mapping for <tt>key</tt>.
17.550 + * (A <tt>null</tt> return can also indicate that the map
17.551 + * previously associated <tt>null</tt> with <tt>key</tt>.)
17.552 + */
17.553 + public V remove(Object key) {
17.554 + Entry<K,V> e = removeEntryForKey(key);
17.555 + return (e == null ? null : e.value);
17.556 + }
17.557 +
17.558 + /**
17.559 + * Removes and returns the entry associated with the specified key
17.560 + * in the HashMap. Returns null if the HashMap contains no mapping
17.561 + * for this key.
17.562 + */
17.563 + final Entry<K,V> removeEntryForKey(Object key) {
17.564 + int hash = (key == null) ? 0 : hash(key.hashCode());
17.565 + int i = indexFor(hash, table.length);
17.566 + Entry<K,V> prev = table[i];
17.567 + Entry<K,V> e = prev;
17.568 +
17.569 + while (e != null) {
17.570 + Entry<K,V> next = e.next;
17.571 + Object k;
17.572 + if (e.hash == hash &&
17.573 + ((k = e.key) == key || (key != null && key.equals(k)))) {
17.574 + modCount++;
17.575 + size--;
17.576 + if (prev == e)
17.577 + table[i] = next;
17.578 + else
17.579 + prev.next = next;
17.580 + e.recordRemoval(this);
17.581 + return e;
17.582 + }
17.583 + prev = e;
17.584 + e = next;
17.585 + }
17.586 +
17.587 + return e;
17.588 + }
17.589 +
17.590 + /**
17.591 + * Special version of remove for EntrySet.
17.592 + */
17.593 + final Entry<K,V> removeMapping(Object o) {
17.594 + if (!(o instanceof Map.Entry))
17.595 + return null;
17.596 +
17.597 + Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
17.598 + Object key = entry.getKey();
17.599 + int hash = (key == null) ? 0 : hash(key.hashCode());
17.600 + int i = indexFor(hash, table.length);
17.601 + Entry<K,V> prev = table[i];
17.602 + Entry<K,V> e = prev;
17.603 +
17.604 + while (e != null) {
17.605 + Entry<K,V> next = e.next;
17.606 + if (e.hash == hash && e.equals(entry)) {
17.607 + modCount++;
17.608 + size--;
17.609 + if (prev == e)
17.610 + table[i] = next;
17.611 + else
17.612 + prev.next = next;
17.613 + e.recordRemoval(this);
17.614 + return e;
17.615 + }
17.616 + prev = e;
17.617 + e = next;
17.618 + }
17.619 +
17.620 + return e;
17.621 + }
17.622 +
17.623 + /**
17.624 + * Removes all of the mappings from this map.
17.625 + * The map will be empty after this call returns.
17.626 + */
17.627 + public void clear() {
17.628 + modCount++;
17.629 + Entry[] tab = table;
17.630 + for (int i = 0; i < tab.length; i++)
17.631 + tab[i] = null;
17.632 + size = 0;
17.633 + }
17.634 +
17.635 + /**
17.636 + * Returns <tt>true</tt> if this map maps one or more keys to the
17.637 + * specified value.
17.638 + *
17.639 + * @param value value whose presence in this map is to be tested
17.640 + * @return <tt>true</tt> if this map maps one or more keys to the
17.641 + * specified value
17.642 + */
17.643 + public boolean containsValue(Object value) {
17.644 + if (value == null)
17.645 + return containsNullValue();
17.646 +
17.647 + Entry[] tab = table;
17.648 + for (int i = 0; i < tab.length ; i++)
17.649 + for (Entry e = tab[i] ; e != null ; e = e.next)
17.650 + if (value.equals(e.value))
17.651 + return true;
17.652 + return false;
17.653 + }
17.654 +
17.655 + /**
17.656 + * Special-case code for containsValue with null argument
17.657 + */
17.658 + private boolean containsNullValue() {
17.659 + Entry[] tab = table;
17.660 + for (int i = 0; i < tab.length ; i++)
17.661 + for (Entry e = tab[i] ; e != null ; e = e.next)
17.662 + if (e.value == null)
17.663 + return true;
17.664 + return false;
17.665 + }
17.666 +
17.667 + /**
17.668 + * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
17.669 + * values themselves are not cloned.
17.670 + *
17.671 + * @return a shallow copy of this map
17.672 + */
17.673 + public Object clone() {
17.674 + HashMap<K,V> result = null;
17.675 + try {
17.676 + result = (HashMap<K,V>)super.clone();
17.677 + } catch (CloneNotSupportedException e) {
17.678 + // assert false;
17.679 + }
17.680 + result.table = new Entry[table.length];
17.681 + result.entrySet = null;
17.682 + result.modCount = 0;
17.683 + result.size = 0;
17.684 + result.init();
17.685 + result.putAllForCreate(this);
17.686 +
17.687 + return result;
17.688 + }
17.689 +
17.690 + static class Entry<K,V> implements Map.Entry<K,V> {
17.691 + final K key;
17.692 + V value;
17.693 + Entry<K,V> next;
17.694 + final int hash;
17.695 +
17.696 + /**
17.697 + * Creates new entry.
17.698 + */
17.699 + Entry(int h, K k, V v, Entry<K,V> n) {
17.700 + value = v;
17.701 + next = n;
17.702 + key = k;
17.703 + hash = h;
17.704 + }
17.705 +
17.706 + public final K getKey() {
17.707 + return key;
17.708 + }
17.709 +
17.710 + public final V getValue() {
17.711 + return value;
17.712 + }
17.713 +
17.714 + public final V setValue(V newValue) {
17.715 + V oldValue = value;
17.716 + value = newValue;
17.717 + return oldValue;
17.718 + }
17.719 +
17.720 + public final boolean equals(Object o) {
17.721 + if (!(o instanceof Map.Entry))
17.722 + return false;
17.723 + Map.Entry e = (Map.Entry)o;
17.724 + Object k1 = getKey();
17.725 + Object k2 = e.getKey();
17.726 + if (k1 == k2 || (k1 != null && k1.equals(k2))) {
17.727 + Object v1 = getValue();
17.728 + Object v2 = e.getValue();
17.729 + if (v1 == v2 || (v1 != null && v1.equals(v2)))
17.730 + return true;
17.731 + }
17.732 + return false;
17.733 + }
17.734 +
17.735 + public final int hashCode() {
17.736 + return (key==null ? 0 : key.hashCode()) ^
17.737 + (value==null ? 0 : value.hashCode());
17.738 + }
17.739 +
17.740 + public final String toString() {
17.741 + return getKey() + "=" + getValue();
17.742 + }
17.743 +
17.744 + /**
17.745 + * This method is invoked whenever the value in an entry is
17.746 + * overwritten by an invocation of put(k,v) for a key k that's already
17.747 + * in the HashMap.
17.748 + */
17.749 + void recordAccess(HashMap<K,V> m) {
17.750 + }
17.751 +
17.752 + /**
17.753 + * This method is invoked whenever the entry is
17.754 + * removed from the table.
17.755 + */
17.756 + void recordRemoval(HashMap<K,V> m) {
17.757 + }
17.758 + }
17.759 +
17.760 + /**
17.761 + * Adds a new entry with the specified key, value and hash code to
17.762 + * the specified bucket. It is the responsibility of this
17.763 + * method to resize the table if appropriate.
17.764 + *
17.765 + * Subclass overrides this to alter the behavior of put method.
17.766 + */
17.767 + void addEntry(int hash, K key, V value, int bucketIndex) {
17.768 + Entry<K,V> e = table[bucketIndex];
17.769 + table[bucketIndex] = new Entry<>(hash, key, value, e);
17.770 + if (size++ >= threshold)
17.771 + resize(2 * table.length);
17.772 + }
17.773 +
17.774 + /**
17.775 + * Like addEntry except that this version is used when creating entries
17.776 + * as part of Map construction or "pseudo-construction" (cloning,
17.777 + * deserialization). This version needn't worry about resizing the table.
17.778 + *
17.779 + * Subclass overrides this to alter the behavior of HashMap(Map),
17.780 + * clone, and readObject.
17.781 + */
17.782 + void createEntry(int hash, K key, V value, int bucketIndex) {
17.783 + Entry<K,V> e = table[bucketIndex];
17.784 + table[bucketIndex] = new Entry<>(hash, key, value, e);
17.785 + size++;
17.786 + }
17.787 +
17.788 + private abstract class HashIterator<E> implements Iterator<E> {
17.789 + Entry<K,V> next; // next entry to return
17.790 + int expectedModCount; // For fast-fail
17.791 + int index; // current slot
17.792 + Entry<K,V> current; // current entry
17.793 +
17.794 + HashIterator() {
17.795 + expectedModCount = modCount;
17.796 + if (size > 0) { // advance to first entry
17.797 + Entry[] t = table;
17.798 + while (index < t.length && (next = t[index++]) == null)
17.799 + ;
17.800 + }
17.801 + }
17.802 +
17.803 + public final boolean hasNext() {
17.804 + return next != null;
17.805 + }
17.806 +
17.807 + final Entry<K,V> nextEntry() {
17.808 + if (modCount != expectedModCount)
17.809 + throw new ConcurrentModificationException();
17.810 + Entry<K,V> e = next;
17.811 + if (e == null)
17.812 + throw new NoSuchElementException();
17.813 +
17.814 + if ((next = e.next) == null) {
17.815 + Entry[] t = table;
17.816 + while (index < t.length && (next = t[index++]) == null)
17.817 + ;
17.818 + }
17.819 + current = e;
17.820 + return e;
17.821 + }
17.822 +
17.823 + public void remove() {
17.824 + if (current == null)
17.825 + throw new IllegalStateException();
17.826 + if (modCount != expectedModCount)
17.827 + throw new ConcurrentModificationException();
17.828 + Object k = current.key;
17.829 + current = null;
17.830 + HashMap.this.removeEntryForKey(k);
17.831 + expectedModCount = modCount;
17.832 + }
17.833 +
17.834 + }
17.835 +
17.836 + private final class ValueIterator extends HashIterator<V> {
17.837 + public V next() {
17.838 + return nextEntry().value;
17.839 + }
17.840 + }
17.841 +
17.842 + private final class KeyIterator extends HashIterator<K> {
17.843 + public K next() {
17.844 + return nextEntry().getKey();
17.845 + }
17.846 + }
17.847 +
17.848 + private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
17.849 + public Map.Entry<K,V> next() {
17.850 + return nextEntry();
17.851 + }
17.852 + }
17.853 +
17.854 + // Subclass overrides these to alter behavior of views' iterator() method
17.855 + Iterator<K> newKeyIterator() {
17.856 + return new KeyIterator();
17.857 + }
17.858 + Iterator<V> newValueIterator() {
17.859 + return new ValueIterator();
17.860 + }
17.861 + Iterator<Map.Entry<K,V>> newEntryIterator() {
17.862 + return new EntryIterator();
17.863 + }
17.864 +
17.865 +
17.866 + // Views
17.867 +
17.868 + private transient Set<Map.Entry<K,V>> entrySet = null;
17.869 +
17.870 + /**
17.871 + * Returns a {@link Set} view of the keys contained in this map.
17.872 + * The set is backed by the map, so changes to the map are
17.873 + * reflected in the set, and vice-versa. If the map is modified
17.874 + * while an iteration over the set is in progress (except through
17.875 + * the iterator's own <tt>remove</tt> operation), the results of
17.876 + * the iteration are undefined. The set supports element removal,
17.877 + * which removes the corresponding mapping from the map, via the
17.878 + * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
17.879 + * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
17.880 + * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
17.881 + * operations.
17.882 + */
17.883 + public Set<K> keySet() {
17.884 + Set<K> ks = keySet;
17.885 + return (ks != null ? ks : (keySet = new KeySet()));
17.886 + }
17.887 +
17.888 + private final class KeySet extends AbstractSet<K> {
17.889 + public Iterator<K> iterator() {
17.890 + return newKeyIterator();
17.891 + }
17.892 + public int size() {
17.893 + return size;
17.894 + }
17.895 + public boolean contains(Object o) {
17.896 + return containsKey(o);
17.897 + }
17.898 + public boolean remove(Object o) {
17.899 + return HashMap.this.removeEntryForKey(o) != null;
17.900 + }
17.901 + public void clear() {
17.902 + HashMap.this.clear();
17.903 + }
17.904 + }
17.905 +
17.906 + /**
17.907 + * Returns a {@link Collection} view of the values contained in this map.
17.908 + * The collection is backed by the map, so changes to the map are
17.909 + * reflected in the collection, and vice-versa. If the map is
17.910 + * modified while an iteration over the collection is in progress
17.911 + * (except through the iterator's own <tt>remove</tt> operation),
17.912 + * the results of the iteration are undefined. The collection
17.913 + * supports element removal, which removes the corresponding
17.914 + * mapping from the map, via the <tt>Iterator.remove</tt>,
17.915 + * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
17.916 + * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
17.917 + * support the <tt>add</tt> or <tt>addAll</tt> operations.
17.918 + */
17.919 + public Collection<V> values() {
17.920 + Collection<V> vs = values;
17.921 + return (vs != null ? vs : (values = new Values()));
17.922 + }
17.923 +
17.924 + private final class Values extends AbstractCollection<V> {
17.925 + public Iterator<V> iterator() {
17.926 + return newValueIterator();
17.927 + }
17.928 + public int size() {
17.929 + return size;
17.930 + }
17.931 + public boolean contains(Object o) {
17.932 + return containsValue(o);
17.933 + }
17.934 + public void clear() {
17.935 + HashMap.this.clear();
17.936 + }
17.937 + }
17.938 +
17.939 + /**
17.940 + * Returns a {@link Set} view of the mappings contained in this map.
17.941 + * The set is backed by the map, so changes to the map are
17.942 + * reflected in the set, and vice-versa. If the map is modified
17.943 + * while an iteration over the set is in progress (except through
17.944 + * the iterator's own <tt>remove</tt> operation, or through the
17.945 + * <tt>setValue</tt> operation on a map entry returned by the
17.946 + * iterator) the results of the iteration are undefined. The set
17.947 + * supports element removal, which removes the corresponding
17.948 + * mapping from the map, via the <tt>Iterator.remove</tt>,
17.949 + * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
17.950 + * <tt>clear</tt> operations. It does not support the
17.951 + * <tt>add</tt> or <tt>addAll</tt> operations.
17.952 + *
17.953 + * @return a set view of the mappings contained in this map
17.954 + */
17.955 + public Set<Map.Entry<K,V>> entrySet() {
17.956 + return entrySet0();
17.957 + }
17.958 +
17.959 + private Set<Map.Entry<K,V>> entrySet0() {
17.960 + Set<Map.Entry<K,V>> es = entrySet;
17.961 + return es != null ? es : (entrySet = new EntrySet());
17.962 + }
17.963 +
17.964 + private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
17.965 + public Iterator<Map.Entry<K,V>> iterator() {
17.966 + return newEntryIterator();
17.967 + }
17.968 + public boolean contains(Object o) {
17.969 + if (!(o instanceof Map.Entry))
17.970 + return false;
17.971 + Map.Entry<K,V> e = (Map.Entry<K,V>) o;
17.972 + Entry<K,V> candidate = getEntry(e.getKey());
17.973 + return candidate != null && candidate.equals(e);
17.974 + }
17.975 + public boolean remove(Object o) {
17.976 + return removeMapping(o) != null;
17.977 + }
17.978 + public int size() {
17.979 + return size;
17.980 + }
17.981 + public void clear() {
17.982 + HashMap.this.clear();
17.983 + }
17.984 + }
17.985 +
17.986 + /**
17.987 + * Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
17.988 + * serialize it).
17.989 + *
17.990 + * @serialData The <i>capacity</i> of the HashMap (the length of the
17.991 + * bucket array) is emitted (int), followed by the
17.992 + * <i>size</i> (an int, the number of key-value
17.993 + * mappings), followed by the key (Object) and value (Object)
17.994 + * for each key-value mapping. The key-value mappings are
17.995 + * emitted in no particular order.
17.996 + */
17.997 + private void writeObject(java.io.ObjectOutputStream s)
17.998 + throws IOException
17.999 + {
17.1000 + Iterator<Map.Entry<K,V>> i =
17.1001 + (size > 0) ? entrySet0().iterator() : null;
17.1002 +
17.1003 + // Write out the threshold, loadfactor, and any hidden stuff
17.1004 + s.defaultWriteObject();
17.1005 +
17.1006 + // Write out number of buckets
17.1007 + s.writeInt(table.length);
17.1008 +
17.1009 + // Write out size (number of Mappings)
17.1010 + s.writeInt(size);
17.1011 +
17.1012 + // Write out keys and values (alternating)
17.1013 + if (i != null) {
17.1014 + while (i.hasNext()) {
17.1015 + Map.Entry<K,V> e = i.next();
17.1016 + s.writeObject(e.getKey());
17.1017 + s.writeObject(e.getValue());
17.1018 + }
17.1019 + }
17.1020 + }
17.1021 +
17.1022 + private static final long serialVersionUID = 362498820763181265L;
17.1023 +
17.1024 + /**
17.1025 + * Reconstitute the <tt>HashMap</tt> instance from a stream (i.e.,
17.1026 + * deserialize it).
17.1027 + */
17.1028 + private void readObject(java.io.ObjectInputStream s)
17.1029 + throws IOException, ClassNotFoundException
17.1030 + {
17.1031 + // Read in the threshold, loadfactor, and any hidden stuff
17.1032 + s.defaultReadObject();
17.1033 +
17.1034 + // Read in number of buckets and allocate the bucket array;
17.1035 + int numBuckets = s.readInt();
17.1036 + table = new Entry[numBuckets];
17.1037 +
17.1038 + init(); // Give subclass a chance to do its thing.
17.1039 +
17.1040 + // Read in size (number of Mappings)
17.1041 + int size = s.readInt();
17.1042 +
17.1043 + // Read the keys and values, and put the mappings in the HashMap
17.1044 + for (int i=0; i<size; i++) {
17.1045 + K key = (K) s.readObject();
17.1046 + V value = (V) s.readObject();
17.1047 + putForCreate(key, value);
17.1048 + }
17.1049 + }
17.1050 +
17.1051 + // These methods are used when serializing HashSets
17.1052 + int capacity() { return table.length; }
17.1053 + float loadFactor() { return loadFactor; }
17.1054 +}
18.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
18.2 +++ b/emul/compact/src/main/java/java/util/HashSet.java Wed Jan 23 22:33:45 2013 +0100
18.3 @@ -0,0 +1,312 @@
18.4 +/*
18.5 + * Copyright (c) 1997, 2010, 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 +/**
18.32 + * This class implements the <tt>Set</tt> interface, backed by a hash table
18.33 + * (actually a <tt>HashMap</tt> instance). It makes no guarantees as to the
18.34 + * iteration order of the set; in particular, it does not guarantee that the
18.35 + * order will remain constant over time. This class permits the <tt>null</tt>
18.36 + * element.
18.37 + *
18.38 + * <p>This class offers constant time performance for the basic operations
18.39 + * (<tt>add</tt>, <tt>remove</tt>, <tt>contains</tt> and <tt>size</tt>),
18.40 + * assuming the hash function disperses the elements properly among the
18.41 + * buckets. Iterating over this set requires time proportional to the sum of
18.42 + * the <tt>HashSet</tt> instance's size (the number of elements) plus the
18.43 + * "capacity" of the backing <tt>HashMap</tt> instance (the number of
18.44 + * buckets). Thus, it's very important not to set the initial capacity too
18.45 + * high (or the load factor too low) if iteration performance is important.
18.46 + *
18.47 + * <p><strong>Note that this implementation is not synchronized.</strong>
18.48 + * If multiple threads access a hash set concurrently, and at least one of
18.49 + * the threads modifies the set, it <i>must</i> be synchronized externally.
18.50 + * This is typically accomplished by synchronizing on some object that
18.51 + * naturally encapsulates the set.
18.52 + *
18.53 + * If no such object exists, the set should be "wrapped" using the
18.54 + * {@link Collections#synchronizedSet Collections.synchronizedSet}
18.55 + * method. This is best done at creation time, to prevent accidental
18.56 + * unsynchronized access to the set:<pre>
18.57 + * Set s = Collections.synchronizedSet(new HashSet(...));</pre>
18.58 + *
18.59 + * <p>The iterators returned by this class's <tt>iterator</tt> method are
18.60 + * <i>fail-fast</i>: if the set is modified at any time after the iterator is
18.61 + * created, in any way except through the iterator's own <tt>remove</tt>
18.62 + * method, the Iterator throws a {@link ConcurrentModificationException}.
18.63 + * Thus, in the face of concurrent modification, the iterator fails quickly
18.64 + * and cleanly, rather than risking arbitrary, non-deterministic behavior at
18.65 + * an undetermined time in the future.
18.66 + *
18.67 + * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
18.68 + * as it is, generally speaking, impossible to make any hard guarantees in the
18.69 + * presence of unsynchronized concurrent modification. Fail-fast iterators
18.70 + * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
18.71 + * Therefore, it would be wrong to write a program that depended on this
18.72 + * exception for its correctness: <i>the fail-fast behavior of iterators
18.73 + * should be used only to detect bugs.</i>
18.74 + *
18.75 + * <p>This class is a member of the
18.76 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
18.77 + * Java Collections Framework</a>.
18.78 + *
18.79 + * @param <E> the type of elements maintained by this set
18.80 + *
18.81 + * @author Josh Bloch
18.82 + * @author Neal Gafter
18.83 + * @see Collection
18.84 + * @see Set
18.85 + * @see TreeSet
18.86 + * @see HashMap
18.87 + * @since 1.2
18.88 + */
18.89 +
18.90 +public class HashSet<E>
18.91 + extends AbstractSet<E>
18.92 + implements Set<E>, Cloneable, java.io.Serializable
18.93 +{
18.94 + static final long serialVersionUID = -5024744406713321676L;
18.95 +
18.96 + private transient HashMap<E,Object> map;
18.97 +
18.98 + // Dummy value to associate with an Object in the backing Map
18.99 + private static final Object PRESENT = new Object();
18.100 +
18.101 + /**
18.102 + * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
18.103 + * default initial capacity (16) and load factor (0.75).
18.104 + */
18.105 + public HashSet() {
18.106 + map = new HashMap<>();
18.107 + }
18.108 +
18.109 + /**
18.110 + * Constructs a new set containing the elements in the specified
18.111 + * collection. The <tt>HashMap</tt> is created with default load factor
18.112 + * (0.75) and an initial capacity sufficient to contain the elements in
18.113 + * the specified collection.
18.114 + *
18.115 + * @param c the collection whose elements are to be placed into this set
18.116 + * @throws NullPointerException if the specified collection is null
18.117 + */
18.118 + public HashSet(Collection<? extends E> c) {
18.119 + map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
18.120 + addAll(c);
18.121 + }
18.122 +
18.123 + /**
18.124 + * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
18.125 + * the specified initial capacity and the specified load factor.
18.126 + *
18.127 + * @param initialCapacity the initial capacity of the hash map
18.128 + * @param loadFactor the load factor of the hash map
18.129 + * @throws IllegalArgumentException if the initial capacity is less
18.130 + * than zero, or if the load factor is nonpositive
18.131 + */
18.132 + public HashSet(int initialCapacity, float loadFactor) {
18.133 + map = new HashMap<>(initialCapacity, loadFactor);
18.134 + }
18.135 +
18.136 + /**
18.137 + * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
18.138 + * the specified initial capacity and default load factor (0.75).
18.139 + *
18.140 + * @param initialCapacity the initial capacity of the hash table
18.141 + * @throws IllegalArgumentException if the initial capacity is less
18.142 + * than zero
18.143 + */
18.144 + public HashSet(int initialCapacity) {
18.145 + map = new HashMap<>(initialCapacity);
18.146 + }
18.147 +
18.148 + /**
18.149 + * Constructs a new, empty linked hash set. (This package private
18.150 + * constructor is only used by LinkedHashSet.) The backing
18.151 + * HashMap instance is a LinkedHashMap with the specified initial
18.152 + * capacity and the specified load factor.
18.153 + *
18.154 + * @param initialCapacity the initial capacity of the hash map
18.155 + * @param loadFactor the load factor of the hash map
18.156 + * @param dummy ignored (distinguishes this
18.157 + * constructor from other int, float constructor.)
18.158 + * @throws IllegalArgumentException if the initial capacity is less
18.159 + * than zero, or if the load factor is nonpositive
18.160 + */
18.161 + HashSet(int initialCapacity, float loadFactor, boolean dummy) {
18.162 + map = new LinkedHashMap<>(initialCapacity, loadFactor);
18.163 + }
18.164 +
18.165 + /**
18.166 + * Returns an iterator over the elements in this set. The elements
18.167 + * are returned in no particular order.
18.168 + *
18.169 + * @return an Iterator over the elements in this set
18.170 + * @see ConcurrentModificationException
18.171 + */
18.172 + public Iterator<E> iterator() {
18.173 + return map.keySet().iterator();
18.174 + }
18.175 +
18.176 + /**
18.177 + * Returns the number of elements in this set (its cardinality).
18.178 + *
18.179 + * @return the number of elements in this set (its cardinality)
18.180 + */
18.181 + public int size() {
18.182 + return map.size();
18.183 + }
18.184 +
18.185 + /**
18.186 + * Returns <tt>true</tt> if this set contains no elements.
18.187 + *
18.188 + * @return <tt>true</tt> if this set contains no elements
18.189 + */
18.190 + public boolean isEmpty() {
18.191 + return map.isEmpty();
18.192 + }
18.193 +
18.194 + /**
18.195 + * Returns <tt>true</tt> if this set contains the specified element.
18.196 + * More formally, returns <tt>true</tt> if and only if this set
18.197 + * contains an element <tt>e</tt> such that
18.198 + * <tt>(o==null ? e==null : o.equals(e))</tt>.
18.199 + *
18.200 + * @param o element whose presence in this set is to be tested
18.201 + * @return <tt>true</tt> if this set contains the specified element
18.202 + */
18.203 + public boolean contains(Object o) {
18.204 + return map.containsKey(o);
18.205 + }
18.206 +
18.207 + /**
18.208 + * Adds the specified element to this set if it is not already present.
18.209 + * More formally, adds the specified element <tt>e</tt> to this set if
18.210 + * this set contains no element <tt>e2</tt> such that
18.211 + * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
18.212 + * If this set already contains the element, the call leaves the set
18.213 + * unchanged and returns <tt>false</tt>.
18.214 + *
18.215 + * @param e element to be added to this set
18.216 + * @return <tt>true</tt> if this set did not already contain the specified
18.217 + * element
18.218 + */
18.219 + public boolean add(E e) {
18.220 + return map.put(e, PRESENT)==null;
18.221 + }
18.222 +
18.223 + /**
18.224 + * Removes the specified element from this set if it is present.
18.225 + * More formally, removes an element <tt>e</tt> such that
18.226 + * <tt>(o==null ? e==null : o.equals(e))</tt>,
18.227 + * if this set contains such an element. Returns <tt>true</tt> if
18.228 + * this set contained the element (or equivalently, if this set
18.229 + * changed as a result of the call). (This set will not contain the
18.230 + * element once the call returns.)
18.231 + *
18.232 + * @param o object to be removed from this set, if present
18.233 + * @return <tt>true</tt> if the set contained the specified element
18.234 + */
18.235 + public boolean remove(Object o) {
18.236 + return map.remove(o)==PRESENT;
18.237 + }
18.238 +
18.239 + /**
18.240 + * Removes all of the elements from this set.
18.241 + * The set will be empty after this call returns.
18.242 + */
18.243 + public void clear() {
18.244 + map.clear();
18.245 + }
18.246 +
18.247 + /**
18.248 + * Returns a shallow copy of this <tt>HashSet</tt> instance: the elements
18.249 + * themselves are not cloned.
18.250 + *
18.251 + * @return a shallow copy of this set
18.252 + */
18.253 + public Object clone() {
18.254 + try {
18.255 + HashSet<E> newSet = (HashSet<E>) super.clone();
18.256 + newSet.map = (HashMap<E, Object>) map.clone();
18.257 + return newSet;
18.258 + } catch (CloneNotSupportedException e) {
18.259 + throw new InternalError();
18.260 + }
18.261 + }
18.262 +
18.263 + /**
18.264 + * Save the state of this <tt>HashSet</tt> instance to a stream (that is,
18.265 + * serialize it).
18.266 + *
18.267 + * @serialData The capacity of the backing <tt>HashMap</tt> instance
18.268 + * (int), and its load factor (float) are emitted, followed by
18.269 + * the size of the set (the number of elements it contains)
18.270 + * (int), followed by all of its elements (each an Object) in
18.271 + * no particular order.
18.272 + */
18.273 + private void writeObject(java.io.ObjectOutputStream s)
18.274 + throws java.io.IOException {
18.275 + // Write out any hidden serialization magic
18.276 + s.defaultWriteObject();
18.277 +
18.278 + // Write out HashMap capacity and load factor
18.279 + s.writeInt(map.capacity());
18.280 + s.writeFloat(map.loadFactor());
18.281 +
18.282 + // Write out size
18.283 + s.writeInt(map.size());
18.284 +
18.285 + // Write out all elements in the proper order.
18.286 + for (E e : map.keySet())
18.287 + s.writeObject(e);
18.288 + }
18.289 +
18.290 + /**
18.291 + * Reconstitute the <tt>HashSet</tt> instance from a stream (that is,
18.292 + * deserialize it).
18.293 + */
18.294 + private void readObject(java.io.ObjectInputStream s)
18.295 + throws java.io.IOException, ClassNotFoundException {
18.296 + // Read in any hidden serialization magic
18.297 + s.defaultReadObject();
18.298 +
18.299 + // Read in HashMap capacity and load factor and create backing HashMap
18.300 + int capacity = s.readInt();
18.301 + float loadFactor = s.readFloat();
18.302 + map = (((HashSet)this) instanceof LinkedHashSet ?
18.303 + new LinkedHashMap<E,Object>(capacity, loadFactor) :
18.304 + new HashMap<E,Object>(capacity, loadFactor));
18.305 +
18.306 + // Read in size
18.307 + int size = s.readInt();
18.308 +
18.309 + // Read in all elements in the proper order.
18.310 + for (int i=0; i<size; i++) {
18.311 + E e = (E) s.readObject();
18.312 + map.put(e, PRESENT);
18.313 + }
18.314 + }
18.315 +}
19.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
19.2 +++ b/emul/compact/src/main/java/java/util/Iterator.java Wed Jan 23 22:33:45 2013 +0100
19.3 @@ -0,0 +1,87 @@
19.4 +/*
19.5 + * Copyright (c) 1997, 2010, 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 +/**
19.32 + * An iterator over a collection. {@code Iterator} takes the place of
19.33 + * {@link Enumeration} in the Java Collections Framework. Iterators
19.34 + * differ from enumerations in two ways:
19.35 + *
19.36 + * <ul>
19.37 + * <li> Iterators allow the caller to remove elements from the
19.38 + * underlying collection during the iteration with well-defined
19.39 + * semantics.
19.40 + * <li> Method names have been improved.
19.41 + * </ul>
19.42 + *
19.43 + * <p>This interface is a member of the
19.44 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
19.45 + * Java Collections Framework</a>.
19.46 + *
19.47 + * @param <E> the type of elements returned by this iterator
19.48 + *
19.49 + * @author Josh Bloch
19.50 + * @see Collection
19.51 + * @see ListIterator
19.52 + * @see Iterable
19.53 + * @since 1.2
19.54 + */
19.55 +public interface Iterator<E> {
19.56 + /**
19.57 + * Returns {@code true} if the iteration has more elements.
19.58 + * (In other words, returns {@code true} if {@link #next} would
19.59 + * return an element rather than throwing an exception.)
19.60 + *
19.61 + * @return {@code true} if the iteration has more elements
19.62 + */
19.63 + boolean hasNext();
19.64 +
19.65 + /**
19.66 + * Returns the next element in the iteration.
19.67 + *
19.68 + * @return the next element in the iteration
19.69 + * @throws NoSuchElementException if the iteration has no more elements
19.70 + */
19.71 + E next();
19.72 +
19.73 + /**
19.74 + * Removes from the underlying collection the last element returned
19.75 + * by this iterator (optional operation). This method can be called
19.76 + * only once per call to {@link #next}. The behavior of an iterator
19.77 + * is unspecified if the underlying collection is modified while the
19.78 + * iteration is in progress in any way other than by calling this
19.79 + * method.
19.80 + *
19.81 + * @throws UnsupportedOperationException if the {@code remove}
19.82 + * operation is not supported by this iterator
19.83 + *
19.84 + * @throws IllegalStateException if the {@code next} method has not
19.85 + * yet been called, or the {@code remove} method has already
19.86 + * been called after the last call to the {@code next}
19.87 + * method
19.88 + */
19.89 + void remove();
19.90 +}
20.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
20.2 +++ b/emul/compact/src/main/java/java/util/LinkedHashMap.java Wed Jan 23 22:33:45 2013 +0100
20.3 @@ -0,0 +1,491 @@
20.4 +/*
20.5 + * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
20.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
20.7 + *
20.8 + * This code is free software; you can redistribute it and/or modify it
20.9 + * under the terms of the GNU General Public License version 2 only, as
20.10 + * published by the Free Software Foundation. Oracle designates this
20.11 + * particular file as subject to the "Classpath" exception as provided
20.12 + * by Oracle in the LICENSE file that accompanied this code.
20.13 + *
20.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
20.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
20.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20.17 + * version 2 for more details (a copy is included in the LICENSE file that
20.18 + * accompanied this code).
20.19 + *
20.20 + * You should have received a copy of the GNU General Public License version
20.21 + * 2 along with this work; if not, write to the Free Software Foundation,
20.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20.23 + *
20.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20.25 + * or visit www.oracle.com if you need additional information or have any
20.26 + * questions.
20.27 + */
20.28 +
20.29 +package java.util;
20.30 +import java.io.*;
20.31 +
20.32 +/**
20.33 + * <p>Hash table and linked list implementation of the <tt>Map</tt> interface,
20.34 + * with predictable iteration order. This implementation differs from
20.35 + * <tt>HashMap</tt> in that it maintains a doubly-linked list running through
20.36 + * all of its entries. This linked list defines the iteration ordering,
20.37 + * which is normally the order in which keys were inserted into the map
20.38 + * (<i>insertion-order</i>). Note that insertion order is not affected
20.39 + * if a key is <i>re-inserted</i> into the map. (A key <tt>k</tt> is
20.40 + * reinserted into a map <tt>m</tt> if <tt>m.put(k, v)</tt> is invoked when
20.41 + * <tt>m.containsKey(k)</tt> would return <tt>true</tt> immediately prior to
20.42 + * the invocation.)
20.43 + *
20.44 + * <p>This implementation spares its clients from the unspecified, generally
20.45 + * chaotic ordering provided by {@link HashMap} (and {@link Hashtable}),
20.46 + * without incurring the increased cost associated with {@link TreeMap}. It
20.47 + * can be used to produce a copy of a map that has the same order as the
20.48 + * original, regardless of the original map's implementation:
20.49 + * <pre>
20.50 + * void foo(Map m) {
20.51 + * Map copy = new LinkedHashMap(m);
20.52 + * ...
20.53 + * }
20.54 + * </pre>
20.55 + * This technique is particularly useful if a module takes a map on input,
20.56 + * copies it, and later returns results whose order is determined by that of
20.57 + * the copy. (Clients generally appreciate having things returned in the same
20.58 + * order they were presented.)
20.59 + *
20.60 + * <p>A special {@link #LinkedHashMap(int,float,boolean) constructor} is
20.61 + * provided to create a linked hash map whose order of iteration is the order
20.62 + * in which its entries were last accessed, from least-recently accessed to
20.63 + * most-recently (<i>access-order</i>). This kind of map is well-suited to
20.64 + * building LRU caches. Invoking the <tt>put</tt> or <tt>get</tt> method
20.65 + * results in an access to the corresponding entry (assuming it exists after
20.66 + * the invocation completes). The <tt>putAll</tt> method generates one entry
20.67 + * access for each mapping in the specified map, in the order that key-value
20.68 + * mappings are provided by the specified map's entry set iterator. <i>No
20.69 + * other methods generate entry accesses.</i> In particular, operations on
20.70 + * collection-views do <i>not</i> affect the order of iteration of the backing
20.71 + * map.
20.72 + *
20.73 + * <p>The {@link #removeEldestEntry(Map.Entry)} method may be overridden to
20.74 + * impose a policy for removing stale mappings automatically when new mappings
20.75 + * are added to the map.
20.76 + *
20.77 + * <p>This class provides all of the optional <tt>Map</tt> operations, and
20.78 + * permits null elements. Like <tt>HashMap</tt>, it provides constant-time
20.79 + * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and
20.80 + * <tt>remove</tt>), assuming the hash function disperses elements
20.81 + * properly among the buckets. Performance is likely to be just slightly
20.82 + * below that of <tt>HashMap</tt>, due to the added expense of maintaining the
20.83 + * linked list, with one exception: Iteration over the collection-views
20.84 + * of a <tt>LinkedHashMap</tt> requires time proportional to the <i>size</i>
20.85 + * of the map, regardless of its capacity. Iteration over a <tt>HashMap</tt>
20.86 + * is likely to be more expensive, requiring time proportional to its
20.87 + * <i>capacity</i>.
20.88 + *
20.89 + * <p>A linked hash map has two parameters that affect its performance:
20.90 + * <i>initial capacity</i> and <i>load factor</i>. They are defined precisely
20.91 + * as for <tt>HashMap</tt>. Note, however, that the penalty for choosing an
20.92 + * excessively high value for initial capacity is less severe for this class
20.93 + * than for <tt>HashMap</tt>, as iteration times for this class are unaffected
20.94 + * by capacity.
20.95 + *
20.96 + * <p><strong>Note that this implementation is not synchronized.</strong>
20.97 + * If multiple threads access a linked hash map concurrently, and at least
20.98 + * one of the threads modifies the map structurally, it <em>must</em> be
20.99 + * synchronized externally. This is typically accomplished by
20.100 + * synchronizing on some object that naturally encapsulates the map.
20.101 + *
20.102 + * If no such object exists, the map should be "wrapped" using the
20.103 + * {@link Collections#synchronizedMap Collections.synchronizedMap}
20.104 + * method. This is best done at creation time, to prevent accidental
20.105 + * unsynchronized access to the map:<pre>
20.106 + * Map m = Collections.synchronizedMap(new LinkedHashMap(...));</pre>
20.107 + *
20.108 + * A structural modification is any operation that adds or deletes one or more
20.109 + * mappings or, in the case of access-ordered linked hash maps, affects
20.110 + * iteration order. In insertion-ordered linked hash maps, merely changing
20.111 + * the value associated with a key that is already contained in the map is not
20.112 + * a structural modification. <strong>In access-ordered linked hash maps,
20.113 + * merely querying the map with <tt>get</tt> is a structural
20.114 + * modification.</strong>)
20.115 + *
20.116 + * <p>The iterators returned by the <tt>iterator</tt> method of the collections
20.117 + * returned by all of this class's collection view methods are
20.118 + * <em>fail-fast</em>: if the map is structurally modified at any time after
20.119 + * the iterator is created, in any way except through the iterator's own
20.120 + * <tt>remove</tt> method, the iterator will throw a {@link
20.121 + * ConcurrentModificationException}. Thus, in the face of concurrent
20.122 + * modification, the iterator fails quickly and cleanly, rather than risking
20.123 + * arbitrary, non-deterministic behavior at an undetermined time in the future.
20.124 + *
20.125 + * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
20.126 + * as it is, generally speaking, impossible to make any hard guarantees in the
20.127 + * presence of unsynchronized concurrent modification. Fail-fast iterators
20.128 + * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
20.129 + * Therefore, it would be wrong to write a program that depended on this
20.130 + * exception for its correctness: <i>the fail-fast behavior of iterators
20.131 + * should be used only to detect bugs.</i>
20.132 + *
20.133 + * <p>This class is a member of the
20.134 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
20.135 + * Java Collections Framework</a>.
20.136 + *
20.137 + * @param <K> the type of keys maintained by this map
20.138 + * @param <V> the type of mapped values
20.139 + *
20.140 + * @author Josh Bloch
20.141 + * @see Object#hashCode()
20.142 + * @see Collection
20.143 + * @see Map
20.144 + * @see HashMap
20.145 + * @see TreeMap
20.146 + * @see Hashtable
20.147 + * @since 1.4
20.148 + */
20.149 +
20.150 +public class LinkedHashMap<K,V>
20.151 + extends HashMap<K,V>
20.152 + implements Map<K,V>
20.153 +{
20.154 +
20.155 + private static final long serialVersionUID = 3801124242820219131L;
20.156 +
20.157 + /**
20.158 + * The head of the doubly linked list.
20.159 + */
20.160 + private transient Entry<K,V> header;
20.161 +
20.162 + /**
20.163 + * The iteration ordering method for this linked hash map: <tt>true</tt>
20.164 + * for access-order, <tt>false</tt> for insertion-order.
20.165 + *
20.166 + * @serial
20.167 + */
20.168 + private final boolean accessOrder;
20.169 +
20.170 + /**
20.171 + * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
20.172 + * with the specified initial capacity and load factor.
20.173 + *
20.174 + * @param initialCapacity the initial capacity
20.175 + * @param loadFactor the load factor
20.176 + * @throws IllegalArgumentException if the initial capacity is negative
20.177 + * or the load factor is nonpositive
20.178 + */
20.179 + public LinkedHashMap(int initialCapacity, float loadFactor) {
20.180 + super(initialCapacity, loadFactor);
20.181 + accessOrder = false;
20.182 + }
20.183 +
20.184 + /**
20.185 + * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
20.186 + * with the specified initial capacity and a default load factor (0.75).
20.187 + *
20.188 + * @param initialCapacity the initial capacity
20.189 + * @throws IllegalArgumentException if the initial capacity is negative
20.190 + */
20.191 + public LinkedHashMap(int initialCapacity) {
20.192 + super(initialCapacity);
20.193 + accessOrder = false;
20.194 + }
20.195 +
20.196 + /**
20.197 + * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
20.198 + * with the default initial capacity (16) and load factor (0.75).
20.199 + */
20.200 + public LinkedHashMap() {
20.201 + super();
20.202 + accessOrder = false;
20.203 + }
20.204 +
20.205 + /**
20.206 + * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with
20.207 + * the same mappings as the specified map. The <tt>LinkedHashMap</tt>
20.208 + * instance is created with a default load factor (0.75) and an initial
20.209 + * capacity sufficient to hold the mappings in the specified map.
20.210 + *
20.211 + * @param m the map whose mappings are to be placed in this map
20.212 + * @throws NullPointerException if the specified map is null
20.213 + */
20.214 + public LinkedHashMap(Map<? extends K, ? extends V> m) {
20.215 + super(m);
20.216 + accessOrder = false;
20.217 + }
20.218 +
20.219 + /**
20.220 + * Constructs an empty <tt>LinkedHashMap</tt> instance with the
20.221 + * specified initial capacity, load factor and ordering mode.
20.222 + *
20.223 + * @param initialCapacity the initial capacity
20.224 + * @param loadFactor the load factor
20.225 + * @param accessOrder the ordering mode - <tt>true</tt> for
20.226 + * access-order, <tt>false</tt> for insertion-order
20.227 + * @throws IllegalArgumentException if the initial capacity is negative
20.228 + * or the load factor is nonpositive
20.229 + */
20.230 + public LinkedHashMap(int initialCapacity,
20.231 + float loadFactor,
20.232 + boolean accessOrder) {
20.233 + super(initialCapacity, loadFactor);
20.234 + this.accessOrder = accessOrder;
20.235 + }
20.236 +
20.237 + /**
20.238 + * Called by superclass constructors and pseudoconstructors (clone,
20.239 + * readObject) before any entries are inserted into the map. Initializes
20.240 + * the chain.
20.241 + */
20.242 + void init() {
20.243 + header = new Entry<>(-1, null, null, null);
20.244 + header.before = header.after = header;
20.245 + }
20.246 +
20.247 + /**
20.248 + * Transfers all entries to new table array. This method is called
20.249 + * by superclass resize. It is overridden for performance, as it is
20.250 + * faster to iterate using our linked list.
20.251 + */
20.252 + void transfer(HashMap.Entry[] newTable) {
20.253 + int newCapacity = newTable.length;
20.254 + for (Entry<K,V> e = header.after; e != header; e = e.after) {
20.255 + int index = indexFor(e.hash, newCapacity);
20.256 + e.next = newTable[index];
20.257 + newTable[index] = e;
20.258 + }
20.259 + }
20.260 +
20.261 +
20.262 + /**
20.263 + * Returns <tt>true</tt> if this map maps one or more keys to the
20.264 + * specified value.
20.265 + *
20.266 + * @param value value whose presence in this map is to be tested
20.267 + * @return <tt>true</tt> if this map maps one or more keys to the
20.268 + * specified value
20.269 + */
20.270 + public boolean containsValue(Object value) {
20.271 + // Overridden to take advantage of faster iterator
20.272 + if (value==null) {
20.273 + for (Entry e = header.after; e != header; e = e.after)
20.274 + if (e.value==null)
20.275 + return true;
20.276 + } else {
20.277 + for (Entry e = header.after; e != header; e = e.after)
20.278 + if (value.equals(e.value))
20.279 + return true;
20.280 + }
20.281 + return false;
20.282 + }
20.283 +
20.284 + /**
20.285 + * Returns the value to which the specified key is mapped,
20.286 + * or {@code null} if this map contains no mapping for the key.
20.287 + *
20.288 + * <p>More formally, if this map contains a mapping from a key
20.289 + * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
20.290 + * key.equals(k))}, then this method returns {@code v}; otherwise
20.291 + * it returns {@code null}. (There can be at most one such mapping.)
20.292 + *
20.293 + * <p>A return value of {@code null} does not <i>necessarily</i>
20.294 + * indicate that the map contains no mapping for the key; it's also
20.295 + * possible that the map explicitly maps the key to {@code null}.
20.296 + * The {@link #containsKey containsKey} operation may be used to
20.297 + * distinguish these two cases.
20.298 + */
20.299 + public V get(Object key) {
20.300 + Entry<K,V> e = (Entry<K,V>)getEntry(key);
20.301 + if (e == null)
20.302 + return null;
20.303 + e.recordAccess(this);
20.304 + return e.value;
20.305 + }
20.306 +
20.307 + /**
20.308 + * Removes all of the mappings from this map.
20.309 + * The map will be empty after this call returns.
20.310 + */
20.311 + public void clear() {
20.312 + super.clear();
20.313 + header.before = header.after = header;
20.314 + }
20.315 +
20.316 + /**
20.317 + * LinkedHashMap entry.
20.318 + */
20.319 + private static class Entry<K,V> extends HashMap.Entry<K,V> {
20.320 + // These fields comprise the doubly linked list used for iteration.
20.321 + Entry<K,V> before, after;
20.322 +
20.323 + Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {
20.324 + super(hash, key, value, next);
20.325 + }
20.326 +
20.327 + /**
20.328 + * Removes this entry from the linked list.
20.329 + */
20.330 + private void remove() {
20.331 + before.after = after;
20.332 + after.before = before;
20.333 + }
20.334 +
20.335 + /**
20.336 + * Inserts this entry before the specified existing entry in the list.
20.337 + */
20.338 + private void addBefore(Entry<K,V> existingEntry) {
20.339 + after = existingEntry;
20.340 + before = existingEntry.before;
20.341 + before.after = this;
20.342 + after.before = this;
20.343 + }
20.344 +
20.345 + /**
20.346 + * This method is invoked by the superclass whenever the value
20.347 + * of a pre-existing entry is read by Map.get or modified by Map.set.
20.348 + * If the enclosing Map is access-ordered, it moves the entry
20.349 + * to the end of the list; otherwise, it does nothing.
20.350 + */
20.351 + void recordAccess(HashMap<K,V> m) {
20.352 + LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
20.353 + if (lm.accessOrder) {
20.354 + lm.modCount++;
20.355 + remove();
20.356 + addBefore(lm.header);
20.357 + }
20.358 + }
20.359 +
20.360 + void recordRemoval(HashMap<K,V> m) {
20.361 + remove();
20.362 + }
20.363 + }
20.364 +
20.365 + private abstract class LinkedHashIterator<T> implements Iterator<T> {
20.366 + Entry<K,V> nextEntry = header.after;
20.367 + Entry<K,V> lastReturned = null;
20.368 +
20.369 + /**
20.370 + * The modCount value that the iterator believes that the backing
20.371 + * List should have. If this expectation is violated, the iterator
20.372 + * has detected concurrent modification.
20.373 + */
20.374 + int expectedModCount = modCount;
20.375 +
20.376 + public boolean hasNext() {
20.377 + return nextEntry != header;
20.378 + }
20.379 +
20.380 + public void remove() {
20.381 + if (lastReturned == null)
20.382 + throw new IllegalStateException();
20.383 + if (modCount != expectedModCount)
20.384 + throw new ConcurrentModificationException();
20.385 +
20.386 + LinkedHashMap.this.remove(lastReturned.key);
20.387 + lastReturned = null;
20.388 + expectedModCount = modCount;
20.389 + }
20.390 +
20.391 + Entry<K,V> nextEntry() {
20.392 + if (modCount != expectedModCount)
20.393 + throw new ConcurrentModificationException();
20.394 + if (nextEntry == header)
20.395 + throw new NoSuchElementException();
20.396 +
20.397 + Entry<K,V> e = lastReturned = nextEntry;
20.398 + nextEntry = e.after;
20.399 + return e;
20.400 + }
20.401 + }
20.402 +
20.403 + private class KeyIterator extends LinkedHashIterator<K> {
20.404 + public K next() { return nextEntry().getKey(); }
20.405 + }
20.406 +
20.407 + private class ValueIterator extends LinkedHashIterator<V> {
20.408 + public V next() { return nextEntry().value; }
20.409 + }
20.410 +
20.411 + private class EntryIterator extends LinkedHashIterator<Map.Entry<K,V>> {
20.412 + public Map.Entry<K,V> next() { return nextEntry(); }
20.413 + }
20.414 +
20.415 + // These Overrides alter the behavior of superclass view iterator() methods
20.416 + Iterator<K> newKeyIterator() { return new KeyIterator(); }
20.417 + Iterator<V> newValueIterator() { return new ValueIterator(); }
20.418 + Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); }
20.419 +
20.420 + /**
20.421 + * This override alters behavior of superclass put method. It causes newly
20.422 + * allocated entry to get inserted at the end of the linked list and
20.423 + * removes the eldest entry if appropriate.
20.424 + */
20.425 + void addEntry(int hash, K key, V value, int bucketIndex) {
20.426 + createEntry(hash, key, value, bucketIndex);
20.427 +
20.428 + // Remove eldest entry if instructed, else grow capacity if appropriate
20.429 + Entry<K,V> eldest = header.after;
20.430 + if (removeEldestEntry(eldest)) {
20.431 + removeEntryForKey(eldest.key);
20.432 + } else {
20.433 + if (size >= threshold)
20.434 + resize(2 * table.length);
20.435 + }
20.436 + }
20.437 +
20.438 + /**
20.439 + * This override differs from addEntry in that it doesn't resize the
20.440 + * table or remove the eldest entry.
20.441 + */
20.442 + void createEntry(int hash, K key, V value, int bucketIndex) {
20.443 + HashMap.Entry<K,V> old = table[bucketIndex];
20.444 + Entry<K,V> e = new Entry<>(hash, key, value, old);
20.445 + table[bucketIndex] = e;
20.446 + e.addBefore(header);
20.447 + size++;
20.448 + }
20.449 +
20.450 + /**
20.451 + * Returns <tt>true</tt> if this map should remove its eldest entry.
20.452 + * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
20.453 + * inserting a new entry into the map. It provides the implementor
20.454 + * with the opportunity to remove the eldest entry each time a new one
20.455 + * is added. This is useful if the map represents a cache: it allows
20.456 + * the map to reduce memory consumption by deleting stale entries.
20.457 + *
20.458 + * <p>Sample use: this override will allow the map to grow up to 100
20.459 + * entries and then delete the eldest entry each time a new entry is
20.460 + * added, maintaining a steady state of 100 entries.
20.461 + * <pre>
20.462 + * private static final int MAX_ENTRIES = 100;
20.463 + *
20.464 + * protected boolean removeEldestEntry(Map.Entry eldest) {
20.465 + * return size() > MAX_ENTRIES;
20.466 + * }
20.467 + * </pre>
20.468 + *
20.469 + * <p>This method typically does not modify the map in any way,
20.470 + * instead allowing the map to modify itself as directed by its
20.471 + * return value. It <i>is</i> permitted for this method to modify
20.472 + * the map directly, but if it does so, it <i>must</i> return
20.473 + * <tt>false</tt> (indicating that the map should not attempt any
20.474 + * further modification). The effects of returning <tt>true</tt>
20.475 + * after modifying the map from within this method are unspecified.
20.476 + *
20.477 + * <p>This implementation merely returns <tt>false</tt> (so that this
20.478 + * map acts like a normal map - the eldest element is never removed).
20.479 + *
20.480 + * @param eldest The least recently inserted entry in the map, or if
20.481 + * this is an access-ordered map, the least recently accessed
20.482 + * entry. This is the entry that will be removed it this
20.483 + * method returns <tt>true</tt>. If the map was empty prior
20.484 + * to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
20.485 + * in this invocation, this will be the entry that was just
20.486 + * inserted; in other words, if the map contains a single
20.487 + * entry, the eldest entry is also the newest.
20.488 + * @return <tt>true</tt> if the eldest entry should be removed
20.489 + * from the map; <tt>false</tt> if it should be retained.
20.490 + */
20.491 + protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
20.492 + return false;
20.493 + }
20.494 +}
21.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
21.2 +++ b/emul/compact/src/main/java/java/util/List.java Wed Jan 23 22:33:45 2013 +0100
21.3 @@ -0,0 +1,600 @@
21.4 +/*
21.5 + * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
21.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
21.7 + *
21.8 + * This code is free software; you can redistribute it and/or modify it
21.9 + * under the terms of the GNU General Public License version 2 only, as
21.10 + * published by the Free Software Foundation. Oracle designates this
21.11 + * particular file as subject to the "Classpath" exception as provided
21.12 + * by Oracle in the LICENSE file that accompanied this code.
21.13 + *
21.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
21.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
21.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
21.17 + * version 2 for more details (a copy is included in the LICENSE file that
21.18 + * accompanied this code).
21.19 + *
21.20 + * You should have received a copy of the GNU General Public License version
21.21 + * 2 along with this work; if not, write to the Free Software Foundation,
21.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21.23 + *
21.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21.25 + * or visit www.oracle.com if you need additional information or have any
21.26 + * questions.
21.27 + */
21.28 +
21.29 +package java.util;
21.30 +
21.31 +/**
21.32 + * An ordered collection (also known as a <i>sequence</i>). The user of this
21.33 + * interface has precise control over where in the list each element is
21.34 + * inserted. The user can access elements by their integer index (position in
21.35 + * the list), and search for elements in the list.<p>
21.36 + *
21.37 + * Unlike sets, lists typically allow duplicate elements. More formally,
21.38 + * lists typically allow pairs of elements <tt>e1</tt> and <tt>e2</tt>
21.39 + * such that <tt>e1.equals(e2)</tt>, and they typically allow multiple
21.40 + * null elements if they allow null elements at all. It is not inconceivable
21.41 + * that someone might wish to implement a list that prohibits duplicates, by
21.42 + * throwing runtime exceptions when the user attempts to insert them, but we
21.43 + * expect this usage to be rare.<p>
21.44 + *
21.45 + * The <tt>List</tt> interface places additional stipulations, beyond those
21.46 + * specified in the <tt>Collection</tt> interface, on the contracts of the
21.47 + * <tt>iterator</tt>, <tt>add</tt>, <tt>remove</tt>, <tt>equals</tt>, and
21.48 + * <tt>hashCode</tt> methods. Declarations for other inherited methods are
21.49 + * also included here for convenience.<p>
21.50 + *
21.51 + * The <tt>List</tt> interface provides four methods for positional (indexed)
21.52 + * access to list elements. Lists (like Java arrays) are zero based. Note
21.53 + * that these operations may execute in time proportional to the index value
21.54 + * for some implementations (the <tt>LinkedList</tt> class, for
21.55 + * example). Thus, iterating over the elements in a list is typically
21.56 + * preferable to indexing through it if the caller does not know the
21.57 + * implementation.<p>
21.58 + *
21.59 + * The <tt>List</tt> interface provides a special iterator, called a
21.60 + * <tt>ListIterator</tt>, that allows element insertion and replacement, and
21.61 + * bidirectional access in addition to the normal operations that the
21.62 + * <tt>Iterator</tt> interface provides. A method is provided to obtain a
21.63 + * list iterator that starts at a specified position in the list.<p>
21.64 + *
21.65 + * The <tt>List</tt> interface provides two methods to search for a specified
21.66 + * object. From a performance standpoint, these methods should be used with
21.67 + * caution. In many implementations they will perform costly linear
21.68 + * searches.<p>
21.69 + *
21.70 + * The <tt>List</tt> interface provides two methods to efficiently insert and
21.71 + * remove multiple elements at an arbitrary point in the list.<p>
21.72 + *
21.73 + * Note: While it is permissible for lists to contain themselves as elements,
21.74 + * extreme caution is advised: the <tt>equals</tt> and <tt>hashCode</tt>
21.75 + * methods are no longer well defined on such a list.
21.76 + *
21.77 + * <p>Some list implementations have restrictions on the elements that
21.78 + * they may contain. For example, some implementations prohibit null elements,
21.79 + * and some have restrictions on the types of their elements. Attempting to
21.80 + * add an ineligible element throws an unchecked exception, typically
21.81 + * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting
21.82 + * to query the presence of an ineligible element may throw an exception,
21.83 + * or it may simply return false; some implementations will exhibit the former
21.84 + * behavior and some will exhibit the latter. More generally, attempting an
21.85 + * operation on an ineligible element whose completion would not result in
21.86 + * the insertion of an ineligible element into the list may throw an
21.87 + * exception or it may succeed, at the option of the implementation.
21.88 + * Such exceptions are marked as "optional" in the specification for this
21.89 + * interface.
21.90 + *
21.91 + * <p>This interface is a member of the
21.92 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
21.93 + * Java Collections Framework</a>.
21.94 + *
21.95 + * @param <E> the type of elements in this list
21.96 + *
21.97 + * @author Josh Bloch
21.98 + * @author Neal Gafter
21.99 + * @see Collection
21.100 + * @see Set
21.101 + * @see ArrayList
21.102 + * @see LinkedList
21.103 + * @see Vector
21.104 + * @see Arrays#asList(Object[])
21.105 + * @see Collections#nCopies(int, Object)
21.106 + * @see Collections#EMPTY_LIST
21.107 + * @see AbstractList
21.108 + * @see AbstractSequentialList
21.109 + * @since 1.2
21.110 + */
21.111 +
21.112 +public interface List<E> extends Collection<E> {
21.113 + // Query Operations
21.114 +
21.115 + /**
21.116 + * Returns the number of elements in this list. If this list contains
21.117 + * more than <tt>Integer.MAX_VALUE</tt> elements, returns
21.118 + * <tt>Integer.MAX_VALUE</tt>.
21.119 + *
21.120 + * @return the number of elements in this list
21.121 + */
21.122 + int size();
21.123 +
21.124 + /**
21.125 + * Returns <tt>true</tt> if this list contains no elements.
21.126 + *
21.127 + * @return <tt>true</tt> if this list contains no elements
21.128 + */
21.129 + boolean isEmpty();
21.130 +
21.131 + /**
21.132 + * Returns <tt>true</tt> if this list contains the specified element.
21.133 + * More formally, returns <tt>true</tt> if and only if this list contains
21.134 + * at least one element <tt>e</tt> such that
21.135 + * <tt>(o==null ? e==null : o.equals(e))</tt>.
21.136 + *
21.137 + * @param o element whose presence in this list is to be tested
21.138 + * @return <tt>true</tt> if this list contains the specified element
21.139 + * @throws ClassCastException if the type of the specified element
21.140 + * is incompatible with this list
21.141 + * (<a href="Collection.html#optional-restrictions">optional</a>)
21.142 + * @throws NullPointerException if the specified element is null and this
21.143 + * list does not permit null elements
21.144 + * (<a href="Collection.html#optional-restrictions">optional</a>)
21.145 + */
21.146 + boolean contains(Object o);
21.147 +
21.148 + /**
21.149 + * Returns an iterator over the elements in this list in proper sequence.
21.150 + *
21.151 + * @return an iterator over the elements in this list in proper sequence
21.152 + */
21.153 + Iterator<E> iterator();
21.154 +
21.155 + /**
21.156 + * Returns an array containing all of the elements in this list in proper
21.157 + * sequence (from first to last element).
21.158 + *
21.159 + * <p>The returned array will be "safe" in that no references to it are
21.160 + * maintained by this list. (In other words, this method must
21.161 + * allocate a new array even if this list is backed by an array).
21.162 + * The caller is thus free to modify the returned array.
21.163 + *
21.164 + * <p>This method acts as bridge between array-based and collection-based
21.165 + * APIs.
21.166 + *
21.167 + * @return an array containing all of the elements in this list in proper
21.168 + * sequence
21.169 + * @see Arrays#asList(Object[])
21.170 + */
21.171 + Object[] toArray();
21.172 +
21.173 + /**
21.174 + * Returns an array containing all of the elements in this list in
21.175 + * proper sequence (from first to last element); the runtime type of
21.176 + * the returned array is that of the specified array. If the list fits
21.177 + * in the specified array, it is returned therein. Otherwise, a new
21.178 + * array is allocated with the runtime type of the specified array and
21.179 + * the size of this list.
21.180 + *
21.181 + * <p>If the list fits in the specified array with room to spare (i.e.,
21.182 + * the array has more elements than the list), the element in the array
21.183 + * immediately following the end of the list is set to <tt>null</tt>.
21.184 + * (This is useful in determining the length of the list <i>only</i> if
21.185 + * the caller knows that the list does not contain any null elements.)
21.186 + *
21.187 + * <p>Like the {@link #toArray()} method, this method acts as bridge between
21.188 + * array-based and collection-based APIs. Further, this method allows
21.189 + * precise control over the runtime type of the output array, and may,
21.190 + * under certain circumstances, be used to save allocation costs.
21.191 + *
21.192 + * <p>Suppose <tt>x</tt> is a list known to contain only strings.
21.193 + * The following code can be used to dump the list into a newly
21.194 + * allocated array of <tt>String</tt>:
21.195 + *
21.196 + * <pre>
21.197 + * String[] y = x.toArray(new String[0]);</pre>
21.198 + *
21.199 + * Note that <tt>toArray(new Object[0])</tt> is identical in function to
21.200 + * <tt>toArray()</tt>.
21.201 + *
21.202 + * @param a the array into which the elements of this list are to
21.203 + * be stored, if it is big enough; otherwise, a new array of the
21.204 + * same runtime type is allocated for this purpose.
21.205 + * @return an array containing the elements of this list
21.206 + * @throws ArrayStoreException if the runtime type of the specified array
21.207 + * is not a supertype of the runtime type of every element in
21.208 + * this list
21.209 + * @throws NullPointerException if the specified array is null
21.210 + */
21.211 + <T> T[] toArray(T[] a);
21.212 +
21.213 +
21.214 + // Modification Operations
21.215 +
21.216 + /**
21.217 + * Appends the specified element to the end of this list (optional
21.218 + * operation).
21.219 + *
21.220 + * <p>Lists that support this operation may place limitations on what
21.221 + * elements may be added to this list. In particular, some
21.222 + * lists will refuse to add null elements, and others will impose
21.223 + * restrictions on the type of elements that may be added. List
21.224 + * classes should clearly specify in their documentation any restrictions
21.225 + * on what elements may be added.
21.226 + *
21.227 + * @param e element to be appended to this list
21.228 + * @return <tt>true</tt> (as specified by {@link Collection#add})
21.229 + * @throws UnsupportedOperationException if the <tt>add</tt> operation
21.230 + * is not supported by this list
21.231 + * @throws ClassCastException if the class of the specified element
21.232 + * prevents it from being added to this list
21.233 + * @throws NullPointerException if the specified element is null and this
21.234 + * list does not permit null elements
21.235 + * @throws IllegalArgumentException if some property of this element
21.236 + * prevents it from being added to this list
21.237 + */
21.238 + boolean add(E e);
21.239 +
21.240 + /**
21.241 + * Removes the first occurrence of the specified element from this list,
21.242 + * if it is present (optional operation). If this list does not contain
21.243 + * the element, it is unchanged. More formally, removes the element with
21.244 + * the lowest index <tt>i</tt> such that
21.245 + * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
21.246 + * (if such an element exists). Returns <tt>true</tt> if this list
21.247 + * contained the specified element (or equivalently, if this list changed
21.248 + * as a result of the call).
21.249 + *
21.250 + * @param o element to be removed from this list, if present
21.251 + * @return <tt>true</tt> if this list contained the specified element
21.252 + * @throws ClassCastException if the type of the specified element
21.253 + * is incompatible with this list
21.254 + * (<a href="Collection.html#optional-restrictions">optional</a>)
21.255 + * @throws NullPointerException if the specified element is null and this
21.256 + * list does not permit null elements
21.257 + * (<a href="Collection.html#optional-restrictions">optional</a>)
21.258 + * @throws UnsupportedOperationException if the <tt>remove</tt> operation
21.259 + * is not supported by this list
21.260 + */
21.261 + boolean remove(Object o);
21.262 +
21.263 +
21.264 + // Bulk Modification Operations
21.265 +
21.266 + /**
21.267 + * Returns <tt>true</tt> if this list contains all of the elements of the
21.268 + * specified collection.
21.269 + *
21.270 + * @param c collection to be checked for containment in this list
21.271 + * @return <tt>true</tt> if this list contains all of the elements of the
21.272 + * specified collection
21.273 + * @throws ClassCastException if the types of one or more elements
21.274 + * in the specified collection are incompatible with this
21.275 + * list
21.276 + * (<a href="Collection.html#optional-restrictions">optional</a>)
21.277 + * @throws NullPointerException if the specified collection contains one
21.278 + * or more null elements and this list does not permit null
21.279 + * elements
21.280 + * (<a href="Collection.html#optional-restrictions">optional</a>),
21.281 + * or if the specified collection is null
21.282 + * @see #contains(Object)
21.283 + */
21.284 + boolean containsAll(Collection<?> c);
21.285 +
21.286 + /**
21.287 + * Appends all of the elements in the specified collection to the end of
21.288 + * this list, in the order that they are returned by the specified
21.289 + * collection's iterator (optional operation). The behavior of this
21.290 + * operation is undefined if the specified collection is modified while
21.291 + * the operation is in progress. (Note that this will occur if the
21.292 + * specified collection is this list, and it's nonempty.)
21.293 + *
21.294 + * @param c collection containing elements to be added to this list
21.295 + * @return <tt>true</tt> if this list changed as a result of the call
21.296 + * @throws UnsupportedOperationException if the <tt>addAll</tt> operation
21.297 + * is not supported by this list
21.298 + * @throws ClassCastException if the class of an element of the specified
21.299 + * collection prevents it from being added to this list
21.300 + * @throws NullPointerException if the specified collection contains one
21.301 + * or more null elements and this list does not permit null
21.302 + * elements, or if the specified collection is null
21.303 + * @throws IllegalArgumentException if some property of an element of the
21.304 + * specified collection prevents it from being added to this list
21.305 + * @see #add(Object)
21.306 + */
21.307 + boolean addAll(Collection<? extends E> c);
21.308 +
21.309 + /**
21.310 + * Inserts all of the elements in the specified collection into this
21.311 + * list at the specified position (optional operation). Shifts the
21.312 + * element currently at that position (if any) and any subsequent
21.313 + * elements to the right (increases their indices). The new elements
21.314 + * will appear in this list in the order that they are returned by the
21.315 + * specified collection's iterator. The behavior of this operation is
21.316 + * undefined if the specified collection is modified while the
21.317 + * operation is in progress. (Note that this will occur if the specified
21.318 + * collection is this list, and it's nonempty.)
21.319 + *
21.320 + * @param index index at which to insert the first element from the
21.321 + * specified collection
21.322 + * @param c collection containing elements to be added to this list
21.323 + * @return <tt>true</tt> if this list changed as a result of the call
21.324 + * @throws UnsupportedOperationException if the <tt>addAll</tt> operation
21.325 + * is not supported by this list
21.326 + * @throws ClassCastException if the class of an element of the specified
21.327 + * collection prevents it from being added to this list
21.328 + * @throws NullPointerException if the specified collection contains one
21.329 + * or more null elements and this list does not permit null
21.330 + * elements, or if the specified collection is null
21.331 + * @throws IllegalArgumentException if some property of an element of the
21.332 + * specified collection prevents it from being added to this list
21.333 + * @throws IndexOutOfBoundsException if the index is out of range
21.334 + * (<tt>index < 0 || index > size()</tt>)
21.335 + */
21.336 + boolean addAll(int index, Collection<? extends E> c);
21.337 +
21.338 + /**
21.339 + * Removes from this list all of its elements that are contained in the
21.340 + * specified collection (optional operation).
21.341 + *
21.342 + * @param c collection containing elements to be removed from this list
21.343 + * @return <tt>true</tt> if this list changed as a result of the call
21.344 + * @throws UnsupportedOperationException if the <tt>removeAll</tt> operation
21.345 + * is not supported by this list
21.346 + * @throws ClassCastException if the class of an element of this list
21.347 + * is incompatible with the specified collection
21.348 + * (<a href="Collection.html#optional-restrictions">optional</a>)
21.349 + * @throws NullPointerException if this list contains a null element and the
21.350 + * specified collection does not permit null elements
21.351 + * (<a href="Collection.html#optional-restrictions">optional</a>),
21.352 + * or if the specified collection is null
21.353 + * @see #remove(Object)
21.354 + * @see #contains(Object)
21.355 + */
21.356 + boolean removeAll(Collection<?> c);
21.357 +
21.358 + /**
21.359 + * Retains only the elements in this list that are contained in the
21.360 + * specified collection (optional operation). In other words, removes
21.361 + * from this list all of its elements that are not contained in the
21.362 + * specified collection.
21.363 + *
21.364 + * @param c collection containing elements to be retained in this list
21.365 + * @return <tt>true</tt> if this list changed as a result of the call
21.366 + * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
21.367 + * is not supported by this list
21.368 + * @throws ClassCastException if the class of an element of this list
21.369 + * is incompatible with the specified collection
21.370 + * (<a href="Collection.html#optional-restrictions">optional</a>)
21.371 + * @throws NullPointerException if this list contains a null element and the
21.372 + * specified collection does not permit null elements
21.373 + * (<a href="Collection.html#optional-restrictions">optional</a>),
21.374 + * or if the specified collection is null
21.375 + * @see #remove(Object)
21.376 + * @see #contains(Object)
21.377 + */
21.378 + boolean retainAll(Collection<?> c);
21.379 +
21.380 + /**
21.381 + * Removes all of the elements from this list (optional operation).
21.382 + * The list will be empty after this call returns.
21.383 + *
21.384 + * @throws UnsupportedOperationException if the <tt>clear</tt> operation
21.385 + * is not supported by this list
21.386 + */
21.387 + void clear();
21.388 +
21.389 +
21.390 + // Comparison and hashing
21.391 +
21.392 + /**
21.393 + * Compares the specified object with this list for equality. Returns
21.394 + * <tt>true</tt> if and only if the specified object is also a list, both
21.395 + * lists have the same size, and all corresponding pairs of elements in
21.396 + * the two lists are <i>equal</i>. (Two elements <tt>e1</tt> and
21.397 + * <tt>e2</tt> are <i>equal</i> if <tt>(e1==null ? e2==null :
21.398 + * e1.equals(e2))</tt>.) In other words, two lists are defined to be
21.399 + * equal if they contain the same elements in the same order. This
21.400 + * definition ensures that the equals method works properly across
21.401 + * different implementations of the <tt>List</tt> interface.
21.402 + *
21.403 + * @param o the object to be compared for equality with this list
21.404 + * @return <tt>true</tt> if the specified object is equal to this list
21.405 + */
21.406 + boolean equals(Object o);
21.407 +
21.408 + /**
21.409 + * Returns the hash code value for this list. The hash code of a list
21.410 + * is defined to be the result of the following calculation:
21.411 + * <pre>
21.412 + * int hashCode = 1;
21.413 + * for (E e : list)
21.414 + * hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
21.415 + * </pre>
21.416 + * This ensures that <tt>list1.equals(list2)</tt> implies that
21.417 + * <tt>list1.hashCode()==list2.hashCode()</tt> for any two lists,
21.418 + * <tt>list1</tt> and <tt>list2</tt>, as required by the general
21.419 + * contract of {@link Object#hashCode}.
21.420 + *
21.421 + * @return the hash code value for this list
21.422 + * @see Object#equals(Object)
21.423 + * @see #equals(Object)
21.424 + */
21.425 + int hashCode();
21.426 +
21.427 +
21.428 + // Positional Access Operations
21.429 +
21.430 + /**
21.431 + * Returns the element at the specified position in this list.
21.432 + *
21.433 + * @param index index of the element to return
21.434 + * @return the element at the specified position in this list
21.435 + * @throws IndexOutOfBoundsException if the index is out of range
21.436 + * (<tt>index < 0 || index >= size()</tt>)
21.437 + */
21.438 + E get(int index);
21.439 +
21.440 + /**
21.441 + * Replaces the element at the specified position in this list with the
21.442 + * specified element (optional operation).
21.443 + *
21.444 + * @param index index of the element to replace
21.445 + * @param element element to be stored at the specified position
21.446 + * @return the element previously at the specified position
21.447 + * @throws UnsupportedOperationException if the <tt>set</tt> operation
21.448 + * is not supported by this list
21.449 + * @throws ClassCastException if the class of the specified element
21.450 + * prevents it from being added to this list
21.451 + * @throws NullPointerException if the specified element is null and
21.452 + * this list does not permit null elements
21.453 + * @throws IllegalArgumentException if some property of the specified
21.454 + * element prevents it from being added to this list
21.455 + * @throws IndexOutOfBoundsException if the index is out of range
21.456 + * (<tt>index < 0 || index >= size()</tt>)
21.457 + */
21.458 + E set(int index, E element);
21.459 +
21.460 + /**
21.461 + * Inserts the specified element at the specified position in this list
21.462 + * (optional operation). Shifts the element currently at that position
21.463 + * (if any) and any subsequent elements to the right (adds one to their
21.464 + * indices).
21.465 + *
21.466 + * @param index index at which the specified element is to be inserted
21.467 + * @param element element to be inserted
21.468 + * @throws UnsupportedOperationException if the <tt>add</tt> operation
21.469 + * is not supported by this list
21.470 + * @throws ClassCastException if the class of the specified element
21.471 + * prevents it from being added to this list
21.472 + * @throws NullPointerException if the specified element is null and
21.473 + * this list does not permit null elements
21.474 + * @throws IllegalArgumentException if some property of the specified
21.475 + * element prevents it from being added to this list
21.476 + * @throws IndexOutOfBoundsException if the index is out of range
21.477 + * (<tt>index < 0 || index > size()</tt>)
21.478 + */
21.479 + void add(int index, E element);
21.480 +
21.481 + /**
21.482 + * Removes the element at the specified position in this list (optional
21.483 + * operation). Shifts any subsequent elements to the left (subtracts one
21.484 + * from their indices). Returns the element that was removed from the
21.485 + * list.
21.486 + *
21.487 + * @param index the index of the element to be removed
21.488 + * @return the element previously at the specified position
21.489 + * @throws UnsupportedOperationException if the <tt>remove</tt> operation
21.490 + * is not supported by this list
21.491 + * @throws IndexOutOfBoundsException if the index is out of range
21.492 + * (<tt>index < 0 || index >= size()</tt>)
21.493 + */
21.494 + E remove(int index);
21.495 +
21.496 +
21.497 + // Search Operations
21.498 +
21.499 + /**
21.500 + * Returns the index of the first occurrence of the specified element
21.501 + * in this list, or -1 if this list does not contain the element.
21.502 + * More formally, returns the lowest index <tt>i</tt> such that
21.503 + * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
21.504 + * or -1 if there is no such index.
21.505 + *
21.506 + * @param o element to search for
21.507 + * @return the index of the first occurrence of the specified element in
21.508 + * this list, or -1 if this list does not contain the element
21.509 + * @throws ClassCastException if the type of the specified element
21.510 + * is incompatible with this list
21.511 + * (<a href="Collection.html#optional-restrictions">optional</a>)
21.512 + * @throws NullPointerException if the specified element is null and this
21.513 + * list does not permit null elements
21.514 + * (<a href="Collection.html#optional-restrictions">optional</a>)
21.515 + */
21.516 + int indexOf(Object o);
21.517 +
21.518 + /**
21.519 + * Returns the index of the last occurrence of the specified element
21.520 + * in this list, or -1 if this list does not contain the element.
21.521 + * More formally, returns the highest index <tt>i</tt> such that
21.522 + * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
21.523 + * or -1 if there is no such index.
21.524 + *
21.525 + * @param o element to search for
21.526 + * @return the index of the last occurrence of the specified element in
21.527 + * this list, or -1 if this list does not contain the element
21.528 + * @throws ClassCastException if the type of the specified element
21.529 + * is incompatible with this list
21.530 + * (<a href="Collection.html#optional-restrictions">optional</a>)
21.531 + * @throws NullPointerException if the specified element is null and this
21.532 + * list does not permit null elements
21.533 + * (<a href="Collection.html#optional-restrictions">optional</a>)
21.534 + */
21.535 + int lastIndexOf(Object o);
21.536 +
21.537 +
21.538 + // List Iterators
21.539 +
21.540 + /**
21.541 + * Returns a list iterator over the elements in this list (in proper
21.542 + * sequence).
21.543 + *
21.544 + * @return a list iterator over the elements in this list (in proper
21.545 + * sequence)
21.546 + */
21.547 + ListIterator<E> listIterator();
21.548 +
21.549 + /**
21.550 + * Returns a list iterator over the elements in this list (in proper
21.551 + * sequence), starting at the specified position in the list.
21.552 + * The specified index indicates the first element that would be
21.553 + * returned by an initial call to {@link ListIterator#next next}.
21.554 + * An initial call to {@link ListIterator#previous previous} would
21.555 + * return the element with the specified index minus one.
21.556 + *
21.557 + * @param index index of the first element to be returned from the
21.558 + * list iterator (by a call to {@link ListIterator#next next})
21.559 + * @return a list iterator over the elements in this list (in proper
21.560 + * sequence), starting at the specified position in the list
21.561 + * @throws IndexOutOfBoundsException if the index is out of range
21.562 + * ({@code index < 0 || index > size()})
21.563 + */
21.564 + ListIterator<E> listIterator(int index);
21.565 +
21.566 + // View
21.567 +
21.568 + /**
21.569 + * Returns a view of the portion of this list between the specified
21.570 + * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive. (If
21.571 + * <tt>fromIndex</tt> and <tt>toIndex</tt> are equal, the returned list is
21.572 + * empty.) The returned list is backed by this list, so non-structural
21.573 + * changes in the returned list are reflected in this list, and vice-versa.
21.574 + * The returned list supports all of the optional list operations supported
21.575 + * by this list.<p>
21.576 + *
21.577 + * This method eliminates the need for explicit range operations (of
21.578 + * the sort that commonly exist for arrays). Any operation that expects
21.579 + * a list can be used as a range operation by passing a subList view
21.580 + * instead of a whole list. For example, the following idiom
21.581 + * removes a range of elements from a list:
21.582 + * <pre>
21.583 + * list.subList(from, to).clear();
21.584 + * </pre>
21.585 + * Similar idioms may be constructed for <tt>indexOf</tt> and
21.586 + * <tt>lastIndexOf</tt>, and all of the algorithms in the
21.587 + * <tt>Collections</tt> class can be applied to a subList.<p>
21.588 + *
21.589 + * The semantics of the list returned by this method become undefined if
21.590 + * the backing list (i.e., this list) is <i>structurally modified</i> in
21.591 + * any way other than via the returned list. (Structural modifications are
21.592 + * those that change the size of this list, or otherwise perturb it in such
21.593 + * a fashion that iterations in progress may yield incorrect results.)
21.594 + *
21.595 + * @param fromIndex low endpoint (inclusive) of the subList
21.596 + * @param toIndex high endpoint (exclusive) of the subList
21.597 + * @return a view of the specified range within this list
21.598 + * @throws IndexOutOfBoundsException for an illegal endpoint index value
21.599 + * (<tt>fromIndex < 0 || toIndex > size ||
21.600 + * fromIndex > toIndex</tt>)
21.601 + */
21.602 + List<E> subList(int fromIndex, int toIndex);
21.603 +}
22.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
22.2 +++ b/emul/compact/src/main/java/java/util/ListIterator.java Wed Jan 23 22:33:45 2013 +0100
22.3 @@ -0,0 +1,195 @@
22.4 +/*
22.5 + * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
22.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
22.7 + *
22.8 + * This code is free software; you can redistribute it and/or modify it
22.9 + * under the terms of the GNU General Public License version 2 only, as
22.10 + * published by the Free Software Foundation. Oracle designates this
22.11 + * particular file as subject to the "Classpath" exception as provided
22.12 + * by Oracle in the LICENSE file that accompanied this code.
22.13 + *
22.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
22.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
22.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22.17 + * version 2 for more details (a copy is included in the LICENSE file that
22.18 + * accompanied this code).
22.19 + *
22.20 + * You should have received a copy of the GNU General Public License version
22.21 + * 2 along with this work; if not, write to the Free Software Foundation,
22.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
22.23 + *
22.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22.25 + * or visit www.oracle.com if you need additional information or have any
22.26 + * questions.
22.27 + */
22.28 +
22.29 +package java.util;
22.30 +
22.31 +/**
22.32 + * An iterator for lists that allows the programmer
22.33 + * to traverse the list in either direction, modify
22.34 + * the list during iteration, and obtain the iterator's
22.35 + * current position in the list. A {@code ListIterator}
22.36 + * has no current element; its <I>cursor position</I> always
22.37 + * lies between the element that would be returned by a call
22.38 + * to {@code previous()} and the element that would be
22.39 + * returned by a call to {@code next()}.
22.40 + * An iterator for a list of length {@code n} has {@code n+1} possible
22.41 + * cursor positions, as illustrated by the carets ({@code ^}) below:
22.42 + * <PRE>
22.43 + * Element(0) Element(1) Element(2) ... Element(n-1)
22.44 + * cursor positions: ^ ^ ^ ^ ^
22.45 + * </PRE>
22.46 + * Note that the {@link #remove} and {@link #set(Object)} methods are
22.47 + * <i>not</i> defined in terms of the cursor position; they are defined to
22.48 + * operate on the last element returned by a call to {@link #next} or
22.49 + * {@link #previous()}.
22.50 + *
22.51 + * <p>This interface is a member of the
22.52 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
22.53 + * Java Collections Framework</a>.
22.54 + *
22.55 + * @author Josh Bloch
22.56 + * @see Collection
22.57 + * @see List
22.58 + * @see Iterator
22.59 + * @see Enumeration
22.60 + * @see List#listIterator()
22.61 + * @since 1.2
22.62 + */
22.63 +public interface ListIterator<E> extends Iterator<E> {
22.64 + // Query Operations
22.65 +
22.66 + /**
22.67 + * Returns {@code true} if this list iterator has more elements when
22.68 + * traversing the list in the forward direction. (In other words,
22.69 + * returns {@code true} if {@link #next} would return an element rather
22.70 + * than throwing an exception.)
22.71 + *
22.72 + * @return {@code true} if the list iterator has more elements when
22.73 + * traversing the list in the forward direction
22.74 + */
22.75 + boolean hasNext();
22.76 +
22.77 + /**
22.78 + * Returns the next element in the list and advances the cursor position.
22.79 + * This method may be called repeatedly to iterate through the list,
22.80 + * or intermixed with calls to {@link #previous} to go back and forth.
22.81 + * (Note that alternating calls to {@code next} and {@code previous}
22.82 + * will return the same element repeatedly.)
22.83 + *
22.84 + * @return the next element in the list
22.85 + * @throws NoSuchElementException if the iteration has no next element
22.86 + */
22.87 + E next();
22.88 +
22.89 + /**
22.90 + * Returns {@code true} if this list iterator has more elements when
22.91 + * traversing the list in the reverse direction. (In other words,
22.92 + * returns {@code true} if {@link #previous} would return an element
22.93 + * rather than throwing an exception.)
22.94 + *
22.95 + * @return {@code true} if the list iterator has more elements when
22.96 + * traversing the list in the reverse direction
22.97 + */
22.98 + boolean hasPrevious();
22.99 +
22.100 + /**
22.101 + * Returns the previous element in the list and moves the cursor
22.102 + * position backwards. This method may be called repeatedly to
22.103 + * iterate through the list backwards, or intermixed with calls to
22.104 + * {@link #next} to go back and forth. (Note that alternating calls
22.105 + * to {@code next} and {@code previous} will return the same
22.106 + * element repeatedly.)
22.107 + *
22.108 + * @return the previous element in the list
22.109 + * @throws NoSuchElementException if the iteration has no previous
22.110 + * element
22.111 + */
22.112 + E previous();
22.113 +
22.114 + /**
22.115 + * Returns the index of the element that would be returned by a
22.116 + * subsequent call to {@link #next}. (Returns list size if the list
22.117 + * iterator is at the end of the list.)
22.118 + *
22.119 + * @return the index of the element that would be returned by a
22.120 + * subsequent call to {@code next}, or list size if the list
22.121 + * iterator is at the end of the list
22.122 + */
22.123 + int nextIndex();
22.124 +
22.125 + /**
22.126 + * Returns the index of the element that would be returned by a
22.127 + * subsequent call to {@link #previous}. (Returns -1 if the list
22.128 + * iterator is at the beginning of the list.)
22.129 + *
22.130 + * @return the index of the element that would be returned by a
22.131 + * subsequent call to {@code previous}, or -1 if the list
22.132 + * iterator is at the beginning of the list
22.133 + */
22.134 + int previousIndex();
22.135 +
22.136 +
22.137 + // Modification Operations
22.138 +
22.139 + /**
22.140 + * Removes from the list the last element that was returned by {@link
22.141 + * #next} or {@link #previous} (optional operation). This call can
22.142 + * only be made once per call to {@code next} or {@code previous}.
22.143 + * It can be made only if {@link #add} has not been
22.144 + * called after the last call to {@code next} or {@code previous}.
22.145 + *
22.146 + * @throws UnsupportedOperationException if the {@code remove}
22.147 + * operation is not supported by this list iterator
22.148 + * @throws IllegalStateException if neither {@code next} nor
22.149 + * {@code previous} have been called, or {@code remove} or
22.150 + * {@code add} have been called after the last call to
22.151 + * {@code next} or {@code previous}
22.152 + */
22.153 + void remove();
22.154 +
22.155 + /**
22.156 + * Replaces the last element returned by {@link #next} or
22.157 + * {@link #previous} with the specified element (optional operation).
22.158 + * This call can be made only if neither {@link #remove} nor {@link
22.159 + * #add} have been called after the last call to {@code next} or
22.160 + * {@code previous}.
22.161 + *
22.162 + * @param e the element with which to replace the last element returned by
22.163 + * {@code next} or {@code previous}
22.164 + * @throws UnsupportedOperationException if the {@code set} operation
22.165 + * is not supported by this list iterator
22.166 + * @throws ClassCastException if the class of the specified element
22.167 + * prevents it from being added to this list
22.168 + * @throws IllegalArgumentException if some aspect of the specified
22.169 + * element prevents it from being added to this list
22.170 + * @throws IllegalStateException if neither {@code next} nor
22.171 + * {@code previous} have been called, or {@code remove} or
22.172 + * {@code add} have been called after the last call to
22.173 + * {@code next} or {@code previous}
22.174 + */
22.175 + void set(E e);
22.176 +
22.177 + /**
22.178 + * Inserts the specified element into the list (optional operation).
22.179 + * The element is inserted immediately before the element that
22.180 + * would be returned by {@link #next}, if any, and after the element
22.181 + * that would be returned by {@link #previous}, if any. (If the
22.182 + * list contains no elements, the new element becomes the sole element
22.183 + * on the list.) The new element is inserted before the implicit
22.184 + * cursor: a subsequent call to {@code next} would be unaffected, and a
22.185 + * subsequent call to {@code previous} would return the new element.
22.186 + * (This call increases by one the value that would be returned by a
22.187 + * call to {@code nextIndex} or {@code previousIndex}.)
22.188 + *
22.189 + * @param e the element to insert
22.190 + * @throws UnsupportedOperationException if the {@code add} method is
22.191 + * not supported by this list iterator
22.192 + * @throws ClassCastException if the class of the specified element
22.193 + * prevents it from being added to this list
22.194 + * @throws IllegalArgumentException if some aspect of this element
22.195 + * prevents it from being added to this list
22.196 + */
22.197 + void add(E e);
22.198 +}
23.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
23.2 +++ b/emul/compact/src/main/java/java/util/Map.java Wed Jan 23 22:33:45 2013 +0100
23.3 @@ -0,0 +1,478 @@
23.4 +/*
23.5 + * Copyright (c) 1997, 2006, 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.util;
23.30 +
23.31 +/**
23.32 + * An object that maps keys to values. A map cannot contain duplicate keys;
23.33 + * each key can map to at most one value.
23.34 + *
23.35 + * <p>This interface takes the place of the <tt>Dictionary</tt> class, which
23.36 + * was a totally abstract class rather than an interface.
23.37 + *
23.38 + * <p>The <tt>Map</tt> interface provides three <i>collection views</i>, which
23.39 + * allow a map's contents to be viewed as a set of keys, collection of values,
23.40 + * or set of key-value mappings. The <i>order</i> of a map is defined as
23.41 + * the order in which the iterators on the map's collection views return their
23.42 + * elements. Some map implementations, like the <tt>TreeMap</tt> class, make
23.43 + * specific guarantees as to their order; others, like the <tt>HashMap</tt>
23.44 + * class, do not.
23.45 + *
23.46 + * <p>Note: great care must be exercised if mutable objects are used as map
23.47 + * keys. The behavior of a map is not specified if the value of an object is
23.48 + * changed in a manner that affects <tt>equals</tt> comparisons while the
23.49 + * object is a key in the map. A special case of this prohibition is that it
23.50 + * is not permissible for a map to contain itself as a key. While it is
23.51 + * permissible for a map to contain itself as a value, extreme caution is
23.52 + * advised: the <tt>equals</tt> and <tt>hashCode</tt> methods are no longer
23.53 + * well defined on such a map.
23.54 + *
23.55 + * <p>All general-purpose map implementation classes should provide two
23.56 + * "standard" constructors: a void (no arguments) constructor which creates an
23.57 + * empty map, and a constructor with a single argument of type <tt>Map</tt>,
23.58 + * which creates a new map with the same key-value mappings as its argument.
23.59 + * In effect, the latter constructor allows the user to copy any map,
23.60 + * producing an equivalent map of the desired class. There is no way to
23.61 + * enforce this recommendation (as interfaces cannot contain constructors) but
23.62 + * all of the general-purpose map implementations in the JDK comply.
23.63 + *
23.64 + * <p>The "destructive" methods contained in this interface, that is, the
23.65 + * methods that modify the map on which they operate, are specified to throw
23.66 + * <tt>UnsupportedOperationException</tt> if this map does not support the
23.67 + * operation. If this is the case, these methods may, but are not required
23.68 + * to, throw an <tt>UnsupportedOperationException</tt> if the invocation would
23.69 + * have no effect on the map. For example, invoking the {@link #putAll(Map)}
23.70 + * method on an unmodifiable map may, but is not required to, throw the
23.71 + * exception if the map whose mappings are to be "superimposed" is empty.
23.72 + *
23.73 + * <p>Some map implementations have restrictions on the keys and values they
23.74 + * may contain. For example, some implementations prohibit null keys and
23.75 + * values, and some have restrictions on the types of their keys. Attempting
23.76 + * to insert an ineligible key or value throws an unchecked exception,
23.77 + * typically <tt>NullPointerException</tt> or <tt>ClassCastException</tt>.
23.78 + * Attempting to query the presence of an ineligible key or value may throw an
23.79 + * exception, or it may simply return false; some implementations will exhibit
23.80 + * the former behavior and some will exhibit the latter. More generally,
23.81 + * attempting an operation on an ineligible key or value whose completion
23.82 + * would not result in the insertion of an ineligible element into the map may
23.83 + * throw an exception or it may succeed, at the option of the implementation.
23.84 + * Such exceptions are marked as "optional" in the specification for this
23.85 + * interface.
23.86 + *
23.87 + * <p>This interface is a member of the
23.88 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
23.89 + * Java Collections Framework</a>.
23.90 + *
23.91 + * <p>Many methods in Collections Framework interfaces are defined
23.92 + * in terms of the {@link Object#equals(Object) equals} method. For
23.93 + * example, the specification for the {@link #containsKey(Object)
23.94 + * containsKey(Object key)} method says: "returns <tt>true</tt> if and
23.95 + * only if this map contains a mapping for a key <tt>k</tt> such that
23.96 + * <tt>(key==null ? k==null : key.equals(k))</tt>." This specification should
23.97 + * <i>not</i> be construed to imply that invoking <tt>Map.containsKey</tt>
23.98 + * with a non-null argument <tt>key</tt> will cause <tt>key.equals(k)</tt> to
23.99 + * be invoked for any key <tt>k</tt>. Implementations are free to
23.100 + * implement optimizations whereby the <tt>equals</tt> invocation is avoided,
23.101 + * for example, by first comparing the hash codes of the two keys. (The
23.102 + * {@link Object#hashCode()} specification guarantees that two objects with
23.103 + * unequal hash codes cannot be equal.) More generally, implementations of
23.104 + * the various Collections Framework interfaces are free to take advantage of
23.105 + * the specified behavior of underlying {@link Object} methods wherever the
23.106 + * implementor deems it appropriate.
23.107 + *
23.108 + * @param <K> the type of keys maintained by this map
23.109 + * @param <V> the type of mapped values
23.110 + *
23.111 + * @author Josh Bloch
23.112 + * @see HashMap
23.113 + * @see TreeMap
23.114 + * @see Hashtable
23.115 + * @see SortedMap
23.116 + * @see Collection
23.117 + * @see Set
23.118 + * @since 1.2
23.119 + */
23.120 +public interface Map<K,V> {
23.121 + // Query Operations
23.122 +
23.123 + /**
23.124 + * Returns the number of key-value mappings in this map. If the
23.125 + * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
23.126 + * <tt>Integer.MAX_VALUE</tt>.
23.127 + *
23.128 + * @return the number of key-value mappings in this map
23.129 + */
23.130 + int size();
23.131 +
23.132 + /**
23.133 + * Returns <tt>true</tt> if this map contains no key-value mappings.
23.134 + *
23.135 + * @return <tt>true</tt> if this map contains no key-value mappings
23.136 + */
23.137 + boolean isEmpty();
23.138 +
23.139 + /**
23.140 + * Returns <tt>true</tt> if this map contains a mapping for the specified
23.141 + * key. More formally, returns <tt>true</tt> if and only if
23.142 + * this map contains a mapping for a key <tt>k</tt> such that
23.143 + * <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be
23.144 + * at most one such mapping.)
23.145 + *
23.146 + * @param key key whose presence in this map is to be tested
23.147 + * @return <tt>true</tt> if this map contains a mapping for the specified
23.148 + * key
23.149 + * @throws ClassCastException if the key is of an inappropriate type for
23.150 + * this map
23.151 + * (<a href="Collection.html#optional-restrictions">optional</a>)
23.152 + * @throws NullPointerException if the specified key is null and this map
23.153 + * does not permit null keys
23.154 + * (<a href="Collection.html#optional-restrictions">optional</a>)
23.155 + */
23.156 + boolean containsKey(Object key);
23.157 +
23.158 + /**
23.159 + * Returns <tt>true</tt> if this map maps one or more keys to the
23.160 + * specified value. More formally, returns <tt>true</tt> if and only if
23.161 + * this map contains at least one mapping to a value <tt>v</tt> such that
23.162 + * <tt>(value==null ? v==null : value.equals(v))</tt>. This operation
23.163 + * will probably require time linear in the map size for most
23.164 + * implementations of the <tt>Map</tt> interface.
23.165 + *
23.166 + * @param value value whose presence in this map is to be tested
23.167 + * @return <tt>true</tt> if this map maps one or more keys to the
23.168 + * specified value
23.169 + * @throws ClassCastException if the value is of an inappropriate type for
23.170 + * this map
23.171 + * (<a href="Collection.html#optional-restrictions">optional</a>)
23.172 + * @throws NullPointerException if the specified value is null and this
23.173 + * map does not permit null values
23.174 + * (<a href="Collection.html#optional-restrictions">optional</a>)
23.175 + */
23.176 + boolean containsValue(Object value);
23.177 +
23.178 + /**
23.179 + * Returns the value to which the specified key is mapped,
23.180 + * or {@code null} if this map contains no mapping for the key.
23.181 + *
23.182 + * <p>More formally, if this map contains a mapping from a key
23.183 + * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
23.184 + * key.equals(k))}, then this method returns {@code v}; otherwise
23.185 + * it returns {@code null}. (There can be at most one such mapping.)
23.186 + *
23.187 + * <p>If this map permits null values, then a return value of
23.188 + * {@code null} does not <i>necessarily</i> indicate that the map
23.189 + * contains no mapping for the key; it's also possible that the map
23.190 + * explicitly maps the key to {@code null}. The {@link #containsKey
23.191 + * containsKey} operation may be used to distinguish these two cases.
23.192 + *
23.193 + * @param key the key whose associated value is to be returned
23.194 + * @return the value to which the specified key is mapped, or
23.195 + * {@code null} if this map contains no mapping for the key
23.196 + * @throws ClassCastException if the key is of an inappropriate type for
23.197 + * this map
23.198 + * (<a href="Collection.html#optional-restrictions">optional</a>)
23.199 + * @throws NullPointerException if the specified key is null and this map
23.200 + * does not permit null keys
23.201 + * (<a href="Collection.html#optional-restrictions">optional</a>)
23.202 + */
23.203 + V get(Object key);
23.204 +
23.205 + // Modification Operations
23.206 +
23.207 + /**
23.208 + * Associates the specified value with the specified key in this map
23.209 + * (optional operation). If the map previously contained a mapping for
23.210 + * the key, the old value is replaced by the specified value. (A map
23.211 + * <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
23.212 + * if {@link #containsKey(Object) m.containsKey(k)} would return
23.213 + * <tt>true</tt>.)
23.214 + *
23.215 + * @param key key with which the specified value is to be associated
23.216 + * @param value value to be associated with the specified key
23.217 + * @return the previous value associated with <tt>key</tt>, or
23.218 + * <tt>null</tt> if there was no mapping for <tt>key</tt>.
23.219 + * (A <tt>null</tt> return can also indicate that the map
23.220 + * previously associated <tt>null</tt> with <tt>key</tt>,
23.221 + * if the implementation supports <tt>null</tt> values.)
23.222 + * @throws UnsupportedOperationException if the <tt>put</tt> operation
23.223 + * is not supported by this map
23.224 + * @throws ClassCastException if the class of the specified key or value
23.225 + * prevents it from being stored in this map
23.226 + * @throws NullPointerException if the specified key or value is null
23.227 + * and this map does not permit null keys or values
23.228 + * @throws IllegalArgumentException if some property of the specified key
23.229 + * or value prevents it from being stored in this map
23.230 + */
23.231 + V put(K key, V value);
23.232 +
23.233 + /**
23.234 + * Removes the mapping for a key from this map if it is present
23.235 + * (optional operation). More formally, if this map contains a mapping
23.236 + * from key <tt>k</tt> to value <tt>v</tt> such that
23.237 + * <code>(key==null ? k==null : key.equals(k))</code>, that mapping
23.238 + * is removed. (The map can contain at most one such mapping.)
23.239 + *
23.240 + * <p>Returns the value to which this map previously associated the key,
23.241 + * or <tt>null</tt> if the map contained no mapping for the key.
23.242 + *
23.243 + * <p>If this map permits null values, then a return value of
23.244 + * <tt>null</tt> does not <i>necessarily</i> indicate that the map
23.245 + * contained no mapping for the key; it's also possible that the map
23.246 + * explicitly mapped the key to <tt>null</tt>.
23.247 + *
23.248 + * <p>The map will not contain a mapping for the specified key once the
23.249 + * call returns.
23.250 + *
23.251 + * @param key key whose mapping is to be removed from the map
23.252 + * @return the previous value associated with <tt>key</tt>, or
23.253 + * <tt>null</tt> if there was no mapping for <tt>key</tt>.
23.254 + * @throws UnsupportedOperationException if the <tt>remove</tt> operation
23.255 + * is not supported by this map
23.256 + * @throws ClassCastException if the key is of an inappropriate type for
23.257 + * this map
23.258 + * (<a href="Collection.html#optional-restrictions">optional</a>)
23.259 + * @throws NullPointerException if the specified key is null and this
23.260 + * map does not permit null keys
23.261 + * (<a href="Collection.html#optional-restrictions">optional</a>)
23.262 + */
23.263 + V remove(Object key);
23.264 +
23.265 +
23.266 + // Bulk Operations
23.267 +
23.268 + /**
23.269 + * Copies all of the mappings from the specified map to this map
23.270 + * (optional operation). The effect of this call is equivalent to that
23.271 + * of calling {@link #put(Object,Object) put(k, v)} on this map once
23.272 + * for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
23.273 + * specified map. The behavior of this operation is undefined if the
23.274 + * specified map is modified while the operation is in progress.
23.275 + *
23.276 + * @param m mappings to be stored in this map
23.277 + * @throws UnsupportedOperationException if the <tt>putAll</tt> operation
23.278 + * is not supported by this map
23.279 + * @throws ClassCastException if the class of a key or value in the
23.280 + * specified map prevents it from being stored in this map
23.281 + * @throws NullPointerException if the specified map is null, or if
23.282 + * this map does not permit null keys or values, and the
23.283 + * specified map contains null keys or values
23.284 + * @throws IllegalArgumentException if some property of a key or value in
23.285 + * the specified map prevents it from being stored in this map
23.286 + */
23.287 + void putAll(Map<? extends K, ? extends V> m);
23.288 +
23.289 + /**
23.290 + * Removes all of the mappings from this map (optional operation).
23.291 + * The map will be empty after this call returns.
23.292 + *
23.293 + * @throws UnsupportedOperationException if the <tt>clear</tt> operation
23.294 + * is not supported by this map
23.295 + */
23.296 + void clear();
23.297 +
23.298 +
23.299 + // Views
23.300 +
23.301 + /**
23.302 + * Returns a {@link Set} view of the keys contained in this map.
23.303 + * The set is backed by the map, so changes to the map are
23.304 + * reflected in the set, and vice-versa. If the map is modified
23.305 + * while an iteration over the set is in progress (except through
23.306 + * the iterator's own <tt>remove</tt> operation), the results of
23.307 + * the iteration are undefined. The set supports element removal,
23.308 + * which removes the corresponding mapping from the map, via the
23.309 + * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
23.310 + * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
23.311 + * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
23.312 + * operations.
23.313 + *
23.314 + * @return a set view of the keys contained in this map
23.315 + */
23.316 + Set<K> keySet();
23.317 +
23.318 + /**
23.319 + * Returns a {@link Collection} view of the values contained in this map.
23.320 + * The collection is backed by the map, so changes to the map are
23.321 + * reflected in the collection, and vice-versa. If the map is
23.322 + * modified while an iteration over the collection is in progress
23.323 + * (except through the iterator's own <tt>remove</tt> operation),
23.324 + * the results of the iteration are undefined. The collection
23.325 + * supports element removal, which removes the corresponding
23.326 + * mapping from the map, via the <tt>Iterator.remove</tt>,
23.327 + * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
23.328 + * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
23.329 + * support the <tt>add</tt> or <tt>addAll</tt> operations.
23.330 + *
23.331 + * @return a collection view of the values contained in this map
23.332 + */
23.333 + Collection<V> values();
23.334 +
23.335 + /**
23.336 + * Returns a {@link Set} view of the mappings contained in this map.
23.337 + * The set is backed by the map, so changes to the map are
23.338 + * reflected in the set, and vice-versa. If the map is modified
23.339 + * while an iteration over the set is in progress (except through
23.340 + * the iterator's own <tt>remove</tt> operation, or through the
23.341 + * <tt>setValue</tt> operation on a map entry returned by the
23.342 + * iterator) the results of the iteration are undefined. The set
23.343 + * supports element removal, which removes the corresponding
23.344 + * mapping from the map, via the <tt>Iterator.remove</tt>,
23.345 + * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
23.346 + * <tt>clear</tt> operations. It does not support the
23.347 + * <tt>add</tt> or <tt>addAll</tt> operations.
23.348 + *
23.349 + * @return a set view of the mappings contained in this map
23.350 + */
23.351 + Set<Map.Entry<K, V>> entrySet();
23.352 +
23.353 + /**
23.354 + * A map entry (key-value pair). The <tt>Map.entrySet</tt> method returns
23.355 + * a collection-view of the map, whose elements are of this class. The
23.356 + * <i>only</i> way to obtain a reference to a map entry is from the
23.357 + * iterator of this collection-view. These <tt>Map.Entry</tt> objects are
23.358 + * valid <i>only</i> for the duration of the iteration; more formally,
23.359 + * the behavior of a map entry is undefined if the backing map has been
23.360 + * modified after the entry was returned by the iterator, except through
23.361 + * the <tt>setValue</tt> operation on the map entry.
23.362 + *
23.363 + * @see Map#entrySet()
23.364 + * @since 1.2
23.365 + */
23.366 + interface Entry<K,V> {
23.367 + /**
23.368 + * Returns the key corresponding to this entry.
23.369 + *
23.370 + * @return the key corresponding to this entry
23.371 + * @throws IllegalStateException implementations may, but are not
23.372 + * required to, throw this exception if the entry has been
23.373 + * removed from the backing map.
23.374 + */
23.375 + K getKey();
23.376 +
23.377 + /**
23.378 + * Returns the value corresponding to this entry. If the mapping
23.379 + * has been removed from the backing map (by the iterator's
23.380 + * <tt>remove</tt> operation), the results of this call are undefined.
23.381 + *
23.382 + * @return the value corresponding to this entry
23.383 + * @throws IllegalStateException implementations may, but are not
23.384 + * required to, throw this exception if the entry has been
23.385 + * removed from the backing map.
23.386 + */
23.387 + V getValue();
23.388 +
23.389 + /**
23.390 + * Replaces the value corresponding to this entry with the specified
23.391 + * value (optional operation). (Writes through to the map.) The
23.392 + * behavior of this call is undefined if the mapping has already been
23.393 + * removed from the map (by the iterator's <tt>remove</tt> operation).
23.394 + *
23.395 + * @param value new value to be stored in this entry
23.396 + * @return old value corresponding to the entry
23.397 + * @throws UnsupportedOperationException if the <tt>put</tt> operation
23.398 + * is not supported by the backing map
23.399 + * @throws ClassCastException if the class of the specified value
23.400 + * prevents it from being stored in the backing map
23.401 + * @throws NullPointerException if the backing map does not permit
23.402 + * null values, and the specified value is null
23.403 + * @throws IllegalArgumentException if some property of this value
23.404 + * prevents it from being stored in the backing map
23.405 + * @throws IllegalStateException implementations may, but are not
23.406 + * required to, throw this exception if the entry has been
23.407 + * removed from the backing map.
23.408 + */
23.409 + V setValue(V value);
23.410 +
23.411 + /**
23.412 + * Compares the specified object with this entry for equality.
23.413 + * Returns <tt>true</tt> if the given object is also a map entry and
23.414 + * the two entries represent the same mapping. More formally, two
23.415 + * entries <tt>e1</tt> and <tt>e2</tt> represent the same mapping
23.416 + * if<pre>
23.417 + * (e1.getKey()==null ?
23.418 + * e2.getKey()==null : e1.getKey().equals(e2.getKey())) &&
23.419 + * (e1.getValue()==null ?
23.420 + * e2.getValue()==null : e1.getValue().equals(e2.getValue()))
23.421 + * </pre>
23.422 + * This ensures that the <tt>equals</tt> method works properly across
23.423 + * different implementations of the <tt>Map.Entry</tt> interface.
23.424 + *
23.425 + * @param o object to be compared for equality with this map entry
23.426 + * @return <tt>true</tt> if the specified object is equal to this map
23.427 + * entry
23.428 + */
23.429 + boolean equals(Object o);
23.430 +
23.431 + /**
23.432 + * Returns the hash code value for this map entry. The hash code
23.433 + * of a map entry <tt>e</tt> is defined to be: <pre>
23.434 + * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^
23.435 + * (e.getValue()==null ? 0 : e.getValue().hashCode())
23.436 + * </pre>
23.437 + * This ensures that <tt>e1.equals(e2)</tt> implies that
23.438 + * <tt>e1.hashCode()==e2.hashCode()</tt> for any two Entries
23.439 + * <tt>e1</tt> and <tt>e2</tt>, as required by the general
23.440 + * contract of <tt>Object.hashCode</tt>.
23.441 + *
23.442 + * @return the hash code value for this map entry
23.443 + * @see Object#hashCode()
23.444 + * @see Object#equals(Object)
23.445 + * @see #equals(Object)
23.446 + */
23.447 + int hashCode();
23.448 + }
23.449 +
23.450 + // Comparison and hashing
23.451 +
23.452 + /**
23.453 + * Compares the specified object with this map for equality. Returns
23.454 + * <tt>true</tt> if the given object is also a map and the two maps
23.455 + * represent the same mappings. More formally, two maps <tt>m1</tt> and
23.456 + * <tt>m2</tt> represent the same mappings if
23.457 + * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
23.458 + * <tt>equals</tt> method works properly across different implementations
23.459 + * of the <tt>Map</tt> interface.
23.460 + *
23.461 + * @param o object to be compared for equality with this map
23.462 + * @return <tt>true</tt> if the specified object is equal to this map
23.463 + */
23.464 + boolean equals(Object o);
23.465 +
23.466 + /**
23.467 + * Returns the hash code value for this map. The hash code of a map is
23.468 + * defined to be the sum of the hash codes of each entry in the map's
23.469 + * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
23.470 + * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
23.471 + * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
23.472 + * {@link Object#hashCode}.
23.473 + *
23.474 + * @return the hash code value for this map
23.475 + * @see Map.Entry#hashCode()
23.476 + * @see Object#equals(Object)
23.477 + * @see #equals(Object)
23.478 + */
23.479 + int hashCode();
23.480 +
23.481 +}
24.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
24.2 +++ b/emul/compact/src/main/java/java/util/RandomAccess.java Wed Jan 23 22:33:45 2013 +0100
24.3 @@ -0,0 +1,68 @@
24.4 +/*
24.5 + * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
24.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
24.7 + *
24.8 + * This code is free software; you can redistribute it and/or modify it
24.9 + * under the terms of the GNU General Public License version 2 only, as
24.10 + * published by the Free Software Foundation. Oracle designates this
24.11 + * particular file as subject to the "Classpath" exception as provided
24.12 + * by Oracle in the LICENSE file that accompanied this code.
24.13 + *
24.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
24.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
24.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
24.17 + * version 2 for more details (a copy is included in the LICENSE file that
24.18 + * accompanied this code).
24.19 + *
24.20 + * You should have received a copy of the GNU General Public License version
24.21 + * 2 along with this work; if not, write to the Free Software Foundation,
24.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24.23 + *
24.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
24.25 + * or visit www.oracle.com if you need additional information or have any
24.26 + * questions.
24.27 + */
24.28 +
24.29 +package java.util;
24.30 +
24.31 +/**
24.32 + * Marker interface used by <tt>List</tt> implementations to indicate that
24.33 + * they support fast (generally constant time) random access. The primary
24.34 + * purpose of this interface is to allow generic algorithms to alter their
24.35 + * behavior to provide good performance when applied to either random or
24.36 + * sequential access lists.
24.37 + *
24.38 + * <p>The best algorithms for manipulating random access lists (such as
24.39 + * <tt>ArrayList</tt>) can produce quadratic behavior when applied to
24.40 + * sequential access lists (such as <tt>LinkedList</tt>). Generic list
24.41 + * algorithms are encouraged to check whether the given list is an
24.42 + * <tt>instanceof</tt> this interface before applying an algorithm that would
24.43 + * provide poor performance if it were applied to a sequential access list,
24.44 + * and to alter their behavior if necessary to guarantee acceptable
24.45 + * performance.
24.46 + *
24.47 + * <p>It is recognized that the distinction between random and sequential
24.48 + * access is often fuzzy. For example, some <tt>List</tt> implementations
24.49 + * provide asymptotically linear access times if they get huge, but constant
24.50 + * access times in practice. Such a <tt>List</tt> implementation
24.51 + * should generally implement this interface. As a rule of thumb, a
24.52 + * <tt>List</tt> implementation should implement this interface if,
24.53 + * for typical instances of the class, this loop:
24.54 + * <pre>
24.55 + * for (int i=0, n=list.size(); i < n; i++)
24.56 + * list.get(i);
24.57 + * </pre>
24.58 + * runs faster than this loop:
24.59 + * <pre>
24.60 + * for (Iterator i=list.iterator(); i.hasNext(); )
24.61 + * i.next();
24.62 + * </pre>
24.63 + *
24.64 + * <p>This interface is a member of the
24.65 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
24.66 + * Java Collections Framework</a>.
24.67 + *
24.68 + * @since 1.4
24.69 + */
24.70 +public interface RandomAccess {
24.71 +}
25.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
25.2 +++ b/emul/compact/src/main/java/java/util/ServiceConfigurationError.java Wed Jan 23 22:33:45 2013 +0100
25.3 @@ -0,0 +1,87 @@
25.4 +/*
25.5 + * Copyright (c) 2005, 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.util;
25.30 +
25.31 +
25.32 +/**
25.33 + * Error thrown when something goes wrong while loading a service provider.
25.34 + *
25.35 + * <p> This error will be thrown in the following situations:
25.36 + *
25.37 + * <ul>
25.38 + *
25.39 + * <li> The format of a provider-configuration file violates the <a
25.40 + * href="ServiceLoader.html#format">specification</a>; </li>
25.41 + *
25.42 + * <li> An {@link java.io.IOException IOException} occurs while reading a
25.43 + * provider-configuration file; </li>
25.44 + *
25.45 + * <li> A concrete provider class named in a provider-configuration file
25.46 + * cannot be found; </li>
25.47 + *
25.48 + * <li> A concrete provider class is not a subclass of the service class;
25.49 + * </li>
25.50 + *
25.51 + * <li> A concrete provider class cannot be instantiated; or
25.52 + *
25.53 + * <li> Some other kind of error occurs. </li>
25.54 + *
25.55 + * </ul>
25.56 + *
25.57 + *
25.58 + * @author Mark Reinhold
25.59 + * @since 1.6
25.60 + */
25.61 +
25.62 +public class ServiceConfigurationError
25.63 + extends Error
25.64 +{
25.65 +
25.66 + private static final long serialVersionUID = 74132770414881L;
25.67 +
25.68 + /**
25.69 + * Constructs a new instance with the specified message.
25.70 + *
25.71 + * @param msg The message, or <tt>null</tt> if there is no message
25.72 + *
25.73 + */
25.74 + public ServiceConfigurationError(String msg) {
25.75 + super(msg);
25.76 + }
25.77 +
25.78 + /**
25.79 + * Constructs a new instance with the specified message and cause.
25.80 + *
25.81 + * @param msg The message, or <tt>null</tt> if there is no message
25.82 + *
25.83 + * @param cause The cause, or <tt>null</tt> if the cause is nonexistent
25.84 + * or unknown
25.85 + */
25.86 + public ServiceConfigurationError(String msg, Throwable cause) {
25.87 + super(msg, cause);
25.88 + }
25.89 +
25.90 +}
26.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
26.2 +++ b/emul/compact/src/main/java/java/util/ServiceLoader.java Wed Jan 23 22:33:45 2013 +0100
26.3 @@ -0,0 +1,538 @@
26.4 +/*
26.5 + * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
26.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
26.7 + *
26.8 + * This code is free software; you can redistribute it and/or modify it
26.9 + * under the terms of the GNU General Public License version 2 only, as
26.10 + * published by the Free Software Foundation. Oracle designates this
26.11 + * particular file as subject to the "Classpath" exception as provided
26.12 + * by Oracle in the LICENSE file that accompanied this code.
26.13 + *
26.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
26.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
26.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
26.17 + * version 2 for more details (a copy is included in the LICENSE file that
26.18 + * accompanied this code).
26.19 + *
26.20 + * You should have received a copy of the GNU General Public License version
26.21 + * 2 along with this work; if not, write to the Free Software Foundation,
26.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26.23 + *
26.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
26.25 + * or visit www.oracle.com if you need additional information or have any
26.26 + * questions.
26.27 + */
26.28 +
26.29 +package java.util;
26.30 +
26.31 +import java.io.BufferedReader;
26.32 +import java.io.IOException;
26.33 +import java.io.InputStream;
26.34 +import java.io.InputStreamReader;
26.35 +import java.net.URL;
26.36 +import java.util.ArrayList;
26.37 +import java.util.Enumeration;
26.38 +import java.util.Iterator;
26.39 +import java.util.List;
26.40 +import java.util.NoSuchElementException;
26.41 +
26.42 +
26.43 +/**
26.44 + * A simple service-provider loading facility.
26.45 + *
26.46 + * <p> A <i>service</i> is a well-known set of interfaces and (usually
26.47 + * abstract) classes. A <i>service provider</i> is a specific implementation
26.48 + * of a service. The classes in a provider typically implement the interfaces
26.49 + * and subclass the classes defined in the service itself. Service providers
26.50 + * can be installed in an implementation of the Java platform in the form of
26.51 + * extensions, that is, jar files placed into any of the usual extension
26.52 + * directories. Providers can also be made available by adding them to the
26.53 + * application's class path or by some other platform-specific means.
26.54 + *
26.55 + * <p> For the purpose of loading, a service is represented by a single type,
26.56 + * that is, a single interface or abstract class. (A concrete class can be
26.57 + * used, but this is not recommended.) A provider of a given service contains
26.58 + * one or more concrete classes that extend this <i>service type</i> with data
26.59 + * and code specific to the provider. The <i>provider class</i> is typically
26.60 + * not the entire provider itself but rather a proxy which contains enough
26.61 + * information to decide whether the provider is able to satisfy a particular
26.62 + * request together with code that can create the actual provider on demand.
26.63 + * The details of provider classes tend to be highly service-specific; no
26.64 + * single class or interface could possibly unify them, so no such type is
26.65 + * defined here. The only requirement enforced by this facility is that
26.66 + * provider classes must have a zero-argument constructor so that they can be
26.67 + * instantiated during loading.
26.68 + *
26.69 + * <p><a name="format"> A service provider is identified by placing a
26.70 + * <i>provider-configuration file</i> in the resource directory
26.71 + * <tt>META-INF/services</tt>. The file's name is the fully-qualified <a
26.72 + * href="../lang/ClassLoader.html#name">binary name</a> of the service's type.
26.73 + * The file contains a list of fully-qualified binary names of concrete
26.74 + * provider classes, one per line. Space and tab characters surrounding each
26.75 + * name, as well as blank lines, are ignored. The comment character is
26.76 + * <tt>'#'</tt> (<tt>'\u0023'</tt>, <font size="-1">NUMBER SIGN</font>); on
26.77 + * each line all characters following the first comment character are ignored.
26.78 + * The file must be encoded in UTF-8.
26.79 + *
26.80 + * <p> If a particular concrete provider class is named in more than one
26.81 + * configuration file, or is named in the same configuration file more than
26.82 + * once, then the duplicates are ignored. The configuration file naming a
26.83 + * particular provider need not be in the same jar file or other distribution
26.84 + * unit as the provider itself. The provider must be accessible from the same
26.85 + * class loader that was initially queried to locate the configuration file;
26.86 + * note that this is not necessarily the class loader from which the file was
26.87 + * actually loaded.
26.88 + *
26.89 + * <p> Providers are located and instantiated lazily, that is, on demand. A
26.90 + * service loader maintains a cache of the providers that have been loaded so
26.91 + * far. Each invocation of the {@link #iterator iterator} method returns an
26.92 + * iterator that first yields all of the elements of the cache, in
26.93 + * instantiation order, and then lazily locates and instantiates any remaining
26.94 + * providers, adding each one to the cache in turn. The cache can be cleared
26.95 + * via the {@link #reload reload} method.
26.96 + *
26.97 + * <p> Service loaders always execute in the security context of the caller.
26.98 + * Trusted system code should typically invoke the methods in this class, and
26.99 + * the methods of the iterators which they return, from within a privileged
26.100 + * security context.
26.101 + *
26.102 + * <p> Instances of this class are not safe for use by multiple concurrent
26.103 + * threads.
26.104 + *
26.105 + * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any
26.106 + * method in this class will cause a {@link NullPointerException} to be thrown.
26.107 + *
26.108 + *
26.109 + * <p><span style="font-weight: bold; padding-right: 1em">Example</span>
26.110 + * Suppose we have a service type <tt>com.example.CodecSet</tt> which is
26.111 + * intended to represent sets of encoder/decoder pairs for some protocol. In
26.112 + * this case it is an abstract class with two abstract methods:
26.113 + *
26.114 + * <blockquote><pre>
26.115 + * public abstract Encoder getEncoder(String encodingName);
26.116 + * public abstract Decoder getDecoder(String encodingName);</pre></blockquote>
26.117 + *
26.118 + * Each method returns an appropriate object or <tt>null</tt> if the provider
26.119 + * does not support the given encoding. Typical providers support more than
26.120 + * one encoding.
26.121 + *
26.122 + * <p> If <tt>com.example.impl.StandardCodecs</tt> is an implementation of the
26.123 + * <tt>CodecSet</tt> service then its jar file also contains a file named
26.124 + *
26.125 + * <blockquote><pre>
26.126 + * META-INF/services/com.example.CodecSet</pre></blockquote>
26.127 + *
26.128 + * <p> This file contains the single line:
26.129 + *
26.130 + * <blockquote><pre>
26.131 + * com.example.impl.StandardCodecs # Standard codecs</pre></blockquote>
26.132 + *
26.133 + * <p> The <tt>CodecSet</tt> class creates and saves a single service instance
26.134 + * at initialization:
26.135 + *
26.136 + * <blockquote><pre>
26.137 + * private static ServiceLoader<CodecSet> codecSetLoader
26.138 + * = ServiceLoader.load(CodecSet.class);</pre></blockquote>
26.139 + *
26.140 + * <p> To locate an encoder for a given encoding name it defines a static
26.141 + * factory method which iterates through the known and available providers,
26.142 + * returning only when it has located a suitable encoder or has run out of
26.143 + * providers.
26.144 + *
26.145 + * <blockquote><pre>
26.146 + * public static Encoder getEncoder(String encodingName) {
26.147 + * for (CodecSet cp : codecSetLoader) {
26.148 + * Encoder enc = cp.getEncoder(encodingName);
26.149 + * if (enc != null)
26.150 + * return enc;
26.151 + * }
26.152 + * return null;
26.153 + * }</pre></blockquote>
26.154 + *
26.155 + * <p> A <tt>getDecoder</tt> method is defined similarly.
26.156 + *
26.157 + *
26.158 + * <p><span style="font-weight: bold; padding-right: 1em">Usage Note</span> If
26.159 + * the class path of a class loader that is used for provider loading includes
26.160 + * remote network URLs then those URLs will be dereferenced in the process of
26.161 + * searching for provider-configuration files.
26.162 + *
26.163 + * <p> This activity is normal, although it may cause puzzling entries to be
26.164 + * created in web-server logs. If a web server is not configured correctly,
26.165 + * however, then this activity may cause the provider-loading algorithm to fail
26.166 + * spuriously.
26.167 + *
26.168 + * <p> A web server should return an HTTP 404 (Not Found) response when a
26.169 + * requested resource does not exist. Sometimes, however, web servers are
26.170 + * erroneously configured to return an HTTP 200 (OK) response along with a
26.171 + * helpful HTML error page in such cases. This will cause a {@link
26.172 + * ServiceConfigurationError} to be thrown when this class attempts to parse
26.173 + * the HTML page as a provider-configuration file. The best solution to this
26.174 + * problem is to fix the misconfigured web server to return the correct
26.175 + * response code (HTTP 404) along with the HTML error page.
26.176 + *
26.177 + * @param <S>
26.178 + * The type of the service to be loaded by this loader
26.179 + *
26.180 + * @author Mark Reinhold
26.181 + * @since 1.6
26.182 + */
26.183 +
26.184 +public final class ServiceLoader<S>
26.185 + implements Iterable<S>
26.186 +{
26.187 +
26.188 + private static final String PREFIX = "META-INF/services/";
26.189 +
26.190 + // The class or interface representing the service being loaded
26.191 + private Class<S> service;
26.192 +
26.193 + // The class loader used to locate, load, and instantiate providers
26.194 + private ClassLoader loader;
26.195 +
26.196 + // Cached providers, in instantiation order
26.197 + private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
26.198 +
26.199 + // The current lazy-lookup iterator
26.200 + private LazyIterator lookupIterator;
26.201 +
26.202 + /**
26.203 + * Clear this loader's provider cache so that all providers will be
26.204 + * reloaded.
26.205 + *
26.206 + * <p> After invoking this method, subsequent invocations of the {@link
26.207 + * #iterator() iterator} method will lazily look up and instantiate
26.208 + * providers from scratch, just as is done by a newly-created loader.
26.209 + *
26.210 + * <p> This method is intended for use in situations in which new providers
26.211 + * can be installed into a running Java virtual machine.
26.212 + */
26.213 + public void reload() {
26.214 + providers.clear();
26.215 + lookupIterator = new LazyIterator(service, loader);
26.216 + }
26.217 +
26.218 + private ServiceLoader(Class<S> svc, ClassLoader cl) {
26.219 + service = svc;
26.220 + loader = cl;
26.221 + reload();
26.222 + }
26.223 +
26.224 + private static void fail(Class service, String msg, Throwable cause)
26.225 + throws ServiceConfigurationError
26.226 + {
26.227 + throw new ServiceConfigurationError(service.getName() + ": " + msg,
26.228 + cause);
26.229 + }
26.230 +
26.231 + private static void fail(Class service, String msg)
26.232 + throws ServiceConfigurationError
26.233 + {
26.234 + throw new ServiceConfigurationError(service.getName() + ": " + msg);
26.235 + }
26.236 +
26.237 + private static void fail(Class service, URL u, int line, String msg)
26.238 + throws ServiceConfigurationError
26.239 + {
26.240 + fail(service, u + ":" + line + ": " + msg);
26.241 + }
26.242 +
26.243 + // Parse a single line from the given configuration file, adding the name
26.244 + // on the line to the names list.
26.245 + //
26.246 + private int parseLine(Class service, URL u, BufferedReader r, int lc,
26.247 + List<String> names)
26.248 + throws IOException, ServiceConfigurationError
26.249 + {
26.250 + String ln = r.readLine();
26.251 + if (ln == null) {
26.252 + return -1;
26.253 + }
26.254 + int ci = ln.indexOf('#');
26.255 + if (ci >= 0) ln = ln.substring(0, ci);
26.256 + ln = ln.trim();
26.257 + int n = ln.length();
26.258 + if (n != 0) {
26.259 + if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
26.260 + fail(service, u, lc, "Illegal configuration-file syntax");
26.261 + int cp = ln.codePointAt(0);
26.262 + if (!Character.isJavaIdentifierStart(cp))
26.263 + fail(service, u, lc, "Illegal provider-class name: " + ln);
26.264 + for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
26.265 + cp = ln.codePointAt(i);
26.266 + if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
26.267 + fail(service, u, lc, "Illegal provider-class name: " + ln);
26.268 + }
26.269 + if (!providers.containsKey(ln) && !names.contains(ln))
26.270 + names.add(ln);
26.271 + }
26.272 + return lc + 1;
26.273 + }
26.274 +
26.275 + // Parse the content of the given URL as a provider-configuration file.
26.276 + //
26.277 + // @param service
26.278 + // The service type for which providers are being sought;
26.279 + // used to construct error detail strings
26.280 + //
26.281 + // @param u
26.282 + // The URL naming the configuration file to be parsed
26.283 + //
26.284 + // @return A (possibly empty) iterator that will yield the provider-class
26.285 + // names in the given configuration file that are not yet members
26.286 + // of the returned set
26.287 + //
26.288 + // @throws ServiceConfigurationError
26.289 + // If an I/O error occurs while reading from the given URL, or
26.290 + // if a configuration-file format error is detected
26.291 + //
26.292 + private Iterator<String> parse(Class service, URL u)
26.293 + throws ServiceConfigurationError
26.294 + {
26.295 + InputStream in = null;
26.296 + BufferedReader r = null;
26.297 + ArrayList<String> names = new ArrayList<>();
26.298 + try {
26.299 + in = u.openStream();
26.300 + r = new BufferedReader(new InputStreamReader(in, "utf-8"));
26.301 + int lc = 1;
26.302 + while ((lc = parseLine(service, u, r, lc, names)) >= 0);
26.303 + } catch (IOException x) {
26.304 + fail(service, "Error reading configuration file", x);
26.305 + } finally {
26.306 + try {
26.307 + if (r != null) r.close();
26.308 + if (in != null) in.close();
26.309 + } catch (IOException y) {
26.310 + fail(service, "Error closing configuration file", y);
26.311 + }
26.312 + }
26.313 + return names.iterator();
26.314 + }
26.315 +
26.316 + // Private inner class implementing fully-lazy provider lookup
26.317 + //
26.318 + private class LazyIterator
26.319 + implements Iterator<S>
26.320 + {
26.321 +
26.322 + Class<S> service;
26.323 + ClassLoader loader;
26.324 + Enumeration<URL> configs = null;
26.325 + Iterator<String> pending = null;
26.326 + String nextName = null;
26.327 +
26.328 + private LazyIterator(Class<S> service, ClassLoader loader) {
26.329 + this.service = service;
26.330 + this.loader = loader;
26.331 + }
26.332 +
26.333 + public boolean hasNext() {
26.334 + if (nextName != null) {
26.335 + return true;
26.336 + }
26.337 + if (configs == null) {
26.338 + try {
26.339 + String fullName = PREFIX + service.getName();
26.340 + if (loader == null)
26.341 + configs = ClassLoader.getSystemResources(fullName);
26.342 + else
26.343 + configs = loader.getResources(fullName);
26.344 + } catch (IOException x) {
26.345 + fail(service, "Error locating configuration files", x);
26.346 + }
26.347 + }
26.348 + while ((pending == null) || !pending.hasNext()) {
26.349 + if (!configs.hasMoreElements()) {
26.350 + return false;
26.351 + }
26.352 + pending = parse(service, configs.nextElement());
26.353 + }
26.354 + nextName = pending.next();
26.355 + return true;
26.356 + }
26.357 +
26.358 + public S next() {
26.359 + if (!hasNext()) {
26.360 + throw new NoSuchElementException();
26.361 + }
26.362 + String cn = nextName;
26.363 + nextName = null;
26.364 + try {
26.365 + S p = service.cast(Class.forName(cn, true, loader)
26.366 + .newInstance());
26.367 + providers.put(cn, p);
26.368 + return p;
26.369 + } catch (ClassNotFoundException x) {
26.370 + fail(service,
26.371 + "Provider " + cn + " not found");
26.372 + } catch (Throwable x) {
26.373 + fail(service,
26.374 + "Provider " + cn + " could not be instantiated: " + x,
26.375 + x);
26.376 + }
26.377 + throw new Error(); // This cannot happen
26.378 + }
26.379 +
26.380 + public void remove() {
26.381 + throw new UnsupportedOperationException();
26.382 + }
26.383 +
26.384 + }
26.385 +
26.386 + /**
26.387 + * Lazily loads the available providers of this loader's service.
26.388 + *
26.389 + * <p> The iterator returned by this method first yields all of the
26.390 + * elements of the provider cache, in instantiation order. It then lazily
26.391 + * loads and instantiates any remaining providers, adding each one to the
26.392 + * cache in turn.
26.393 + *
26.394 + * <p> To achieve laziness the actual work of parsing the available
26.395 + * provider-configuration files and instantiating providers must be done by
26.396 + * the iterator itself. Its {@link java.util.Iterator#hasNext hasNext} and
26.397 + * {@link java.util.Iterator#next next} methods can therefore throw a
26.398 + * {@link ServiceConfigurationError} if a provider-configuration file
26.399 + * violates the specified format, or if it names a provider class that
26.400 + * cannot be found and instantiated, or if the result of instantiating the
26.401 + * class is not assignable to the service type, or if any other kind of
26.402 + * exception or error is thrown as the next provider is located and
26.403 + * instantiated. To write robust code it is only necessary to catch {@link
26.404 + * ServiceConfigurationError} when using a service iterator.
26.405 + *
26.406 + * <p> If such an error is thrown then subsequent invocations of the
26.407 + * iterator will make a best effort to locate and instantiate the next
26.408 + * available provider, but in general such recovery cannot be guaranteed.
26.409 + *
26.410 + * <blockquote style="font-size: smaller; line-height: 1.2"><span
26.411 + * style="padding-right: 1em; font-weight: bold">Design Note</span>
26.412 + * Throwing an error in these cases may seem extreme. The rationale for
26.413 + * this behavior is that a malformed provider-configuration file, like a
26.414 + * malformed class file, indicates a serious problem with the way the Java
26.415 + * virtual machine is configured or is being used. As such it is
26.416 + * preferable to throw an error rather than try to recover or, even worse,
26.417 + * fail silently.</blockquote>
26.418 + *
26.419 + * <p> The iterator returned by this method does not support removal.
26.420 + * Invoking its {@link java.util.Iterator#remove() remove} method will
26.421 + * cause an {@link UnsupportedOperationException} to be thrown.
26.422 + *
26.423 + * @return An iterator that lazily loads providers for this loader's
26.424 + * service
26.425 + */
26.426 + public Iterator<S> iterator() {
26.427 + return new Iterator<S>() {
26.428 +
26.429 + Iterator<Map.Entry<String,S>> knownProviders
26.430 + = providers.entrySet().iterator();
26.431 +
26.432 + public boolean hasNext() {
26.433 + if (knownProviders.hasNext())
26.434 + return true;
26.435 + return lookupIterator.hasNext();
26.436 + }
26.437 +
26.438 + public S next() {
26.439 + if (knownProviders.hasNext())
26.440 + return knownProviders.next().getValue();
26.441 + return lookupIterator.next();
26.442 + }
26.443 +
26.444 + public void remove() {
26.445 + throw new UnsupportedOperationException();
26.446 + }
26.447 +
26.448 + };
26.449 + }
26.450 +
26.451 + /**
26.452 + * Creates a new service loader for the given service type and class
26.453 + * loader.
26.454 + *
26.455 + * @param service
26.456 + * The interface or abstract class representing the service
26.457 + *
26.458 + * @param loader
26.459 + * The class loader to be used to load provider-configuration files
26.460 + * and provider classes, or <tt>null</tt> if the system class
26.461 + * loader (or, failing that, the bootstrap class loader) is to be
26.462 + * used
26.463 + *
26.464 + * @return A new service loader
26.465 + */
26.466 + public static <S> ServiceLoader<S> load(Class<S> service,
26.467 + ClassLoader loader)
26.468 + {
26.469 + return new ServiceLoader<>(service, loader);
26.470 + }
26.471 +
26.472 + /**
26.473 + * Creates a new service loader for the given service type, using the
26.474 + * current thread's {@linkplain java.lang.Thread#getContextClassLoader
26.475 + * context class loader}.
26.476 + *
26.477 + * <p> An invocation of this convenience method of the form
26.478 + *
26.479 + * <blockquote><pre>
26.480 + * ServiceLoader.load(<i>service</i>)</pre></blockquote>
26.481 + *
26.482 + * is equivalent to
26.483 + *
26.484 + * <blockquote><pre>
26.485 + * ServiceLoader.load(<i>service</i>,
26.486 + * Thread.currentThread().getContextClassLoader())</pre></blockquote>
26.487 + *
26.488 + * @param service
26.489 + * The interface or abstract class representing the service
26.490 + *
26.491 + * @return A new service loader
26.492 + */
26.493 + public static <S> ServiceLoader<S> load(Class<S> service) {
26.494 + ClassLoader cl = Thread.currentThread().getContextClassLoader();
26.495 + return ServiceLoader.load(service, cl);
26.496 + }
26.497 +
26.498 + /**
26.499 + * Creates a new service loader for the given service type, using the
26.500 + * extension class loader.
26.501 + *
26.502 + * <p> This convenience method simply locates the extension class loader,
26.503 + * call it <tt><i>extClassLoader</i></tt>, and then returns
26.504 + *
26.505 + * <blockquote><pre>
26.506 + * ServiceLoader.load(<i>service</i>, <i>extClassLoader</i>)</pre></blockquote>
26.507 + *
26.508 + * <p> If the extension class loader cannot be found then the system class
26.509 + * loader is used; if there is no system class loader then the bootstrap
26.510 + * class loader is used.
26.511 + *
26.512 + * <p> This method is intended for use when only installed providers are
26.513 + * desired. The resulting service will only find and load providers that
26.514 + * have been installed into the current Java virtual machine; providers on
26.515 + * the application's class path will be ignored.
26.516 + *
26.517 + * @param service
26.518 + * The interface or abstract class representing the service
26.519 + *
26.520 + * @return A new service loader
26.521 + */
26.522 + public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
26.523 + ClassLoader cl = ClassLoader.getSystemClassLoader();
26.524 + ClassLoader prev = null;
26.525 + while (cl != null) {
26.526 + prev = cl;
26.527 + cl = cl.getParent();
26.528 + }
26.529 + return ServiceLoader.load(service, prev);
26.530 + }
26.531 +
26.532 + /**
26.533 + * Returns a string describing this service.
26.534 + *
26.535 + * @return A descriptive string
26.536 + */
26.537 + public String toString() {
26.538 + return "java.util.ServiceLoader[" + service.getName() + "]";
26.539 + }
26.540 +
26.541 +}
27.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
27.2 +++ b/emul/compact/src/main/java/java/util/Set.java Wed Jan 23 22:33:45 2013 +0100
27.3 @@ -0,0 +1,385 @@
27.4 +/*
27.5 + * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
27.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
27.7 + *
27.8 + * This code is free software; you can redistribute it and/or modify it
27.9 + * under the terms of the GNU General Public License version 2 only, as
27.10 + * published by the Free Software Foundation. Oracle designates this
27.11 + * particular file as subject to the "Classpath" exception as provided
27.12 + * by Oracle in the LICENSE file that accompanied this code.
27.13 + *
27.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
27.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
27.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
27.17 + * version 2 for more details (a copy is included in the LICENSE file that
27.18 + * accompanied this code).
27.19 + *
27.20 + * You should have received a copy of the GNU General Public License version
27.21 + * 2 along with this work; if not, write to the Free Software Foundation,
27.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
27.23 + *
27.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
27.25 + * or visit www.oracle.com if you need additional information or have any
27.26 + * questions.
27.27 + */
27.28 +
27.29 +package java.util;
27.30 +
27.31 +/**
27.32 + * A collection that contains no duplicate elements. More formally, sets
27.33 + * contain no pair of elements <code>e1</code> and <code>e2</code> such that
27.34 + * <code>e1.equals(e2)</code>, and at most one null element. As implied by
27.35 + * its name, this interface models the mathematical <i>set</i> abstraction.
27.36 + *
27.37 + * <p>The <tt>Set</tt> interface places additional stipulations, beyond those
27.38 + * inherited from the <tt>Collection</tt> interface, on the contracts of all
27.39 + * constructors and on the contracts of the <tt>add</tt>, <tt>equals</tt> and
27.40 + * <tt>hashCode</tt> methods. Declarations for other inherited methods are
27.41 + * also included here for convenience. (The specifications accompanying these
27.42 + * declarations have been tailored to the <tt>Set</tt> interface, but they do
27.43 + * not contain any additional stipulations.)
27.44 + *
27.45 + * <p>The additional stipulation on constructors is, not surprisingly,
27.46 + * that all constructors must create a set that contains no duplicate elements
27.47 + * (as defined above).
27.48 + *
27.49 + * <p>Note: Great care must be exercised if mutable objects are used as set
27.50 + * elements. The behavior of a set is not specified if the value of an object
27.51 + * is changed in a manner that affects <tt>equals</tt> comparisons while the
27.52 + * object is an element in the set. A special case of this prohibition is
27.53 + * that it is not permissible for a set to contain itself as an element.
27.54 + *
27.55 + * <p>Some set implementations have restrictions on the elements that
27.56 + * they may contain. For example, some implementations prohibit null elements,
27.57 + * and some have restrictions on the types of their elements. Attempting to
27.58 + * add an ineligible element throws an unchecked exception, typically
27.59 + * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting
27.60 + * to query the presence of an ineligible element may throw an exception,
27.61 + * or it may simply return false; some implementations will exhibit the former
27.62 + * behavior and some will exhibit the latter. More generally, attempting an
27.63 + * operation on an ineligible element whose completion would not result in
27.64 + * the insertion of an ineligible element into the set may throw an
27.65 + * exception or it may succeed, at the option of the implementation.
27.66 + * Such exceptions are marked as "optional" in the specification for this
27.67 + * interface.
27.68 + *
27.69 + * <p>This interface is a member of the
27.70 + * <a href="{@docRoot}/../technotes/guides/collections/index.html">
27.71 + * Java Collections Framework</a>.
27.72 + *
27.73 + * @param <E> the type of elements maintained by this set
27.74 + *
27.75 + * @author Josh Bloch
27.76 + * @author Neal Gafter
27.77 + * @see Collection
27.78 + * @see List
27.79 + * @see SortedSet
27.80 + * @see HashSet
27.81 + * @see TreeSet
27.82 + * @see AbstractSet
27.83 + * @see Collections#singleton(java.lang.Object)
27.84 + * @see Collections#EMPTY_SET
27.85 + * @since 1.2
27.86 + */
27.87 +
27.88 +public interface Set<E> extends Collection<E> {
27.89 + // Query Operations
27.90 +
27.91 + /**
27.92 + * Returns the number of elements in this set (its cardinality). If this
27.93 + * set contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
27.94 + * <tt>Integer.MAX_VALUE</tt>.
27.95 + *
27.96 + * @return the number of elements in this set (its cardinality)
27.97 + */
27.98 + int size();
27.99 +
27.100 + /**
27.101 + * Returns <tt>true</tt> if this set contains no elements.
27.102 + *
27.103 + * @return <tt>true</tt> if this set contains no elements
27.104 + */
27.105 + boolean isEmpty();
27.106 +
27.107 + /**
27.108 + * Returns <tt>true</tt> if this set contains the specified element.
27.109 + * More formally, returns <tt>true</tt> if and only if this set
27.110 + * contains an element <tt>e</tt> such that
27.111 + * <tt>(o==null ? e==null : o.equals(e))</tt>.
27.112 + *
27.113 + * @param o element whose presence in this set is to be tested
27.114 + * @return <tt>true</tt> if this set contains the specified element
27.115 + * @throws ClassCastException if the type of the specified element
27.116 + * is incompatible with this set
27.117 + * (<a href="Collection.html#optional-restrictions">optional</a>)
27.118 + * @throws NullPointerException if the specified element is null and this
27.119 + * set does not permit null elements
27.120 + * (<a href="Collection.html#optional-restrictions">optional</a>)
27.121 + */
27.122 + boolean contains(Object o);
27.123 +
27.124 + /**
27.125 + * Returns an iterator over the elements in this set. The elements are
27.126 + * returned in no particular order (unless this set is an instance of some
27.127 + * class that provides a guarantee).
27.128 + *
27.129 + * @return an iterator over the elements in this set
27.130 + */
27.131 + Iterator<E> iterator();
27.132 +
27.133 + /**
27.134 + * Returns an array containing all of the elements in this set.
27.135 + * If this set makes any guarantees as to what order its elements
27.136 + * are returned by its iterator, this method must return the
27.137 + * elements in the same order.
27.138 + *
27.139 + * <p>The returned array will be "safe" in that no references to it
27.140 + * are maintained by this set. (In other words, this method must
27.141 + * allocate a new array even if this set is backed by an array).
27.142 + * The caller is thus free to modify the returned array.
27.143 + *
27.144 + * <p>This method acts as bridge between array-based and collection-based
27.145 + * APIs.
27.146 + *
27.147 + * @return an array containing all the elements in this set
27.148 + */
27.149 + Object[] toArray();
27.150 +
27.151 + /**
27.152 + * Returns an array containing all of the elements in this set; the
27.153 + * runtime type of the returned array is that of the specified array.
27.154 + * If the set fits in the specified array, it is returned therein.
27.155 + * Otherwise, a new array is allocated with the runtime type of the
27.156 + * specified array and the size of this set.
27.157 + *
27.158 + * <p>If this set fits in the specified array with room to spare
27.159 + * (i.e., the array has more elements than this set), the element in
27.160 + * the array immediately following the end of the set is set to
27.161 + * <tt>null</tt>. (This is useful in determining the length of this
27.162 + * set <i>only</i> if the caller knows that this set does not contain
27.163 + * any null elements.)
27.164 + *
27.165 + * <p>If this set makes any guarantees as to what order its elements
27.166 + * are returned by its iterator, this method must return the elements
27.167 + * in the same order.
27.168 + *
27.169 + * <p>Like the {@link #toArray()} method, this method acts as bridge between
27.170 + * array-based and collection-based APIs. Further, this method allows
27.171 + * precise control over the runtime type of the output array, and may,
27.172 + * under certain circumstances, be used to save allocation costs.
27.173 + *
27.174 + * <p>Suppose <tt>x</tt> is a set known to contain only strings.
27.175 + * The following code can be used to dump the set into a newly allocated
27.176 + * array of <tt>String</tt>:
27.177 + *
27.178 + * <pre>
27.179 + * String[] y = x.toArray(new String[0]);</pre>
27.180 + *
27.181 + * Note that <tt>toArray(new Object[0])</tt> is identical in function to
27.182 + * <tt>toArray()</tt>.
27.183 + *
27.184 + * @param a the array into which the elements of this set are to be
27.185 + * stored, if it is big enough; otherwise, a new array of the same
27.186 + * runtime type is allocated for this purpose.
27.187 + * @return an array containing all the elements in this set
27.188 + * @throws ArrayStoreException if the runtime type of the specified array
27.189 + * is not a supertype of the runtime type of every element in this
27.190 + * set
27.191 + * @throws NullPointerException if the specified array is null
27.192 + */
27.193 + <T> T[] toArray(T[] a);
27.194 +
27.195 +
27.196 + // Modification Operations
27.197 +
27.198 + /**
27.199 + * Adds the specified element to this set if it is not already present
27.200 + * (optional operation). More formally, adds the specified element
27.201 + * <tt>e</tt> to this set if the set contains no element <tt>e2</tt>
27.202 + * such that
27.203 + * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
27.204 + * If this set already contains the element, the call leaves the set
27.205 + * unchanged and returns <tt>false</tt>. In combination with the
27.206 + * restriction on constructors, this ensures that sets never contain
27.207 + * duplicate elements.
27.208 + *
27.209 + * <p>The stipulation above does not imply that sets must accept all
27.210 + * elements; sets may refuse to add any particular element, including
27.211 + * <tt>null</tt>, and throw an exception, as described in the
27.212 + * specification for {@link Collection#add Collection.add}.
27.213 + * Individual set implementations should clearly document any
27.214 + * restrictions on the elements that they may contain.
27.215 + *
27.216 + * @param e element to be added to this set
27.217 + * @return <tt>true</tt> if this set did not already contain the specified
27.218 + * element
27.219 + * @throws UnsupportedOperationException if the <tt>add</tt> operation
27.220 + * is not supported by this set
27.221 + * @throws ClassCastException if the class of the specified element
27.222 + * prevents it from being added to this set
27.223 + * @throws NullPointerException if the specified element is null and this
27.224 + * set does not permit null elements
27.225 + * @throws IllegalArgumentException if some property of the specified element
27.226 + * prevents it from being added to this set
27.227 + */
27.228 + boolean add(E e);
27.229 +
27.230 +
27.231 + /**
27.232 + * Removes the specified element from this set if it is present
27.233 + * (optional operation). More formally, removes an element <tt>e</tt>
27.234 + * such that
27.235 + * <tt>(o==null ? e==null : o.equals(e))</tt>, if
27.236 + * this set contains such an element. Returns <tt>true</tt> if this set
27.237 + * contained the element (or equivalently, if this set changed as a
27.238 + * result of the call). (This set will not contain the element once the
27.239 + * call returns.)
27.240 + *
27.241 + * @param o object to be removed from this set, if present
27.242 + * @return <tt>true</tt> if this set contained the specified element
27.243 + * @throws ClassCastException if the type of the specified element
27.244 + * is incompatible with this set
27.245 + * (<a href="Collection.html#optional-restrictions">optional</a>)
27.246 + * @throws NullPointerException if the specified element is null and this
27.247 + * set does not permit null elements
27.248 + * (<a href="Collection.html#optional-restrictions">optional</a>)
27.249 + * @throws UnsupportedOperationException if the <tt>remove</tt> operation
27.250 + * is not supported by this set
27.251 + */
27.252 + boolean remove(Object o);
27.253 +
27.254 +
27.255 + // Bulk Operations
27.256 +
27.257 + /**
27.258 + * Returns <tt>true</tt> if this set contains all of the elements of the
27.259 + * specified collection. If the specified collection is also a set, this
27.260 + * method returns <tt>true</tt> if it is a <i>subset</i> of this set.
27.261 + *
27.262 + * @param c collection to be checked for containment in this set
27.263 + * @return <tt>true</tt> if this set contains all of the elements of the
27.264 + * specified collection
27.265 + * @throws ClassCastException if the types of one or more elements
27.266 + * in the specified collection are incompatible with this
27.267 + * set
27.268 + * (<a href="Collection.html#optional-restrictions">optional</a>)
27.269 + * @throws NullPointerException if the specified collection contains one
27.270 + * or more null elements and this set does not permit null
27.271 + * elements
27.272 + * (<a href="Collection.html#optional-restrictions">optional</a>),
27.273 + * or if the specified collection is null
27.274 + * @see #contains(Object)
27.275 + */
27.276 + boolean containsAll(Collection<?> c);
27.277 +
27.278 + /**
27.279 + * Adds all of the elements in the specified collection to this set if
27.280 + * they're not already present (optional operation). If the specified
27.281 + * collection is also a set, the <tt>addAll</tt> operation effectively
27.282 + * modifies this set so that its value is the <i>union</i> of the two
27.283 + * sets. The behavior of this operation is undefined if the specified
27.284 + * collection is modified while the operation is in progress.
27.285 + *
27.286 + * @param c collection containing elements to be added to this set
27.287 + * @return <tt>true</tt> if this set changed as a result of the call
27.288 + *
27.289 + * @throws UnsupportedOperationException if the <tt>addAll</tt> operation
27.290 + * is not supported by this set
27.291 + * @throws ClassCastException if the class of an element of the
27.292 + * specified collection prevents it from being added to this set
27.293 + * @throws NullPointerException if the specified collection contains one
27.294 + * or more null elements and this set does not permit null
27.295 + * elements, or if the specified collection is null
27.296 + * @throws IllegalArgumentException if some property of an element of the
27.297 + * specified collection prevents it from being added to this set
27.298 + * @see #add(Object)
27.299 + */
27.300 + boolean addAll(Collection<? extends E> c);
27.301 +
27.302 + /**
27.303 + * Retains only the elements in this set that are contained in the
27.304 + * specified collection (optional operation). In other words, removes
27.305 + * from this set all of its elements that are not contained in the
27.306 + * specified collection. If the specified collection is also a set, this
27.307 + * operation effectively modifies this set so that its value is the
27.308 + * <i>intersection</i> of the two sets.
27.309 + *
27.310 + * @param c collection containing elements to be retained in this set
27.311 + * @return <tt>true</tt> if this set changed as a result of the call
27.312 + * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
27.313 + * is not supported by this set
27.314 + * @throws ClassCastException if the class of an element of this set
27.315 + * is incompatible with the specified collection
27.316 + * (<a href="Collection.html#optional-restrictions">optional</a>)
27.317 + * @throws NullPointerException if this set contains a null element and the
27.318 + * specified collection does not permit null elements
27.319 + * (<a href="Collection.html#optional-restrictions">optional</a>),
27.320 + * or if the specified collection is null
27.321 + * @see #remove(Object)
27.322 + */
27.323 + boolean retainAll(Collection<?> c);
27.324 +
27.325 + /**
27.326 + * Removes from this set all of its elements that are contained in the
27.327 + * specified collection (optional operation). If the specified
27.328 + * collection is also a set, this operation effectively modifies this
27.329 + * set so that its value is the <i>asymmetric set difference</i> of
27.330 + * the two sets.
27.331 + *
27.332 + * @param c collection containing elements to be removed from this set
27.333 + * @return <tt>true</tt> if this set changed as a result of the call
27.334 + * @throws UnsupportedOperationException if the <tt>removeAll</tt> operation
27.335 + * is not supported by this set
27.336 + * @throws ClassCastException if the class of an element of this set
27.337 + * is incompatible with the specified collection
27.338 + * (<a href="Collection.html#optional-restrictions">optional</a>)
27.339 + * @throws NullPointerException if this set contains a null element and the
27.340 + * specified collection does not permit null elements
27.341 + * (<a href="Collection.html#optional-restrictions">optional</a>),
27.342 + * or if the specified collection is null
27.343 + * @see #remove(Object)
27.344 + * @see #contains(Object)
27.345 + */
27.346 + boolean removeAll(Collection<?> c);
27.347 +
27.348 + /**
27.349 + * Removes all of the elements from this set (optional operation).
27.350 + * The set will be empty after this call returns.
27.351 + *
27.352 + * @throws UnsupportedOperationException if the <tt>clear</tt> method
27.353 + * is not supported by this set
27.354 + */
27.355 + void clear();
27.356 +
27.357 +
27.358 + // Comparison and hashing
27.359 +
27.360 + /**
27.361 + * Compares the specified object with this set for equality. Returns
27.362 + * <tt>true</tt> if the specified object is also a set, the two sets
27.363 + * have the same size, and every member of the specified set is
27.364 + * contained in this set (or equivalently, every member of this set is
27.365 + * contained in the specified set). This definition ensures that the
27.366 + * equals method works properly across different implementations of the
27.367 + * set interface.
27.368 + *
27.369 + * @param o object to be compared for equality with this set
27.370 + * @return <tt>true</tt> if the specified object is equal to this set
27.371 + */
27.372 + boolean equals(Object o);
27.373 +
27.374 + /**
27.375 + * Returns the hash code value for this set. The hash code of a set is
27.376 + * defined to be the sum of the hash codes of the elements in the set,
27.377 + * where the hash code of a <tt>null</tt> element is defined to be zero.
27.378 + * This ensures that <tt>s1.equals(s2)</tt> implies that
27.379 + * <tt>s1.hashCode()==s2.hashCode()</tt> for any two sets <tt>s1</tt>
27.380 + * and <tt>s2</tt>, as required by the general contract of
27.381 + * {@link Object#hashCode}.
27.382 + *
27.383 + * @return the hash code value for this set
27.384 + * @see Object#equals(Object)
27.385 + * @see Set#equals(Object)
27.386 + */
27.387 + int hashCode();
27.388 +}