code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * An object that creates new threads on demand. Using thread factories * removes hardwiring of calls to {@link Thread#Thread(Runnable) new Thread}, * enabling applications to use special thread subclasses, priorities, etc. * * <p> * The simplest implementation of this interface is just: * <pre> * class SimpleThreadFactory implements ThreadFactory { * public Thread newThread(Runnable r) { * return new Thread(r); * } * } * </pre> * * The {@link Executors#defaultThreadFactory} method provides a more * useful simple implementation, that sets the created thread context * to known values before returning it. * {@description.close} * @since 1.5 * @author Doug Lea */ public interface ThreadFactory { /** {@collect.stats} * {@description.open} * Constructs a new {@code Thread}. Implementations may also initialize * priority, name, daemon status, {@code ThreadGroup}, etc. * {@description.close} * * @param r a runnable to be executed by new thread instance * @return constructed thread, or {@code null} if the request to * create a thread is rejected */ Thread newThread(Runnable r); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.*; import java.util.concurrent.atomic.*; /** {@collect.stats} * {@description.open} * An unbounded thread-safe {@linkplain Queue queue} based on linked nodes. * This queue orders elements FIFO (first-in-first-out). * The <em>head</em> of the queue is that element that has been on the * queue the longest time. * The <em>tail</em> of the queue is that element that has been on the * queue the shortest time. New elements * are inserted at the tail of the queue, and the queue retrieval * operations obtain elements at the head of the queue. * A <tt>ConcurrentLinkedQueue</tt> is an appropriate choice when * many threads will share access to a common collection. * This queue does not permit <tt>null</tt> elements. * * <p>This implementation employs an efficient &quot;wait-free&quot; * algorithm based on one described in <a * href="http://www.cs.rochester.edu/u/michael/PODC96.html"> Simple, * Fast, and Practical Non-Blocking and Blocking Concurrent Queue * Algorithms</a> by Maged M. Michael and Michael L. Scott. * * <p>Beware that, unlike in most collections, the <tt>size</tt> method * is <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these queues, determining the current number * of elements requires a traversal of the elements. * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * <p>Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a * {@code ConcurrentLinkedQueue} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions subsequent to the access or removal of that element from * the {@code ConcurrentLinkedQueue} in another thread. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection * */ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E> implements Queue<E>, java.io.Serializable { private static final long serialVersionUID = 196745693267521676L; /* * This is a straight adaptation of Michael & Scott algorithm. * For explanation, read the paper. The only (minor) algorithmic * difference is that this version supports lazy deletion of * internal nodes (method remove(Object)) -- remove CAS'es item * fields to null. The normal queue operations unlink but then * pass over nodes with null item fields. Similarly, iteration * methods ignore those with nulls. * * Also note that like most non-blocking algorithms in this * package, this implementation relies on the fact that in garbage * collected systems, there is no possibility of ABA problems due * to recycled nodes, so there is no need to use "counted * pointers" or related techniques seen in versions used in * non-GC'ed settings. */ private static class Node<E> { private volatile E item; private volatile Node<E> next; private static final AtomicReferenceFieldUpdater<Node, Node> nextUpdater = AtomicReferenceFieldUpdater.newUpdater (Node.class, Node.class, "next"); private static final AtomicReferenceFieldUpdater<Node, Object> itemUpdater = AtomicReferenceFieldUpdater.newUpdater (Node.class, Object.class, "item"); Node(E x) { item = x; } Node(E x, Node<E> n) { item = x; next = n; } E getItem() { return item; } boolean casItem(E cmp, E val) { return itemUpdater.compareAndSet(this, cmp, val); } void setItem(E val) { itemUpdater.set(this, val); } Node<E> getNext() { return next; } boolean casNext(Node<E> cmp, Node<E> val) { return nextUpdater.compareAndSet(this, cmp, val); } void setNext(Node<E> val) { nextUpdater.set(this, val); } } private static final AtomicReferenceFieldUpdater<ConcurrentLinkedQueue, Node> tailUpdater = AtomicReferenceFieldUpdater.newUpdater (ConcurrentLinkedQueue.class, Node.class, "tail"); private static final AtomicReferenceFieldUpdater<ConcurrentLinkedQueue, Node> headUpdater = AtomicReferenceFieldUpdater.newUpdater (ConcurrentLinkedQueue.class, Node.class, "head"); private boolean casTail(Node<E> cmp, Node<E> val) { return tailUpdater.compareAndSet(this, cmp, val); } private boolean casHead(Node<E> cmp, Node<E> val) { return headUpdater.compareAndSet(this, cmp, val); } /** {@collect.stats} * {@description.open} * Pointer to header node, initialized to a dummy node. The first * actual node is at head.getNext(). * {@description.close} */ private transient volatile Node<E> head = new Node<E>(null, null); /** {@collect.stats} * {@description.open} * Pointer to last node on list * {@description.close} */ private transient volatile Node<E> tail = head; /** {@collect.stats} * {@description.open} * Creates a <tt>ConcurrentLinkedQueue</tt> that is initially empty. * {@description.close} */ public ConcurrentLinkedQueue() {} /** {@collect.stats} * {@description.open} * Creates a <tt>ConcurrentLinkedQueue</tt> * initially containing the elements of the given collection, * added in traversal order of the collection's iterator. * {@description.close} * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection or any * of its elements are null */ public ConcurrentLinkedQueue(Collection<? extends E> c) { for (Iterator<? extends E> it = c.iterator(); it.hasNext();) add(it.next()); } // Have to override just to update the javadoc /** {@collect.stats} * {@description.open} * Inserts the specified element at the tail of this queue. * {@description.close} * * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws NullPointerException if the specified element is null */ public boolean add(E e) { return offer(e); } /** {@collect.stats} * {@description.open} * Inserts the specified element at the tail of this queue. * {@description.close} * * @return <tt>true</tt> (as specified by {@link Queue#offer}) * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { if (e == null) throw new NullPointerException(); Node<E> n = new Node<E>(e, null); for (;;) { Node<E> t = tail; Node<E> s = t.getNext(); if (t == tail) { if (s == null) { if (t.casNext(s, n)) { casTail(t, n); return true; } } else { casTail(t, s); } } } } public E poll() { for (;;) { Node<E> h = head; Node<E> t = tail; Node<E> first = h.getNext(); if (h == head) { if (h == t) { if (first == null) return null; else casTail(t, first); } else if (casHead(h, first)) { E item = first.getItem(); if (item != null) { first.setItem(null); return item; } // else skip over deleted item, continue loop, } } } } public E peek() { // same as poll except don't remove item for (;;) { Node<E> h = head; Node<E> t = tail; Node<E> first = h.getNext(); if (h == head) { if (h == t) { if (first == null) return null; else casTail(t, first); } else { E item = first.getItem(); if (item != null) return item; else // remove deleted node and continue casHead(h, first); } } } } /** {@collect.stats} * {@description.open} * Returns the first actual (non-header) node on list. This is yet * another variant of poll/peek; here returning out the first * node, not element (so we cannot collapse with peek() without * introducing race.) * {@description.close} */ Node<E> first() { for (;;) { Node<E> h = head; Node<E> t = tail; Node<E> first = h.getNext(); if (h == head) { if (h == t) { if (first == null) return null; else casTail(t, first); } else { if (first.getItem() != null) return first; else // remove deleted node and continue casHead(h, first); } } } } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this queue contains no elements. * {@description.close} * * @return <tt>true</tt> if this queue contains no elements */ public boolean isEmpty() { return first() == null; } /** {@collect.stats} * {@description.open} * Returns the number of elements in this queue. If this queue * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns * <tt>Integer.MAX_VALUE</tt>. * * <p>Beware that, unlike in most collections, this method is * <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these queues, determining the current * number of elements requires an O(n) traversal. * {@description.close} * * @return the number of elements in this queue */ public int size() { int count = 0; for (Node<E> p = first(); p != null; p = p.getNext()) { if (p.getItem() != null) { // Collections.size() spec says to max out if (++count == Integer.MAX_VALUE) break; } } return count; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this queue contains the specified element. * More formally, returns <tt>true</tt> if and only if this queue contains * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>. * {@description.close} * * @param o object to be checked for containment in this queue * @return <tt>true</tt> if this queue contains the specified element */ public boolean contains(Object o) { if (o == null) return false; for (Node<E> p = first(); p != null; p = p.getNext()) { E item = p.getItem(); if (item != null && o.equals(item)) return true; } return false; } /** {@collect.stats} * {@description.open} * Removes a single instance of the specified element from this queue, * if it is present. More formally, removes an element <tt>e</tt> such * that <tt>o.equals(e)</tt>, if this queue contains one or more such * elements. * Returns <tt>true</tt> if this queue contained the specified element * (or equivalently, if this queue changed as a result of the call). * {@description.close} * * @param o element to be removed from this queue, if present * @return <tt>true</tt> if this queue changed as a result of the call */ public boolean remove(Object o) { if (o == null) return false; for (Node<E> p = first(); p != null; p = p.getNext()) { E item = p.getItem(); if (item != null && o.equals(item) && p.casItem(item, null)) return true; } return false; } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue, in * proper sequence. * * <p>The returned array will be "safe" in that no references to it are * maintained by this queue. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this queue */ public Object[] toArray() { // Use ArrayList to deal with resizing. ArrayList<E> al = new ArrayList<E>(); for (Node<E> p = first(); p != null; p = p.getNext()) { E item = p.getItem(); if (item != null) al.add(item); } return al.toArray(); } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue, in * proper sequence; the runtime type of the returned array is that of * the specified array. If the queue fits in the specified array, it * is returned therein. Otherwise, a new array is allocated with the * runtime type of the specified array and the size of this queue. * * <p>If this queue fits in the specified array with room to spare * (i.e., the array has more elements than this queue), the element in * the array immediately following the end of the queue is set to * <tt>null</tt>. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a queue known to contain only strings. * The following code can be used to dump the queue into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of the queue are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this queue * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this queue * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { // try to use sent-in array int k = 0; Node<E> p; for (p = first(); p != null && k < a.length; p = p.getNext()) { E item = p.getItem(); if (item != null) a[k++] = (T)item; } if (p == null) { if (k < a.length) a[k] = null; return a; } // If won't fit, use ArrayList version ArrayList<E> al = new ArrayList<E>(); for (Node<E> q = first(); q != null; q = q.getNext()) { E item = q.getItem(); if (item != null) al.add(item); } return al.toArray(a); } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this queue in proper sequence. * {@description.close} * {@property.open synchronized} * The returned iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, * and guarantees to traverse elements as they existed upon * construction of the iterator, and may (but is not guaranteed to) * reflect any modifications subsequent to construction. * {@property.close} * * @return an iterator over the elements in this queue in proper sequence */ public Iterator<E> iterator() { return new Itr(); } private class Itr implements Iterator<E> { /** {@collect.stats} * {@description.open} * Next node to return item for. * {@description.close} */ private Node<E> nextNode; /** {@collect.stats} * {@description.open} * nextItem holds on to item fields because once we claim * that an element exists in hasNext(), we must return it in * the following next() call even if it was in the process of * being removed when hasNext() was called. * {@description.close} */ private E nextItem; /** {@collect.stats} * {@description.open} * Node of the last returned item, to support remove. * {@description.close} */ private Node<E> lastRet; Itr() { advance(); } /** {@collect.stats} * {@description.open} * Moves to next valid node and returns item to return for * next(), or null if no such. * {@description.close} */ private E advance() { lastRet = nextNode; E x = nextItem; Node<E> p = (nextNode == null)? first() : nextNode.getNext(); for (;;) { if (p == null) { nextNode = null; nextItem = null; return x; } E item = p.getItem(); if (item != null) { nextNode = p; nextItem = item; return x; } else // skip over nulls p = p.getNext(); } } public boolean hasNext() { return nextNode != null; } public E next() { if (nextNode == null) throw new NoSuchElementException(); return advance(); } public void remove() { Node<E> l = lastRet; if (l == null) throw new IllegalStateException(); // rely on a future traversal to relink. l.setItem(null); lastRet = null; } } /** {@collect.stats} * {@description.open} * Save the state to a stream (that is, serialize it). * {@description.close} * * @serialData All of the elements (each an <tt>E</tt>) in * the proper order, followed by a null * @param s the stream */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden stuff s.defaultWriteObject(); // Write out all elements in the proper order. for (Node<E> p = first(); p != null; p = p.getNext()) { Object item = p.getItem(); if (item != null) s.writeObject(item); } // Use trailing null as sentinel s.writeObject(null); } /** {@collect.stats} * {@description.open} * Reconstitute the Queue instance from a stream (that is, * deserialize it). * {@description.close} * @param s the stream */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in capacity, and any hidden stuff s.defaultReadObject(); head = new Node<E>(null, null); tail = head; // Read in all elements and place in queue for (;;) { E item = (E)s.readObject(); if (item == null) break; else offer(item); } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.locks; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.*; /** {@collect.stats} * {@description.open} * An implementation of {@link ReadWriteLock} supporting similar * semantics to {@link ReentrantLock}. * <p>This class has the following properties: * * <ul> * <li><b>Acquisition order</b> * * <p> This class does not impose a reader or writer preference * ordering for lock access. However, it does support an optional * <em>fairness</em> policy. * * <dl> * <dt><b><i>Non-fair mode (default)</i></b> * <dd>When constructed as non-fair (the default), the order of entry * to the read and write lock is unspecified, subject to reentrancy * constraints. A nonfair lock that is continuously contended may * indefinitely postpone one or more reader or writer threads, but * will normally have higher throughput than a fair lock. * <p> * * <dt><b><i>Fair mode</i></b> * <dd> When constructed as fair, threads contend for entry using an * approximately arrival-order policy. When the currently held lock * is released either the longest-waiting single writer thread will * be assigned the write lock, or if there is a group of reader threads * waiting longer than all waiting writer threads, that group will be * assigned the read lock. * * <p>A thread that tries to acquire a fair read lock (non-reentrantly) * will block if either the write lock is held, or there is a waiting * writer thread. The thread will not acquire the read lock until * after the oldest currently waiting writer thread has acquired and * released the write lock. Of course, if a waiting writer abandons * its wait, leaving one or more reader threads as the longest waiters * in the queue with the write lock free, then those readers will be * assigned the read lock. * * <p>A thread that tries to acquire a fair write lock (non-reentrantly) * will block unless both the read lock and write lock are free (which * implies there are no waiting threads). (Note that the non-blocking * {@link ReadLock#tryLock()} and {@link WriteLock#tryLock()} methods * do not honor this fair setting and will acquire the lock if it is * possible, regardless of waiting threads.) * <p> * </dl> * * <li><b>Reentrancy</b> * * {@description.close} * {@property.open} * <p>This lock allows both readers and writers to reacquire read or * write locks in the style of a {@link ReentrantLock}. Non-reentrant * readers are not allowed until all write locks held by the writing * thread have been released. * {@property.close} * * {@property.open} * <p>Additionally, a writer can acquire the read lock, but not * vice-versa. Among other applications, reentrancy can be useful * when write locks are held during calls or callbacks to methods that * perform reads under read locks. If a reader tries to acquire the * write lock it will never succeed. * {@property.close} * * {@description.open} * <li><b>Lock downgrading</b> * <p>Reentrancy also allows downgrading from the write lock to a read lock, * by acquiring the write lock, then the read lock and then releasing the * write lock. However, upgrading from a read lock to the write lock is * <b>not</b> possible. * * <li><b>Interruption of lock acquisition</b> * <p>The read lock and write lock both support interruption during lock * acquisition. * * <li><b>{@link Condition} support</b> * <p>The write lock provides a {@link Condition} implementation that * behaves in the same way, with respect to the write lock, as the * {@link Condition} implementation provided by * {@link ReentrantLock#newCondition} does for {@link ReentrantLock}. * This {@link Condition} can, of course, only be used with the write lock. * * <p>The read lock does not support a {@link Condition} and * {@code readLock().newCondition()} throws * {@code UnsupportedOperationException}. * * <li><b>Instrumentation</b> * <p>This class supports methods to determine whether locks * are held or contended. These methods are designed for monitoring * system state, not for synchronization control. * </ul> * * <p>Serialization of this class behaves in the same way as built-in * locks: a deserialized lock is in the unlocked state, regardless of * its state when serialized. * * <p><b>Sample usages</b>. Here is a code sketch showing how to perform * lock downgrading after updating a cache (exception handling is * particularly tricky when handling multiple locks in a non-nested * fashion): * * <pre> {@code * class CachedData { * Object data; * volatile boolean cacheValid; * final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); * * void processCachedData() { * rwl.readLock().lock(); * if (!cacheValid) { * // Must release read lock before acquiring write lock * rwl.readLock().unlock(); * rwl.writeLock().lock(); * try { * // Recheck state because another thread might have * // acquired write lock and changed state before we did. * if (!cacheValid) { * data = ... * cacheValid = true; * } * // Downgrade by acquiring read lock before releasing write lock * rwl.readLock().lock(); * } finally { * rwl.writeLock().unlock(); // Unlock write, still hold read * } * } * * try { * use(data); * } finally { * rwl.readLock().unlock(); * } * } * }}</pre> * * ReentrantReadWriteLocks can be used to improve concurrency in some * uses of some kinds of Collections. This is typically worthwhile * only when the collections are expected to be large, accessed by * more reader threads than writer threads, and entail operations with * overhead that outweighs synchronization overhead. For example, here * is a class using a TreeMap that is expected to be large and * concurrently accessed. * * <pre>{@code * class RWDictionary { * private final Map<String, Data> m = new TreeMap<String, Data>(); * private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); * private final Lock r = rwl.readLock(); * private final Lock w = rwl.writeLock(); * * public Data get(String key) { * r.lock(); * try { return m.get(key); } * finally { r.unlock(); } * } * public String[] allKeys() { * r.lock(); * try { return m.keySet().toArray(); } * finally { r.unlock(); } * } * public Data put(String key, Data value) { * w.lock(); * try { return m.put(key, value); } * finally { w.unlock(); } * } * public void clear() { * w.lock(); * try { m.clear(); } * finally { w.unlock(); } * } * }}</pre> * * <h3>Implementation Notes</h3> * * <p>This lock supports a maximum of 65535 recursive write locks * and 65535 read locks. Attempts to exceed these limits result in * {@link Error} throws from locking methods. * {@description.close} * * @since 1.5 * @author Doug Lea * */ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable { private static final long serialVersionUID = -6992448646407690164L; /** {@collect.stats} * {@description.open} * Inner class providing readlock * {@description.close} */ private final ReentrantReadWriteLock.ReadLock readerLock; /** {@collect.stats} * {@description.open} * Inner class providing writelock * {@description.close} */ private final ReentrantReadWriteLock.WriteLock writerLock; /** {@collect.stats} * {@description.open} * Performs all synchronization mechanics * {@description.close} */ private final Sync sync; /** {@collect.stats} * {@description.open} * Creates a new {@code ReentrantReadWriteLock} with * default (nonfair) ordering properties. * {@description.close} */ public ReentrantReadWriteLock() { this(false); } /** {@collect.stats} * {@description.open} * Creates a new {@code ReentrantReadWriteLock} with * the given fairness policy. * {@description.close} * * @param fair {@code true} if this lock should use a fair ordering policy */ public ReentrantReadWriteLock(boolean fair) { sync = (fair)? new FairSync() : new NonfairSync(); readerLock = new ReadLock(this); writerLock = new WriteLock(this); } public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; } public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; } /** {@collect.stats} * {@description.open} * Synchronization implementation for ReentrantReadWriteLock. * Subclassed into fair and nonfair versions. * {@description.close} */ static abstract class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 6317671515068378041L; /* * Read vs write count extraction constants and functions. * Lock state is logically divided into two shorts: The lower * one representing the exclusive (writer) lock hold count, * and the upper the shared (reader) hold count. */ static final int SHARED_SHIFT = 16; static final int SHARED_UNIT = (1 << SHARED_SHIFT); static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1; static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1; /** {@collect.stats} * {@description.open} * Returns the number of shared holds represented in count * {@description.close} */ static int sharedCount(int c) { return c >>> SHARED_SHIFT; } /** {@collect.stats} * {@description.open} * Returns the number of exclusive holds represented in count * {@description.close} */ static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; } /** {@collect.stats} * {@description.open} * A counter for per-thread read hold counts. * Maintained as a ThreadLocal; cached in cachedHoldCounter * {@description.close} */ static final class HoldCounter { int count; // Use id, not reference, to avoid garbage retention final long tid = Thread.currentThread().getId(); /** {@collect.stats} * {@description.open} * Decrement if positive; return previous value * {@description.close} */ int tryDecrement() { int c = count; if (c > 0) count = c - 1; return c; } } /** {@collect.stats} * {@description.open} * ThreadLocal subclass. Easiest to explicitly define for sake * of deserialization mechanics. * {@description.close} */ static final class ThreadLocalHoldCounter extends ThreadLocal<HoldCounter> { public HoldCounter initialValue() { return new HoldCounter(); } } /** {@collect.stats} * {@description.open} * The number of read locks held by current thread. * Initialized only in constructor and readObject. * {@description.close} */ transient ThreadLocalHoldCounter readHolds; /** {@collect.stats} * {@description.open} * The hold count of the last thread to successfully acquire * readLock. This saves ThreadLocal lookup in the common case * where the next thread to release is the last one to * acquire. This is non-volatile since it is just used * as a heuristic, and would be great for threads to cache. * {@description.close} */ transient HoldCounter cachedHoldCounter; Sync() { readHolds = new ThreadLocalHoldCounter(); setState(getState()); // ensures visibility of readHolds } /* * Acquires and releases use the same code for fair and * nonfair locks, but differ in whether/how they allow barging * when queues are non-empty. */ /** {@collect.stats} * {@description.open} * Returns true if the current thread, when trying to acquire * the read lock, and otherwise eligible to do so, should block * because of policy for overtaking other waiting threads. * {@description.close} */ abstract boolean readerShouldBlock(); /** {@collect.stats} * {@description.open} * Returns true if the current thread, when trying to acquire * the write lock, and otherwise eligible to do so, should block * because of policy for overtaking other waiting threads. * {@description.close} */ abstract boolean writerShouldBlock(); /* * Note that tryRelease and tryAcquire can be called by * Conditions. So it is possible that their arguments contain * both read and write holds that are all released during a * condition wait and re-established in tryAcquire. */ protected final boolean tryRelease(int releases) { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); int nextc = getState() - releases; boolean free = exclusiveCount(nextc) == 0; if (free) setExclusiveOwnerThread(null); setState(nextc); return free; } protected final boolean tryAcquire(int acquires) { /* * Walkthrough: * 1. If read count nonzero or write count nonzero * and owner is a different thread, fail. * 2. If count would saturate, fail. (This can only * happen if count is already nonzero.) * 3. Otherwise, this thread is eligible for lock if * it is either a reentrant acquire or * queue policy allows it. If so, update state * and set owner. */ Thread current = Thread.currentThread(); int c = getState(); int w = exclusiveCount(c); if (c != 0) { // (Note: if c != 0 and w == 0 then shared count != 0) if (w == 0 || current != getExclusiveOwnerThread()) return false; if (w + exclusiveCount(acquires) > MAX_COUNT) throw new Error("Maximum lock count exceeded"); // Reentrant acquire setState(c + acquires); return true; } if (writerShouldBlock() || !compareAndSetState(c, c + acquires)) return false; setExclusiveOwnerThread(current); return true; } protected final boolean tryReleaseShared(int unused) { HoldCounter rh = cachedHoldCounter; Thread current = Thread.currentThread(); if (rh == null || rh.tid != current.getId()) rh = readHolds.get(); if (rh.tryDecrement() <= 0) throw new IllegalMonitorStateException(); for (;;) { int c = getState(); int nextc = c - SHARED_UNIT; if (compareAndSetState(c, nextc)) return nextc == 0; } } protected final int tryAcquireShared(int unused) { /* * Walkthrough: * 1. If write lock held by another thread, fail. * 2. If count saturated, throw error. * 3. Otherwise, this thread is eligible for * lock wrt state, so ask if it should block * because of queue policy. If not, try * to grant by CASing state and updating count. * Note that step does not check for reentrant * acquires, which is postponed to full version * to avoid having to check hold count in * the more typical non-reentrant case. * 4. If step 3 fails either because thread * apparently not eligible or CAS fails, * chain to version with full retry loop. */ Thread current = Thread.currentThread(); int c = getState(); if (exclusiveCount(c) != 0 && getExclusiveOwnerThread() != current) return -1; if (sharedCount(c) == MAX_COUNT) throw new Error("Maximum lock count exceeded"); if (!readerShouldBlock() && compareAndSetState(c, c + SHARED_UNIT)) { HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != current.getId()) cachedHoldCounter = rh = readHolds.get(); rh.count++; return 1; } return fullTryAcquireShared(current); } /** {@collect.stats} * {@description.open} * Full version of acquire for reads, that handles CAS misses * and reentrant reads not dealt with in tryAcquireShared. * {@description.close} */ final int fullTryAcquireShared(Thread current) { /* * This code is in part redundant with that in * tryAcquireShared but is simpler overall by not * complicating tryAcquireShared with interactions between * retries and lazily reading hold counts. */ HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != current.getId()) rh = readHolds.get(); for (;;) { int c = getState(); int w = exclusiveCount(c); if ((w != 0 && getExclusiveOwnerThread() != current) || ((rh.count | w) == 0 && readerShouldBlock())) return -1; if (sharedCount(c) == MAX_COUNT) throw new Error("Maximum lock count exceeded"); if (compareAndSetState(c, c + SHARED_UNIT)) { cachedHoldCounter = rh; // cache for release rh.count++; return 1; } } } /** {@collect.stats} * {@description.open} * Performs tryLock for write, enabling barging in both modes. * This is identical in effect to tryAcquire except for lack * of calls to writerShouldBlock * {@description.close} */ final boolean tryWriteLock() { Thread current = Thread.currentThread(); int c = getState(); if (c != 0) { int w = exclusiveCount(c); if (w == 0 ||current != getExclusiveOwnerThread()) return false; if (w == MAX_COUNT) throw new Error("Maximum lock count exceeded"); } if (!compareAndSetState(c, c + 1)) return false; setExclusiveOwnerThread(current); return true; } /** {@collect.stats} * {@description.open} * Performs tryLock for read, enabling barging in both modes. * This is identical in effect to tryAcquireShared except for * lack of calls to readerShouldBlock * {@description.close} */ final boolean tryReadLock() { Thread current = Thread.currentThread(); for (;;) { int c = getState(); if (exclusiveCount(c) != 0 && getExclusiveOwnerThread() != current) return false; if (sharedCount(c) == MAX_COUNT) throw new Error("Maximum lock count exceeded"); if (compareAndSetState(c, c + SHARED_UNIT)) { HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != current.getId()) cachedHoldCounter = rh = readHolds.get(); rh.count++; return true; } } } protected final boolean isHeldExclusively() { // While we must in general read state before owner, // we don't need to do so to check if current thread is owner return getExclusiveOwnerThread() == Thread.currentThread(); } // Methods relayed to outer class final ConditionObject newCondition() { return new ConditionObject(); } final Thread getOwner() { // Must read state before owner to ensure memory consistency return ((exclusiveCount(getState()) == 0)? null : getExclusiveOwnerThread()); } final int getReadLockCount() { return sharedCount(getState()); } final boolean isWriteLocked() { return exclusiveCount(getState()) != 0; } final int getWriteHoldCount() { return isHeldExclusively() ? exclusiveCount(getState()) : 0; } final int getReadHoldCount() { return getReadLockCount() == 0? 0 : readHolds.get().count; } /** {@collect.stats} * {@description.open} * Reconstitute this lock instance from a stream * {@description.close} * @param s the stream */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); readHolds = new ThreadLocalHoldCounter(); setState(0); // reset to unlocked state } final int getCount() { return getState(); } } /** {@collect.stats} * {@description.open} * Nonfair version of Sync * {@description.close} */ final static class NonfairSync extends Sync { private static final long serialVersionUID = -8159625535654395037L; final boolean writerShouldBlock() { return false; // writers can always barge } final boolean readerShouldBlock() { /* As a heuristic to avoid indefinite writer starvation, * block if the thread that momentarily appears to be head * of queue, if one exists, is a waiting writer. This is * only a probabilistic effect since a new reader will not * block if there is a waiting writer behind other enabled * readers that have not yet drained from the queue. */ return apparentlyFirstQueuedIsExclusive(); } } /** {@collect.stats} * {@description.open} * Fair version of Sync * {@description.close} */ final static class FairSync extends Sync { private static final long serialVersionUID = -2274990926593161451L; final boolean writerShouldBlock() { return hasQueuedPredecessors(); } final boolean readerShouldBlock() { return hasQueuedPredecessors(); } } /** {@collect.stats} * {@description.open} * The lock returned by method {@link ReentrantReadWriteLock#readLock}. * {@description.close} */ public static class ReadLock implements Lock, java.io.Serializable { private static final long serialVersionUID = -5992448646407690164L; private final Sync sync; /** {@collect.stats} * {@description.open} * Constructor for use by subclasses * {@description.close} * * @param lock the outer lock object * @throws NullPointerException if the lock is null */ protected ReadLock(ReentrantReadWriteLock lock) { sync = lock.sync; } /** {@collect.stats} * {@description.open} * Acquires the read lock. * * <p>Acquires the read lock if the write lock is not held by * another thread and returns immediately. * * <p>If the write lock is held by another thread then * the current thread becomes disabled for thread scheduling * purposes and lies dormant until the read lock has been acquired. * {@description.close} */ public void lock() { sync.acquireShared(1); } /** {@collect.stats} * {@description.open} * Acquires the read lock unless the current thread is * {@linkplain Thread#interrupt interrupted}. * * <p>Acquires the read lock if the write lock is not held * by another thread and returns immediately. * * <p>If the write lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until one of two things happens: * * <ul> * * <li>The read lock is acquired by the current thread; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread. * * </ul> * * <p>If the current thread: * * <ul> * * <li>has its interrupted status set on entry to this method; or * * <li>is {@linkplain Thread#interrupt interrupted} while * acquiring the read lock, * * </ul> * * then {@link InterruptedException} is thrown and the current * thread's interrupted status is cleared. * * <p>In this implementation, as this method is an explicit * interruption point, preference is given to responding to * the interrupt over normal or reentrant acquisition of the * lock. * {@description.close} * * @throws InterruptedException if the current thread is interrupted */ public void lockInterruptibly() throws InterruptedException { sync.acquireSharedInterruptibly(1); } /** {@collect.stats} * {@description.open} * Acquires the read lock only if the write lock is not held by * another thread at the time of invocation. * * <p>Acquires the read lock if the write lock is not held by * another thread and returns immediately with the value * {@code true}. Even when this lock has been set to use a * fair ordering policy, a call to {@code tryLock()} * <em>will</em> immediately acquire the read lock if it is * available, whether or not other threads are currently * waiting for the read lock. This &quot;barging&quot; behavior * can be useful in certain circumstances, even though it * breaks fairness. If you want to honor the fairness setting * for this lock, then use {@link #tryLock(long, TimeUnit) * tryLock(0, TimeUnit.SECONDS) } which is almost equivalent * (it also detects interruption). * * <p>If the write lock is held by another thread then * this method will return immediately with the value * {@code false}. * {@description.close} * * @return {@code true} if the read lock was acquired */ public boolean tryLock() { return sync.tryReadLock(); } /** {@collect.stats} * {@description.open} * Acquires the read lock if the write lock is not held by * another thread within the given waiting time and the * current thread has not been {@linkplain Thread#interrupt * interrupted}. * * <p>Acquires the read lock if the write lock is not held by * another thread and returns immediately with the value * {@code true}. If this lock has been set to use a fair * ordering policy then an available lock <em>will not</em> be * acquired if any other threads are waiting for the * lock. This is in contrast to the {@link #tryLock()} * method. If you want a timed {@code tryLock} that does * permit barging on a fair lock then combine the timed and * un-timed forms together: * * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... } * </pre> * * <p>If the write lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until one of three things happens: * * <ul> * * <li>The read lock is acquired by the current thread; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The specified waiting time elapses. * * </ul> * * <p>If the read lock is acquired then the value {@code true} is * returned. * * <p>If the current thread: * * <ul> * * <li>has its interrupted status set on entry to this method; or * * <li>is {@linkplain Thread#interrupt interrupted} while * acquiring the read lock, * * </ul> then {@link InterruptedException} is thrown and the * current thread's interrupted status is cleared. * * <p>If the specified waiting time elapses then the value * {@code false} is returned. If the time is less than or * equal to zero, the method will not wait at all. * * <p>In this implementation, as this method is an explicit * interruption point, preference is given to responding to * the interrupt over normal or reentrant acquisition of the * lock, and over reporting the elapse of the waiting time. * {@description.close} * * @param timeout the time to wait for the read lock * @param unit the time unit of the timeout argument * @return {@code true} if the read lock was acquired * @throws InterruptedException if the current thread is interrupted * @throws NullPointerException if the time unit is null * */ public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } /** {@collect.stats} * {@description.open} * Attempts to release this lock. * * <p> If the number of readers is now zero then the lock * is made available for write lock attempts. * {@description.close} */ public void unlock() { sync.releaseShared(1); } /** {@collect.stats} * {@description.open} * Throws {@code UnsupportedOperationException} because * {@code ReadLocks} do not support conditions. * {@description.close} * * @throws UnsupportedOperationException always */ public Condition newCondition() { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Returns a string identifying this lock, as well as its lock state. * The state, in brackets, includes the String {@code "Read locks ="} * followed by the number of held read locks. * {@description.close} * * @return a string identifying this lock, as well as its lock state */ public String toString() { int r = sync.getReadLockCount(); return super.toString() + "[Read locks = " + r + "]"; } } /** {@collect.stats} * {@description.open} * The lock returned by method {@link ReentrantReadWriteLock#writeLock}. * {@description.close} */ public static class WriteLock implements Lock, java.io.Serializable { private static final long serialVersionUID = -4992448646407690164L; private final Sync sync; /** {@collect.stats} * {@description.open} * Constructor for use by subclasses * {@description.close} * * @param lock the outer lock object * @throws NullPointerException if the lock is null */ protected WriteLock(ReentrantReadWriteLock lock) { sync = lock.sync; } /** {@collect.stats} * {@description.open} * Acquires the write lock. * {@description.close} * * {@property.open} * <p>Acquires the write lock if neither the read nor write lock * are held by another thread * and returns immediately, setting the write lock hold count to * one. * * <p>If the current thread already holds the write lock then the * hold count is incremented by one and the method returns * immediately. * {@property.close} * * {@description.open} * <p>If the lock is held by another thread then the current * thread becomes disabled for thread scheduling purposes and * lies dormant until the write lock has been acquired, at which * time the write lock hold count is set to one. * {@description.close} */ public void lock() { sync.acquire(1); } /** {@collect.stats} * {@description.open} * Acquires the write lock unless the current thread is * {@linkplain Thread#interrupt interrupted}. * {@description.close} * * {@property.open} * <p>Acquires the write lock if neither the read nor write lock * are held by another thread * and returns immediately, setting the write lock hold count to * one. * * <p>If the current thread already holds this lock then the * hold count is incremented by one and the method returns * immediately. * {@property.close} * * {@description.open} * <p>If the lock is held by another thread then the current * thread becomes disabled for thread scheduling purposes and * lies dormant until one of two things happens: * * <ul> * * <li>The write lock is acquired by the current thread; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread. * * </ul> * * <p>If the write lock is acquired by the current thread then the * lock hold count is set to one. * * <p>If the current thread: * * <ul> * * <li>has its interrupted status set on entry to this method; * or * * <li>is {@linkplain Thread#interrupt interrupted} while * acquiring the write lock, * * </ul> * * then {@link InterruptedException} is thrown and the current * thread's interrupted status is cleared. * * <p>In this implementation, as this method is an explicit * interruption point, preference is given to responding to * the interrupt over normal or reentrant acquisition of the * lock. * {@description.close} * * @throws InterruptedException if the current thread is interrupted */ public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } /** {@collect.stats} * {@description.open} * Acquires the write lock only if it is not held by another thread * at the time of invocation. * * <p>Acquires the write lock if neither the read nor write lock * are held by another thread * and returns immediately with the value {@code true}, * setting the write lock hold count to one. Even when this lock has * been set to use a fair ordering policy, a call to * {@code tryLock()} <em>will</em> immediately acquire the * lock if it is available, whether or not other threads are * currently waiting for the write lock. This &quot;barging&quot; * behavior can be useful in certain circumstances, even * though it breaks fairness. If you want to honor the * fairness setting for this lock, then use {@link * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } * which is almost equivalent (it also detects interruption). * * <p> If the current thread already holds this lock then the * hold count is incremented by one and the method returns * {@code true}. * * <p>If the lock is held by another thread then this method * will return immediately with the value {@code false}. * {@description.close} * * @return {@code true} if the lock was free and was acquired * by the current thread, or the write lock was already held * by the current thread; and {@code false} otherwise. */ public boolean tryLock( ) { return sync.tryWriteLock(); } /** {@collect.stats} * {@description.open} * Acquires the write lock if it is not held by another thread * within the given waiting time and the current thread has * not been {@linkplain Thread#interrupt interrupted}. * * <p>Acquires the write lock if neither the read nor write lock * are held by another thread * and returns immediately with the value {@code true}, * setting the write lock hold count to one. If this lock has been * set to use a fair ordering policy then an available lock * <em>will not</em> be acquired if any other threads are * waiting for the write lock. This is in contrast to the {@link * #tryLock()} method. If you want a timed {@code tryLock} * that does permit barging on a fair lock then combine the * timed and un-timed forms together: * * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... } * </pre> * * <p>If the current thread already holds this lock then the * hold count is incremented by one and the method returns * {@code true}. * * <p>If the lock is held by another thread then the current * thread becomes disabled for thread scheduling purposes and * lies dormant until one of three things happens: * * <ul> * * <li>The write lock is acquired by the current thread; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The specified waiting time elapses * * </ul> * * <p>If the write lock is acquired then the value {@code true} is * returned and the write lock hold count is set to one. * * <p>If the current thread: * * <ul> * * <li>has its interrupted status set on entry to this method; * or * * <li>is {@linkplain Thread#interrupt interrupted} while * acquiring the write lock, * * </ul> * * then {@link InterruptedException} is thrown and the current * thread's interrupted status is cleared. * * <p>If the specified waiting time elapses then the value * {@code false} is returned. If the time is less than or * equal to zero, the method will not wait at all. * * <p>In this implementation, as this method is an explicit * interruption point, preference is given to responding to * the interrupt over normal or reentrant acquisition of the * lock, and over reporting the elapse of the waiting time. * {@description.close} * * @param timeout the time to wait for the write lock * @param unit the time unit of the timeout argument * * @return {@code true} if the lock was free and was acquired * by the current thread, or the write lock was already held by the * current thread; and {@code false} if the waiting time * elapsed before the lock could be acquired. * * @throws InterruptedException if the current thread is interrupted * @throws NullPointerException if the time unit is null * */ public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(timeout)); } /** {@collect.stats} * {@description.open} * Attempts to release this lock. * * <p>If the current thread is the holder of this lock then * the hold count is decremented. If the hold count is now * zero then the lock is released. If the current thread is * not the holder of this lock then {@link * IllegalMonitorStateException} is thrown. * {@description.close} * * @throws IllegalMonitorStateException if the current thread does not * hold this lock. */ public void unlock() { sync.release(1); } /** {@collect.stats} * {@description.open} * Returns a {@link Condition} instance for use with this * {@link Lock} instance. * <p>The returned {@link Condition} instance supports the same * usages as do the {@link Object} monitor methods ({@link * Object#wait() wait}, {@link Object#notify notify}, and {@link * Object#notifyAll notifyAll}) when used with the built-in * monitor lock. * * <ul> * * <li>If this write lock is not held when any {@link * Condition} method is called then an {@link * IllegalMonitorStateException} is thrown. (Read locks are * held independently of write locks, so are not checked or * affected. However it is essentially always an error to * invoke a condition waiting method when the current thread * has also acquired read locks, since other threads that * could unblock it will not be able to acquire the write * lock.) * * <li>When the condition {@linkplain Condition#await() waiting} * methods are called the write lock is released and, before * they return, the write lock is reacquired and the lock hold * count restored to what it was when the method was called. * * <li>If a thread is {@linkplain Thread#interrupt interrupted} while * waiting then the wait will terminate, an {@link * InterruptedException} will be thrown, and the thread's * interrupted status will be cleared. * * <li> Waiting threads are signalled in FIFO order. * * <li>The ordering of lock reacquisition for threads returning * from waiting methods is the same as for threads initially * acquiring the lock, which is in the default case not specified, * but for <em>fair</em> locks favors those threads that have been * waiting the longest. * * </ul> * {@description.close} * * @return the Condition object */ public Condition newCondition() { return sync.newCondition(); } /** {@collect.stats} * {@description.open} * Returns a string identifying this lock, as well as its lock * state. The state, in brackets includes either the String * {@code "Unlocked"} or the String {@code "Locked by"} * followed by the {@linkplain Thread#getName name} of the owning thread. * {@description.close} * * @return a string identifying this lock, as well as its lock state */ public String toString() { Thread o = sync.getOwner(); return super.toString() + ((o == null) ? "[Unlocked]" : "[Locked by thread " + o.getName() + "]"); } /** {@collect.stats} * {@description.open} * Queries if this write lock is held by the current thread. * Identical in effect to {@link * ReentrantReadWriteLock#isWriteLockedByCurrentThread}. * {@description.close} * * @return {@code true} if the current thread holds this lock and * {@code false} otherwise * @since 1.6 */ public boolean isHeldByCurrentThread() { return sync.isHeldExclusively(); } /** {@collect.stats} * {@description.open} * Queries the number of holds on this write lock by the current * thread. A thread has a hold on a lock for each lock action * that is not matched by an unlock action. Identical in effect * to {@link ReentrantReadWriteLock#getWriteHoldCount}. * {@description.close} * * @return the number of holds on this lock by the current thread, * or zero if this lock is not held by the current thread * @since 1.6 */ public int getHoldCount() { return sync.getWriteHoldCount(); } } // Instrumentation and status /** {@collect.stats} * {@description.open} * Returns {@code true} if this lock has fairness set true. * {@description.close} * * @return {@code true} if this lock has fairness set true */ public final boolean isFair() { return sync instanceof FairSync; } /** {@collect.stats} * {@description.open} * Returns the thread that currently owns the write lock, or * {@code null} if not owned. When this method is called by a * thread that is not the owner, the return value reflects a * best-effort approximation of current lock status. For example, * the owner may be momentarily {@code null} even if there are * threads trying to acquire the lock but have not yet done so. * This method is designed to facilitate construction of * subclasses that provide more extensive lock monitoring * facilities. * {@description.close} * * @return the owner, or {@code null} if not owned */ protected Thread getOwner() { return sync.getOwner(); } /** {@collect.stats} * {@description.open} * Queries the number of read locks held for this lock. This * method is designed for use in monitoring system state, not for * synchronization control. * {@description.close} * @return the number of read locks held. */ public int getReadLockCount() { return sync.getReadLockCount(); } /** {@collect.stats} * {@description.open} * Queries if the write lock is held by any thread. This method is * designed for use in monitoring system state, not for * synchronization control. * {@description.close} * * @return {@code true} if any thread holds the write lock and * {@code false} otherwise */ public boolean isWriteLocked() { return sync.isWriteLocked(); } /** {@collect.stats} * {@description.open} * Queries if the write lock is held by the current thread. * {@description.close} * * @return {@code true} if the current thread holds the write lock and * {@code false} otherwise */ public boolean isWriteLockedByCurrentThread() { return sync.isHeldExclusively(); } /** {@collect.stats} * {@description.open} * Queries the number of reentrant write holds on this lock by the * current thread. A writer thread has a hold on a lock for * each lock action that is not matched by an unlock action. * {@description.close} * * @return the number of holds on the write lock by the current thread, * or zero if the write lock is not held by the current thread */ public int getWriteHoldCount() { return sync.getWriteHoldCount(); } /** {@collect.stats} * {@description.open} * Queries the number of reentrant read holds on this lock by the * current thread. A reader thread has a hold on a lock for * each lock action that is not matched by an unlock action. * {@description.close} * * @return the number of holds on the read lock by the current thread, * or zero if the read lock is not held by the current thread * @since 1.6 */ public int getReadHoldCount() { return sync.getReadHoldCount(); } /** {@collect.stats} * {@description.open} * Returns a collection containing threads that may be waiting to * acquire the write lock. Because the actual set of threads may * change dynamically while constructing this result, the returned * collection is only a best-effort estimate. The elements of the * returned collection are in no particular order. This method is * designed to facilitate construction of subclasses that provide * more extensive lock monitoring facilities. * {@description.close} * * @return the collection of threads */ protected Collection<Thread> getQueuedWriterThreads() { return sync.getExclusiveQueuedThreads(); } /** {@collect.stats} * {@description.open} * Returns a collection containing threads that may be waiting to * acquire the read lock. Because the actual set of threads may * change dynamically while constructing this result, the returned * collection is only a best-effort estimate. The elements of the * returned collection are in no particular order. This method is * designed to facilitate construction of subclasses that provide * more extensive lock monitoring facilities. * {@description.close} * * @return the collection of threads */ protected Collection<Thread> getQueuedReaderThreads() { return sync.getSharedQueuedThreads(); } /** {@collect.stats} * {@description.open} * Queries whether any threads are waiting to acquire the read or * write lock. Note that because cancellations may occur at any * time, a {@code true} return does not guarantee that any other * thread will ever acquire a lock. This method is designed * primarily for use in monitoring of the system state. * {@description.close} * * @return {@code true} if there may be other threads waiting to * acquire the lock */ public final boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } /** {@collect.stats} * {@description.open} * Queries whether the given thread is waiting to acquire either * the read or write lock. Note that because cancellations may * occur at any time, a {@code true} return does not guarantee * that this thread will ever acquire a lock. This method is * designed primarily for use in monitoring of the system state. * {@description.close} * * @param thread the thread * @return {@code true} if the given thread is queued waiting for this lock * @throws NullPointerException if the thread is null */ public final boolean hasQueuedThread(Thread thread) { return sync.isQueued(thread); } /** {@collect.stats} * {@description.open} * Returns an estimate of the number of threads waiting to acquire * either the read or write lock. The value is only an estimate * because the number of threads may change dynamically while this * method traverses internal data structures. This method is * designed for use in monitoring of the system state, not for * synchronization control. * {@description.close} * * @return the estimated number of threads waiting for this lock */ public final int getQueueLength() { return sync.getQueueLength(); } /** {@collect.stats} * {@description.open} * Returns a collection containing threads that may be waiting to * acquire either the read or write lock. Because the actual set * of threads may change dynamically while constructing this * result, the returned collection is only a best-effort estimate. * The elements of the returned collection are in no particular * order. This method is designed to facilitate construction of * subclasses that provide more extensive monitoring facilities. * {@description.close} * * @return the collection of threads */ protected Collection<Thread> getQueuedThreads() { return sync.getQueuedThreads(); } /** {@collect.stats} * {@description.open} * Queries whether any threads are waiting on the given condition * associated with the write lock. Note that because timeouts and * interrupts may occur at any time, a {@code true} return does * not guarantee that a future {@code signal} will awaken any * threads. This method is designed primarily for use in * monitoring of the system state. * {@description.close} * * @param condition the condition * @return {@code true} if there are any waiting threads * @throws IllegalMonitorStateException if this lock is not held * @throws IllegalArgumentException if the given condition is * not associated with this lock * @throws NullPointerException if the condition is null */ public boolean hasWaiters(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); } /** {@collect.stats} * {@description.open} * Returns an estimate of the number of threads waiting on the * given condition associated with the write lock. Note that because * timeouts and interrupts may occur at any time, the estimate * serves only as an upper bound on the actual number of waiters. * This method is designed for use in monitoring of the system * state, not for synchronization control. * {@description.close} * * @param condition the condition * @return the estimated number of waiting threads * @throws IllegalMonitorStateException if this lock is not held * @throws IllegalArgumentException if the given condition is * not associated with this lock * @throws NullPointerException if the condition is null */ public int getWaitQueueLength(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); } /** {@collect.stats} * {@description.open} * Returns a collection containing those threads that may be * waiting on the given condition associated with the write lock. * Because the actual set of threads may change dynamically while * constructing this result, the returned collection is only a * best-effort estimate. The elements of the returned collection * are in no particular order. This method is designed to * facilitate construction of subclasses that provide more * extensive condition monitoring facilities. * {@description.close} * * @param condition the condition * @return the collection of threads * @throws IllegalMonitorStateException if this lock is not held * @throws IllegalArgumentException if the given condition is * not associated with this lock * @throws NullPointerException if the condition is null */ protected Collection<Thread> getWaitingThreads(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition); } /** {@collect.stats} * {@description.open} * Returns a string identifying this lock, as well as its lock state. * The state, in brackets, includes the String {@code "Write locks ="} * followed by the number of reentrantly held write locks, and the * String {@code "Read locks ="} followed by the number of held * read locks. * {@description.close} * * @return a string identifying this lock, as well as its lock state */ public String toString() { int c = sync.getCount(); int w = Sync.exclusiveCount(c); int r = Sync.sharedCount(c); return super.toString() + "[Write locks = " + w + ", Read locks = " + r + "]"; } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ /** {@collect.stats} * {@description.open} * Interfaces and classes providing a framework for locking and waiting * for conditions that is distinct from built-in synchronization and * monitors. The framework permits much greater flexibility in the use of * locks and conditions, at the expense of more awkward syntax. * * <p>The {@link java.util.concurrent.locks.Lock} interface supports * locking disciplines that differ in semantics (reentrant, fair, etc), * and that can be used in non-block-structured contexts including * hand-over-hand and lock reordering algorithms. The main implementation * is {@link java.util.concurrent.locks.ReentrantLock}. * * <p>The {@link java.util.concurrent.locks.ReadWriteLock} interface * similarly defines locks that may be shared among readers but are * exclusive to writers. Only a single implementation, {@link * java.util.concurrent.locks.ReentrantReadWriteLock}, is provided, since * it covers most standard usage contexts. But programmers may create * their own implementations to cover nonstandard requirements. * * <p>The {@link java.util.concurrent.locks.Condition} interface * describes condition variables that may be associated with Locks. * These are similar in usage to the implicit monitors accessed using * {@code Object.wait}, but offer extended capabilities. * In particular, multiple {@code Condition} objects may be associated * with a single {@code Lock}. To avoid compatibility issues, the * names of {@code Condition} methods are different from the * corresponding {@code Object} versions. * * <p>The {@link java.util.concurrent.locks.AbstractQueuedSynchronizer} * class serves as a useful superclass for defining locks and other * synchronizers that rely on queuing blocked threads. The {@link * java.util.concurrent.locks.AbstractQueuedLongSynchronizer} class * provides the same functionality but extends support to 64 bits of * synchronization state. Both extend class {@link * java.util.concurrent.locks.AbstractOwnableSynchronizer}, a simple * class that helps record the thread currently holding exclusive * synchronization. The {@link java.util.concurrent.locks.LockSupport} * class provides lower-level blocking and unblocking support that is * useful for those developers implementing their own customized lock * classes. * {@description.close} * * @since 1.5 */ package java.util.concurrent.locks;
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.locks; import java.util.concurrent.TimeUnit; /** {@collect.stats} * {@description.open} * {@code Lock} implementations provide more extensive locking * operations than can be obtained using {@code synchronized} methods * and statements. They allow more flexible structuring, may have * quite different properties, and may support multiple associated * {@link Condition} objects. * * <p>A lock is a tool for controlling access to a shared resource by * multiple threads. Commonly, a lock provides exclusive access to a * shared resource: only one thread at a time can acquire the lock and * all access to the shared resource requires that the lock be * acquired first. However, some locks may allow concurrent access to * a shared resource, such as the read lock of a {@link ReadWriteLock}. * {@description.close} * * {@property.open} * <p>The use of {@code synchronized} methods or statements provides * access to the implicit monitor lock associated with every object, but * forces all lock acquisition and release to occur in a block-structured way: * when multiple locks are acquired they must be released in the opposite * order, and all locks must be released in the same lexical scope in which * they were acquired. * {@property.close} * * {@description.open} * <p>While the scoping mechanism for {@code synchronized} methods * and statements makes it much easier to program with monitor locks, * and helps avoid many common programming errors involving locks, * there are occasions where you need to work with locks in a more * flexible way. For example, some algorithms for traversing * concurrently accessed data structures require the use of * &quot;hand-over-hand&quot; or &quot;chain locking&quot;: you * acquire the lock of node A, then node B, then release A and acquire * C, then release B and acquire D and so on. Implementations of the * {@code Lock} interface enable the use of such techniques by * allowing a lock to be acquired and released in different scopes, * and allowing multiple locks to be acquired and released in any * order. * * <p>With this increased flexibility comes additional * responsibility. The absence of block-structured locking removes the * automatic release of locks that occurs with {@code synchronized} * methods and statements. In most cases, the following idiom * should be used: * * <pre><tt> Lock l = ...; * l.lock(); * try { * // access the resource protected by this lock * } finally { * l.unlock(); * } * </tt></pre> * * When locking and unlocking occur in different scopes, care must be * taken to ensure that all code that is executed while the lock is * held is protected by try-finally or try-catch to ensure that the * lock is released when necessary. * * <p>{@code Lock} implementations provide additional functionality * over the use of {@code synchronized} methods and statements by * providing a non-blocking attempt to acquire a lock ({@link * #tryLock()}), an attempt to acquire the lock that can be * interrupted ({@link #lockInterruptibly}, and an attempt to acquire * the lock that can timeout ({@link #tryLock(long, TimeUnit)}). * * <p>A {@code Lock} class can also provide behavior and semantics * that is quite different from that of the implicit monitor lock, * such as guaranteed ordering, non-reentrant usage, or deadlock * detection. If an implementation provides such specialized semantics * then the implementation must document those semantics. * * <p>Note that {@code Lock} instances are just normal objects and can * themselves be used as the target in a {@code synchronized} statement. * Acquiring the * monitor lock of a {@code Lock} instance has no specified relationship * with invoking any of the {@link #lock} methods of that instance. * It is recommended that to avoid confusion you never use {@code Lock} * instances in this way, except within their own implementation. * * <p>Except where noted, passing a {@code null} value for any * parameter will result in a {@link NullPointerException} being * thrown. * * <h3>Memory Synchronization</h3> * * <p>All {@code Lock} implementations <em>must</em> enforce the same * memory synchronization semantics as provided by the built-in monitor * lock, as described in <a href="http://java.sun.com/docs/books/jls/"> * The Java Language Specification, Third Edition (17.4 Memory Model)</a>: * <ul> * <li>A successful {@code lock} operation has the same memory * synchronization effects as a successful <em>Lock</em> action. * <li>A successful {@code unlock} operation has the same * memory synchronization effects as a successful <em>Unlock</em> action. * </ul> * * Unsuccessful locking and unlocking operations, and reentrant * locking/unlocking operations, do not require any memory * synchronization effects. * * <h3>Implementation Considerations</h3> * * <p> The three forms of lock acquisition (interruptible, * non-interruptible, and timed) may differ in their performance * characteristics, ordering guarantees, or other implementation * qualities. Further, the ability to interrupt the <em>ongoing</em> * acquisition of a lock may not be available in a given {@code Lock} * class. Consequently, an implementation is not required to define * exactly the same guarantees or semantics for all three forms of * lock acquisition, nor is it required to support interruption of an * ongoing lock acquisition. An implementation is required to clearly * document the semantics and guarantees provided by each of the * locking methods. It must also obey the interruption semantics as * defined in this interface, to the extent that interruption of lock * acquisition is supported: which is either totally, or only on * method entry. * * <p>As interruption generally implies cancellation, and checks for * interruption are often infrequent, an implementation can favor responding * to an interrupt over normal method return. This is true even if it can be * shown that the interrupt occurred after another action may have unblocked * the thread. An implementation should document this behavior. * {@description.close} * * @see ReentrantLock * @see Condition * @see ReadWriteLock * * @since 1.5 * @author Doug Lea */ public interface Lock { /** {@collect.stats} * {@description.open} * Acquires the lock. * * <p>If the lock is not available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until the * lock has been acquired. * * <p><b>Implementation Considerations</b> * * <p>A {@code Lock} implementation may be able to detect erroneous use * of the lock, such as an invocation that would cause deadlock, and * may throw an (unchecked) exception in such circumstances. The * circumstances and the exception type must be documented by that * {@code Lock} implementation. * {@description.close} */ void lock(); /** {@collect.stats} * {@description.open} * Acquires the lock unless the current thread is * {@linkplain Thread#interrupt interrupted}. * * <p>Acquires the lock if it is available and returns immediately. * * <p>If the lock is not available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * one of two things happens: * * <ul> * <li>The lock is acquired by the current thread; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} the * current thread, and interruption of lock acquisition is supported. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while acquiring the * lock, and interruption of lock acquisition is supported, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p><b>Implementation Considerations</b> * * <p>The ability to interrupt a lock acquisition in some * implementations may not be possible, and if possible may be an * expensive operation. The programmer should be aware that this * may be the case. An implementation should document when this is * the case. * * <p>An implementation can favor responding to an interrupt over * normal method return. * * <p>A {@code Lock} implementation may be able to detect * erroneous use of the lock, such as an invocation that would * cause deadlock, and may throw an (unchecked) exception in such * circumstances. The circumstances and the exception type must * be documented by that {@code Lock} implementation. * {@description.close} * * @throws InterruptedException if the current thread is * interrupted while acquiring the lock (and interruption * of lock acquisition is supported). */ void lockInterruptibly() throws InterruptedException; /** {@collect.stats} * {@description.open} * Acquires the lock only if it is free at the time of invocation. * * <p>Acquires the lock if it is available and returns immediately * with the value {@code true}. * If the lock is not available then this method will return * immediately with the value {@code false}. * * <p>A typical usage idiom for this method would be: * <pre> * Lock lock = ...; * if (lock.tryLock()) { * try { * // manipulate protected state * } finally { * lock.unlock(); * } * } else { * // perform alternative actions * } * </pre> * This usage ensures that the lock is unlocked if it was acquired, and * doesn't try to unlock if the lock was not acquired. * {@description.close} * * @return {@code true} if the lock was acquired and * {@code false} otherwise */ boolean tryLock(); /** {@collect.stats} * {@description.open} * Acquires the lock if it is free within the given waiting time and the * current thread has not been {@linkplain Thread#interrupt interrupted}. * * <p>If the lock is available this method returns immediately * with the value {@code true}. * If the lock is not available then * the current thread becomes disabled for thread scheduling * purposes and lies dormant until one of three things happens: * <ul> * <li>The lock is acquired by the current thread; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} the * current thread, and interruption of lock acquisition is supported; or * <li>The specified waiting time elapses * </ul> * * <p>If the lock is acquired then the value {@code true} is returned. * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while acquiring * the lock, and interruption of lock acquisition is supported, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the specified waiting time elapses then the value {@code false} * is returned. * If the time is * less than or equal to zero, the method will not wait at all. * * <p><b>Implementation Considerations</b> * * <p>The ability to interrupt a lock acquisition in some implementations * may not be possible, and if possible may * be an expensive operation. * The programmer should be aware that this may be the case. An * implementation should document when this is the case. * * <p>An implementation can favor responding to an interrupt over normal * method return, or reporting a timeout. * * <p>A {@code Lock} implementation may be able to detect * erroneous use of the lock, such as an invocation that would cause * deadlock, and may throw an (unchecked) exception in such circumstances. * The circumstances and the exception type must be documented by that * {@code Lock} implementation. * {@description.close} * * @param time the maximum time to wait for the lock * @param unit the time unit of the {@code time} argument * @return {@code true} if the lock was acquired and {@code false} * if the waiting time elapsed before the lock was acquired * * @throws InterruptedException if the current thread is interrupted * while acquiring the lock (and interruption of lock * acquisition is supported) */ boolean tryLock(long time, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * Releases the lock. * * <p><b>Implementation Considerations</b> * * <p>A {@code Lock} implementation will usually impose * restrictions on which thread can release a lock (typically only the * holder of the lock can release it) and may throw * an (unchecked) exception if the restriction is violated. * Any restrictions and the exception * type must be documented by that {@code Lock} implementation. * {@description.close} */ void unlock(); /** {@collect.stats} * {@description.open} * Returns a new {@link Condition} instance that is bound to this * {@code Lock} instance. * * <p>Before waiting on the condition the lock must be held by the * current thread. * A call to {@link Condition#await()} will atomically release the lock * before waiting and re-acquire the lock before the wait returns. * * <p><b>Implementation Considerations</b> * * <p>The exact operation of the {@link Condition} instance depends on * the {@code Lock} implementation and must be documented by that * implementation. * {@description.close} * * @return A new {@link Condition} instance for this {@code Lock} instance * @throws UnsupportedOperationException if this {@code Lock} * implementation does not support conditions */ Condition newCondition(); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.locks; import java.util.concurrent.*; import java.util.Date; /** {@collect.stats} * {@description.open} * {@code Condition} factors out the {@code Object} monitor * methods ({@link Object#wait() wait}, {@link Object#notify notify} * and {@link Object#notifyAll notifyAll}) into distinct objects to * give the effect of having multiple wait-sets per object, by * combining them with the use of arbitrary {@link Lock} implementations. * Where a {@code Lock} replaces the use of {@code synchronized} methods * and statements, a {@code Condition} replaces the use of the Object * monitor methods. * {@description.close} * * {@property.open} * <p>Conditions (also known as <em>condition queues</em> or * <em>condition variables</em>) provide a means for one thread to * suspend execution (to &quot;wait&quot;) until notified by another * thread that some state condition may now be true. Because access * to this shared state information occurs in different threads, it * must be protected, so a lock of some form is associated with the * condition. The key property that waiting for a condition provides * is that it <em>atomically</em> releases the associated lock and * suspends the current thread, just like {@code Object.wait}. * {@property.close} * * {@description.open} * <p>A {@code Condition} instance is intrinsically bound to a lock. * To obtain a {@code Condition} instance for a particular {@link Lock} * instance use its {@link Lock#newCondition newCondition()} method. * * <p>As an example, suppose we have a bounded buffer which supports * {@code put} and {@code take} methods. If a * {@code take} is attempted on an empty buffer, then the thread will block * until an item becomes available; if a {@code put} is attempted on a * full buffer, then the thread will block until a space becomes available. * We would like to keep waiting {@code put} threads and {@code take} * threads in separate wait-sets so that we can use the optimization of * only notifying a single thread at a time when items or spaces become * available in the buffer. This can be achieved using two * {@link Condition} instances. * <pre> * class BoundedBuffer { * <b>final Lock lock = new ReentrantLock();</b> * final Condition notFull = <b>lock.newCondition(); </b> * final Condition notEmpty = <b>lock.newCondition(); </b> * * final Object[] items = new Object[100]; * int putptr, takeptr, count; * * public void put(Object x) throws InterruptedException { * <b>lock.lock(); * try {</b> * while (count == items.length) * <b>notFull.await();</b> * items[putptr] = x; * if (++putptr == items.length) putptr = 0; * ++count; * <b>notEmpty.signal();</b> * <b>} finally { * lock.unlock(); * }</b> * } * * public Object take() throws InterruptedException { * <b>lock.lock(); * try {</b> * while (count == 0) * <b>notEmpty.await();</b> * Object x = items[takeptr]; * if (++takeptr == items.length) takeptr = 0; * --count; * <b>notFull.signal();</b> * return x; * <b>} finally { * lock.unlock(); * }</b> * } * } * </pre> * * (The {@link java.util.concurrent.ArrayBlockingQueue} class provides * this functionality, so there is no reason to implement this * sample usage class.) * * <p>A {@code Condition} implementation can provide behavior and semantics * that is * different from that of the {@code Object} monitor methods, such as * guaranteed ordering for notifications, or not requiring a lock to be held * when performing notifications. * If an implementation provides such specialized semantics then the * implementation must document those semantics. * * <p>Note that {@code Condition} instances are just normal objects and can * themselves be used as the target in a {@code synchronized} statement, * and can have their own monitor {@link Object#wait wait} and * {@link Object#notify notification} methods invoked. * Acquiring the monitor lock of a {@code Condition} instance, or using its * monitor methods, has no specified relationship with acquiring the * {@link Lock} associated with that {@code Condition} or the use of its * {@linkplain #await waiting} and {@linkplain #signal signalling} methods. * It is recommended that to avoid confusion you never use {@code Condition} * instances in this way, except perhaps within their own implementation. * * <p>Except where noted, passing a {@code null} value for any parameter * will result in a {@link NullPointerException} being thrown. * * <h3>Implementation Considerations</h3> * {@description.close} * * {@property.open} * <p>When waiting upon a {@code Condition}, a &quot;<em>spurious * wakeup</em>&quot; is permitted to occur, in * general, as a concession to the underlying platform semantics. * This has little practical impact on most application programs as a * {@code Condition} should always be waited upon in a loop, testing * the state predicate that is being waited for. An implementation is * free to remove the possibility of spurious wakeups but it is * recommended that applications programmers always assume that they can * occur and so always wait in a loop. * {@property.close} * * {@description.open} * <p>The three forms of condition waiting * (interruptible, non-interruptible, and timed) may differ in their ease of * implementation on some platforms and in their performance characteristics. * In particular, it may be difficult to provide these features and maintain * specific semantics such as ordering guarantees. * Further, the ability to interrupt the actual suspension of the thread may * not always be feasible to implement on all platforms. * * <p>Consequently, an implementation is not required to define exactly the * same guarantees or semantics for all three forms of waiting, nor is it * required to support interruption of the actual suspension of the thread. * * <p>An implementation is required to * clearly document the semantics and guarantees provided by each of the * waiting methods, and when an implementation does support interruption of * thread suspension then it must obey the interruption semantics as defined * in this interface. * * <p>As interruption generally implies cancellation, and checks for * interruption are often infrequent, an implementation can favor responding * to an interrupt over normal method return. This is true even if it can be * shown that the interrupt occurred after another action may have unblocked * the thread. An implementation should document this behavior. * {@description.close} * * @since 1.5 * @author Doug Lea */ public interface Condition { /** {@collect.stats} * {@description.open} * Causes the current thread to wait until it is signalled or * {@linkplain Thread#interrupt interrupted}. * * <p>The lock associated with this {@code Condition} is atomically * released and the current thread becomes disabled for thread scheduling * purposes and lies dormant until <em>one</em> of four things happens: * <ul> * <li>Some other thread invokes the {@link #signal} method for this * {@code Condition} and the current thread happens to be chosen as the * thread to be awakened; or * <li>Some other thread invokes the {@link #signalAll} method for this * {@code Condition}; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} the * current thread, and interruption of thread suspension is supported; or * <li>A &quot;<em>spurious wakeup</em>&quot; occurs. * </ul> * * <p>In all cases, before this method can return the current thread must * re-acquire the lock associated with this condition. When the * thread returns it is <em>guaranteed</em> to hold this lock. * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * and interruption of thread suspension is supported, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. It is not specified, in the first * case, whether or not the test for interruption occurs before the lock * is released. * * <p><b>Implementation Considerations</b> * {@description.close} * * {@property.open} * <p>The current thread is assumed to hold the lock associated with this * {@code Condition} when this method is called. * It is up to the implementation to determine if this is * the case and if not, how to respond. Typically, an exception will be * thrown (such as {@link IllegalMonitorStateException}) and the * implementation must document that fact. * {@property.close} * * {@description.open} * <p>An implementation can favor responding to an interrupt over normal * method return in response to a signal. In that case the implementation * must ensure that the signal is redirected to another waiting thread, if * there is one. * {@description.close} * * @throws InterruptedException if the current thread is interrupted * (and interruption of thread suspension is supported) */ void await() throws InterruptedException; /** {@collect.stats} * {@description.open} * Causes the current thread to wait until it is signalled. * * <p>The lock associated with this condition is atomically * released and the current thread becomes disabled for thread scheduling * purposes and lies dormant until <em>one</em> of three things happens: * <ul> * <li>Some other thread invokes the {@link #signal} method for this * {@code Condition} and the current thread happens to be chosen as the * thread to be awakened; or * <li>Some other thread invokes the {@link #signalAll} method for this * {@code Condition}; or * <li>A &quot;<em>spurious wakeup</em>&quot; occurs. * </ul> * {@description.close} * * {@property.open internal} * <p>In all cases, before this method can return the current thread must * re-acquire the lock associated with this condition. When the * thread returns it is <em>guaranteed</em> to hold this lock. * {@property.close} * * {@description.open} * <p>If the current thread's interrupted status is set when it enters * this method, or it is {@linkplain Thread#interrupt interrupted} * while waiting, it will continue to wait until signalled. When it finally * returns from this method its interrupted status will still * be set. * * <p><b>Implementation Considerations</b> * {@description.close} * * {@property.open} * <p>The current thread is assumed to hold the lock associated with this * {@code Condition} when this method is called. * It is up to the implementation to determine if this is * the case and if not, how to respond. Typically, an exception will be * thrown (such as {@link IllegalMonitorStateException}) and the * implementation must document that fact. * {@property.close} */ void awaitUninterruptibly(); /** {@collect.stats} * {@description.open} * Causes the current thread to wait until it is signalled or interrupted, * or the specified waiting time elapses. * * <p>The lock associated with this condition is atomically * released and the current thread becomes disabled for thread scheduling * purposes and lies dormant until <em>one</em> of five things happens: * <ul> * <li>Some other thread invokes the {@link #signal} method for this * {@code Condition} and the current thread happens to be chosen as the * thread to be awakened; or * <li>Some other thread invokes the {@link #signalAll} method for this * {@code Condition}; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} the * current thread, and interruption of thread suspension is supported; or * <li>The specified waiting time elapses; or * <li>A &quot;<em>spurious wakeup</em>&quot; occurs. * </ul> * {@description.close} * * {@property.open internal} * <p>In all cases, before this method can return the current thread must * re-acquire the lock associated with this condition. When the * thread returns it is <em>guaranteed</em> to hold this lock. * {@property.close} * * {@description.open} * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * and interruption of thread suspension is supported, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. It is not specified, in the first * case, whether or not the test for interruption occurs before the lock * is released. * * <p>The method returns an estimate of the number of nanoseconds * remaining to wait given the supplied {@code nanosTimeout} * value upon return, or a value less than or equal to zero if it * timed out. This value can be used to determine whether and how * long to re-wait in cases where the wait returns but an awaited * condition still does not hold. Typical uses of this method take * the following form: * * <pre> * synchronized boolean aMethod(long timeout, TimeUnit unit) { * long nanosTimeout = unit.toNanos(timeout); * while (!conditionBeingWaitedFor) { * if (nanosTimeout &gt; 0) * nanosTimeout = theCondition.awaitNanos(nanosTimeout); * else * return false; * } * // ... * } * </pre> * * <p> Design note: This method requires a nanosecond argument so * as to avoid truncation errors in reporting remaining times. * Such precision loss would make it difficult for programmers to * ensure that total waiting times are not systematically shorter * than specified when re-waits occur. * * <p><b>Implementation Considerations</b> * {@description.close} * * {@property.open} * <p>The current thread is assumed to hold the lock associated with this * {@code Condition} when this method is called. * It is up to the implementation to determine if this is * the case and if not, how to respond. Typically, an exception will be * thrown (such as {@link IllegalMonitorStateException}) and the * implementation must document that fact. * {@property.close} * * {@description.open} * <p>An implementation can favor responding to an interrupt over normal * method return in response to a signal, or over indicating the elapse * of the specified waiting time. In either case the implementation * must ensure that the signal is redirected to another waiting thread, if * there is one. * {@description.close} * * @param nanosTimeout the maximum time to wait, in nanoseconds * @return an estimate of the {@code nanosTimeout} value minus * the time spent waiting upon return from this method. * A positive value may be used as the argument to a * subsequent call to this method to finish waiting out * the desired time. A value less than or equal to zero * indicates that no time remains. * @throws InterruptedException if the current thread is interrupted * (and interruption of thread suspension is supported) */ long awaitNanos(long nanosTimeout) throws InterruptedException; /** {@collect.stats} * {@description.open} * Causes the current thread to wait until it is signalled or interrupted, * or the specified waiting time elapses. This method is behaviorally * equivalent to:<br> * <pre> * awaitNanos(unit.toNanos(time)) &gt; 0 * </pre> * {@description.close} * @param time the maximum time to wait * @param unit the time unit of the {@code time} argument * @return {@code false} if the waiting time detectably elapsed * before return from the method, else {@code true} * @throws InterruptedException if the current thread is interrupted * (and interruption of thread suspension is supported) */ boolean await(long time, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * Causes the current thread to wait until it is signalled or interrupted, * or the specified deadline elapses. * * <p>The lock associated with this condition is atomically * released and the current thread becomes disabled for thread scheduling * purposes and lies dormant until <em>one</em> of five things happens: * <ul> * <li>Some other thread invokes the {@link #signal} method for this * {@code Condition} and the current thread happens to be chosen as the * thread to be awakened; or * <li>Some other thread invokes the {@link #signalAll} method for this * {@code Condition}; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} the * current thread, and interruption of thread suspension is supported; or * <li>The specified deadline elapses; or * <li>A &quot;<em>spurious wakeup</em>&quot; occurs. * </ul> * {@description.close} * * {@property.open internal} * <p>In all cases, before this method can return the current thread must * re-acquire the lock associated with this condition. When the * thread returns it is <em>guaranteed</em> to hold this lock. * {@property.close} * * {@description.open} * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * and interruption of thread suspension is supported, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. It is not specified, in the first * case, whether or not the test for interruption occurs before the lock * is released. * * * <p>The return value indicates whether the deadline has elapsed, * which can be used as follows: * <pre> * synchronized boolean aMethod(Date deadline) { * boolean stillWaiting = true; * while (!conditionBeingWaitedFor) { * if (stillWaiting) * stillWaiting = theCondition.awaitUntil(deadline); * else * return false; * } * // ... * } * </pre> * * <p><b>Implementation Considerations</b> * {@description.close} * * {@property.open} * <p>The current thread is assumed to hold the lock associated with this * {@code Condition} when this method is called. * It is up to the implementation to determine if this is * the case and if not, how to respond. Typically, an exception will be * thrown (such as {@link IllegalMonitorStateException}) and the * implementation must document that fact. * {@property.close} * * {@description.open} * <p>An implementation can favor responding to an interrupt over normal * method return in response to a signal, or over indicating the passing * of the specified deadline. In either case the implementation * must ensure that the signal is redirected to another waiting thread, if * there is one. * {@description.close} * * @param deadline the absolute time to wait until * @return {@code false} if the deadline has elapsed upon return, else * {@code true} * @throws InterruptedException if the current thread is interrupted * (and interruption of thread suspension is supported) */ boolean awaitUntil(Date deadline) throws InterruptedException; /** {@collect.stats} * {@description.open} * Wakes up one waiting thread. * * <p>If any threads are waiting on this condition then one * is selected for waking up. That thread must then re-acquire the * lock before returning from {@code await}. * {@description.close} */ void signal(); /** {@collect.stats} * {@description.open} * Wakes up all waiting threads. * * <p>If any threads are waiting on this condition then they are * all woken up. Each thread must re-acquire the lock before it can * return from {@code await}. * {@description.close} */ void signalAll(); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.locks; /** {@collect.stats} * {@description.open} * A synchronizer that may be exclusively owned by a thread. This * class provides a basis for creating locks and related synchronizers * that may entail a notion of ownership. The * <tt>AbstractOwnableSynchronizer</tt> class itself does not manage or * use this information. However, subclasses and tools may use * appropriately maintained values to help control and monitor access * and provide diagnostics. * {@description.close} * * @since 1.6 * @author Doug Lea */ public abstract class AbstractOwnableSynchronizer implements java.io.Serializable { /** {@collect.stats} * {@description.open} * Use serial ID even though all fields transient. * {@description.close} */ private static final long serialVersionUID = 3737899427754241961L; /** {@collect.stats} * {@description.open} * Empty constructor for use by subclasses. * {@description.close} */ protected AbstractOwnableSynchronizer() { } /** {@collect.stats} * {@description.open} * The current owner of exclusive mode synchronization. * {@description.close} */ private transient Thread exclusiveOwnerThread; /** {@collect.stats} * {@description.open} * Sets the thread that currently owns exclusive access. A * <tt>null</tt> argument indicates that no thread owns access. * This method does not otherwise impose any synchronization or * <tt>volatile</tt> field accesses. * {@description.close} */ protected final void setExclusiveOwnerThread(Thread t) { exclusiveOwnerThread = t; } /** {@collect.stats} * {@description.open} * Returns the thread last set by * <tt>setExclusiveOwnerThread</tt>, or <tt>null</tt> if never * set. This method does not otherwise impose any synchronization * or <tt>volatile</tt> field accesses. * {@description.close} * @return the owner thread */ protected final Thread getExclusiveOwnerThread() { return exclusiveOwnerThread; } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.locks; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import sun.misc.Unsafe; /** {@collect.stats} * {@description.open} * Provides a framework for implementing blocking locks and related * synchronizers (semaphores, events, etc) that rely on * first-in-first-out (FIFO) wait queues. This class is designed to * be a useful basis for most kinds of synchronizers that rely on a * single atomic <tt>int</tt> value to represent state. Subclasses * must define the protected methods that change this state, and which * define what that state means in terms of this object being acquired * or released. Given these, the other methods in this class carry * out all queuing and blocking mechanics. Subclasses can maintain * other state fields, but only the atomically updated <tt>int</tt> * value manipulated using methods {@link #getState}, {@link * #setState} and {@link #compareAndSetState} is tracked with respect * to synchronization. * * <p>Subclasses should be defined as non-public internal helper * classes that are used to implement the synchronization properties * of their enclosing class. Class * <tt>AbstractQueuedSynchronizer</tt> does not implement any * synchronization interface. Instead it defines methods such as * {@link #acquireInterruptibly} that can be invoked as * appropriate by concrete locks and related synchronizers to * implement their public methods. * * <p>This class supports either or both a default <em>exclusive</em> * mode and a <em>shared</em> mode. When acquired in exclusive mode, * attempted acquires by other threads cannot succeed. Shared mode * acquires by multiple threads may (but need not) succeed. This class * does not &quot;understand&quot; these differences except in the * mechanical sense that when a shared mode acquire succeeds, the next * waiting thread (if one exists) must also determine whether it can * acquire as well. Threads waiting in the different modes share the * same FIFO queue. Usually, implementation subclasses support only * one of these modes, but both can come into play for example in a * {@link ReadWriteLock}. Subclasses that support only exclusive or * only shared modes need not define the methods supporting the unused mode. * * <p>This class defines a nested {@link ConditionObject} class that * can be used as a {@link Condition} implementation by subclasses * supporting exclusive mode for which method {@link * #isHeldExclusively} reports whether synchronization is exclusively * held with respect to the current thread, method {@link #release} * invoked with the current {@link #getState} value fully releases * this object, and {@link #acquire}, given this saved state value, * eventually restores this object to its previous acquired state. No * <tt>AbstractQueuedSynchronizer</tt> method otherwise creates such a * condition, so if this constraint cannot be met, do not use it. The * behavior of {@link ConditionObject} depends of course on the * semantics of its synchronizer implementation. * * <p>This class provides inspection, instrumentation, and monitoring * methods for the internal queue, as well as similar methods for * condition objects. These can be exported as desired into classes * using an <tt>AbstractQueuedSynchronizer</tt> for their * synchronization mechanics. * * <p>Serialization of this class stores only the underlying atomic * integer maintaining state, so deserialized objects have empty * thread queues. Typical subclasses requiring serializability will * define a <tt>readObject</tt> method that restores this to a known * initial state upon deserialization. * * <h3>Usage</h3> * * <p>To use this class as the basis of a synchronizer, redefine the * following methods, as applicable, by inspecting and/or modifying * the synchronization state using {@link #getState}, {@link * #setState} and/or {@link #compareAndSetState}: * * <ul> * <li> {@link #tryAcquire} * <li> {@link #tryRelease} * <li> {@link #tryAcquireShared} * <li> {@link #tryReleaseShared} * <li> {@link #isHeldExclusively} *</ul> * * Each of these methods by default throws {@link * UnsupportedOperationException}. * {@description.close} * {@property.open internal} * Implementations of these methods * must be internally thread-safe, and should in general be short and * not block. * {@property.close} * {@description.open} * Defining these methods is the <em>only</em> supported * means of using this class. All other methods are declared * <tt>final</tt> because they cannot be independently varied. * * <p>You may also find the inherited methods from {@link * AbstractOwnableSynchronizer} useful to keep track of the thread * owning an exclusive synchronizer. You are encouraged to use them * -- this enables monitoring and diagnostic tools to assist users in * determining which threads hold locks. * * <p>Even though this class is based on an internal FIFO queue, it * does not automatically enforce FIFO acquisition policies. The core * of exclusive synchronization takes the form: * * <pre> * Acquire: * while (!tryAcquire(arg)) { * <em>enqueue thread if it is not already queued</em>; * <em>possibly block current thread</em>; * } * * Release: * if (tryRelease(arg)) * <em>unblock the first queued thread</em>; * </pre> * * (Shared mode is similar but may involve cascading signals.) * * <p><a name="barging">Because checks in acquire are invoked before enqueuing, a newly * acquiring thread may <em>barge</em> ahead of others that are * blocked and queued. However, you can, if desired, define * <tt>tryAcquire</tt> and/or <tt>tryAcquireShared</tt> to disable * barging by internally invoking one or more of the inspection * methods. In particular, a strict FIFO lock can define * <tt>tryAcquire</tt> to immediately return <tt>false</tt> if {@link * #getFirstQueuedThread} does not return the current thread. A * normally preferable non-strict fair version can immediately return * <tt>false</tt> only if {@link #hasQueuedThreads} returns * <tt>true</tt> and <tt>getFirstQueuedThread</tt> is not the current * thread; or equivalently, that <tt>getFirstQueuedThread</tt> is both * non-null and not the current thread. Further variations are * possible. * * <p>Throughput and scalability are generally highest for the * default barging (also known as <em>greedy</em>, * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy. * While this is not guaranteed to be fair or starvation-free, earlier * queued threads are allowed to recontend before later queued * threads, and each recontention has an unbiased chance to succeed * against incoming threads. Also, while acquires do not * &quot;spin&quot; in the usual sense, they may perform multiple * invocations of <tt>tryAcquire</tt> interspersed with other * computations before blocking. This gives most of the benefits of * spins when exclusive synchronization is only briefly held, without * most of the liabilities when it isn't. If so desired, you can * augment this by preceding calls to acquire methods with * "fast-path" checks, possibly prechecking {@link #hasContended} * and/or {@link #hasQueuedThreads} to only do so if the synchronizer * is likely not to be contended. * * <p>This class provides an efficient and scalable basis for * synchronization in part by specializing its range of use to * synchronizers that can rely on <tt>int</tt> state, acquire, and * release parameters, and an internal FIFO wait queue. When this does * not suffice, you can build synchronizers from a lower level using * {@link java.util.concurrent.atomic atomic} classes, your own custom * {@link java.util.Queue} classes, and {@link LockSupport} blocking * support. * * <h3>Usage Examples</h3> * * <p>Here is a non-reentrant mutual exclusion lock class that uses * the value zero to represent the unlocked state, and one to * represent the locked state. While a non-reentrant lock * does not strictly require recording of the current owner * thread, this class does so anyway to make usage easier to monitor. * It also supports conditions and exposes * one of the instrumentation methods: * * <pre> * class Mutex implements Lock, java.io.Serializable { * * // Our internal helper class * private static class Sync extends AbstractQueuedSynchronizer { * // Report whether in locked state * protected boolean isHeldExclusively() { * return getState() == 1; * } * * // Acquire the lock if state is zero * public boolean tryAcquire(int acquires) { * assert acquires == 1; // Otherwise unused * if (compareAndSetState(0, 1)) { * setExclusiveOwnerThread(Thread.currentThread()); * return true; * } * return false; * } * * // Release the lock by setting state to zero * protected boolean tryRelease(int releases) { * assert releases == 1; // Otherwise unused * if (getState() == 0) throw new IllegalMonitorStateException(); * setExclusiveOwnerThread(null); * setState(0); * return true; * } * * // Provide a Condition * Condition newCondition() { return new ConditionObject(); } * * // Deserialize properly * private void readObject(ObjectInputStream s) * throws IOException, ClassNotFoundException { * s.defaultReadObject(); * setState(0); // reset to unlocked state * } * } * * // The sync object does all the hard work. We just forward to it. * private final Sync sync = new Sync(); * * public void lock() { sync.acquire(1); } * public boolean tryLock() { return sync.tryAcquire(1); } * public void unlock() { sync.release(1); } * public Condition newCondition() { return sync.newCondition(); } * public boolean isLocked() { return sync.isHeldExclusively(); } * public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } * public void lockInterruptibly() throws InterruptedException { * sync.acquireInterruptibly(1); * } * public boolean tryLock(long timeout, TimeUnit unit) * throws InterruptedException { * return sync.tryAcquireNanos(1, unit.toNanos(timeout)); * } * } * </pre> * * <p>Here is a latch class that is like a {@link CountDownLatch} * except that it only requires a single <tt>signal</tt> to * fire. Because a latch is non-exclusive, it uses the <tt>shared</tt> * acquire and release methods. * * <pre> * class BooleanLatch { * * private static class Sync extends AbstractQueuedSynchronizer { * boolean isSignalled() { return getState() != 0; } * * protected int tryAcquireShared(int ignore) { * return isSignalled()? 1 : -1; * } * * protected boolean tryReleaseShared(int ignore) { * setState(1); * return true; * } * } * * private final Sync sync = new Sync(); * public boolean isSignalled() { return sync.isSignalled(); } * public void signal() { sync.releaseShared(1); } * public void await() throws InterruptedException { * sync.acquireSharedInterruptibly(1); * } * } * </pre> * {@description.close} * * @since 1.5 * @author Doug Lea */ public abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer implements java.io.Serializable { private static final long serialVersionUID = 7373984972572414691L; /** {@collect.stats} * {@description.open} * Creates a new <tt>AbstractQueuedSynchronizer</tt> instance * with initial synchronization state of zero. * {@description.close} */ protected AbstractQueuedSynchronizer() { } /** {@collect.stats} * {@description.open} * Wait queue node class. * * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and * Hagersten) lock queue. CLH locks are normally used for * spinlocks. We instead use them for blocking synchronizers, but * use the same basic tactic of holding some of the control * information about a thread in the predecessor of its node. A * "status" field in each node keeps track of whether a thread * should block. A node is signalled when its predecessor * releases. Each node of the queue otherwise serves as a * specific-notification-style monitor holding a single waiting * thread. The status field does NOT control whether threads are * granted locks etc though. A thread may try to acquire if it is * first in the queue. But being first does not guarantee success; * it only gives the right to contend. So the currently released * contender thread may need to rewait. * * <p>To enqueue into a CLH lock, you atomically splice it in as new * tail. To dequeue, you just set the head field. * <pre> * +------+ prev +-----+ +-----+ * head | | <---- | | <---- | | tail * +------+ +-----+ +-----+ * </pre> * * <p>Insertion into a CLH queue requires only a single atomic * operation on "tail", so there is a simple atomic point of * demarcation from unqueued to queued. Similarly, dequeing * involves only updating the "head". However, it takes a bit * more work for nodes to determine who their successors are, * in part to deal with possible cancellation due to timeouts * and interrupts. * * <p>The "prev" links (not used in original CLH locks), are mainly * needed to handle cancellation. If a node is cancelled, its * successor is (normally) relinked to a non-cancelled * predecessor. For explanation of similar mechanics in the case * of spin locks, see the papers by Scott and Scherer at * http://www.cs.rochester.edu/u/scott/synchronization/ * * <p>We also use "next" links to implement blocking mechanics. * The thread id for each node is kept in its own node, so a * predecessor signals the next node to wake up by traversing * next link to determine which thread it is. Determination of * successor must avoid races with newly queued nodes to set * the "next" fields of their predecessors. This is solved * when necessary by checking backwards from the atomically * updated "tail" when a node's successor appears to be null. * (Or, said differently, the next-links are an optimization * so that we don't usually need a backward scan.) * * <p>Cancellation introduces some conservatism to the basic * algorithms. Since we must poll for cancellation of other * nodes, we can miss noticing whether a cancelled node is * ahead or behind us. This is dealt with by always unparking * successors upon cancellation, allowing them to stabilize on * a new predecessor, unless we can identify an uncancelled * predecessor who will carry this responsibility. * * <p>CLH queues need a dummy header node to get started. But * we don't create them on construction, because it would be wasted * effort if there is never contention. Instead, the node * is constructed and head and tail pointers are set upon first * contention. * * <p>Threads waiting on Conditions use the same nodes, but * use an additional link. Conditions only need to link nodes * in simple (non-concurrent) linked queues because they are * only accessed when exclusively held. Upon await, a node is * inserted into a condition queue. Upon signal, the node is * transferred to the main queue. A special value of status * field is used to mark which queue a node is on. * * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill * Scherer and Michael Scott, along with members of JSR-166 * expert group, for helpful ideas, discussions, and critiques * on the design of this class. * {@description.close} */ static final class Node { /** {@collect.stats} * {@description.open} * Marker to indicate a node is waiting in shared mode * {@description.close} */ static final Node SHARED = new Node(); /** {@collect.stats} * {@description.open} * Marker to indicate a node is waiting in exclusive mode * {@description.close} */ static final Node EXCLUSIVE = null; /** {@collect.stats} * {@description.open} * waitStatus value to indicate thread has cancelled * {@description.close} */ static final int CANCELLED = 1; /** {@collect.stats} * {@description.open} * waitStatus value to indicate successor's thread needs unparking * {@description.close} */ static final int SIGNAL = -1; /** {@collect.stats} * {@description.open} * waitStatus value to indicate thread is waiting on condition * {@description.close} */ static final int CONDITION = -2; /** {@collect.stats} * {@description.open} * waitStatus value to indicate the next acquireShared should * unconditionally propagate * {@description.close} */ static final int PROPAGATE = -3; /** {@collect.stats} * {@description.open} * Status field, taking on only the values: * SIGNAL: The successor of this node is (or will soon be) * blocked (via park), so the current node must * unpark its successor when it releases or * cancels. To avoid races, acquire methods must * first indicate they need a signal, * then retry the atomic acquire, and then, * on failure, block. * CANCELLED: This node is cancelled due to timeout or interrupt. * Nodes never leave this state. In particular, * a thread with cancelled node never again blocks. * CONDITION: This node is currently on a condition queue. * It will not be used as a sync queue node * until transferred, at which time the status * will be set to 0. (Use of this value here has * nothing to do with the other uses of the * field, but simplifies mechanics.) * PROPAGATE: A releaseShared should be propagated to other * nodes. This is set (for head node only) in * doReleaseShared to ensure propagation * continues, even if other operations have * since intervened. * 0: None of the above * * The values are arranged numerically to simplify use. * Non-negative values mean that a node doesn't need to * signal. So, most code doesn't need to check for particular * values, just for sign. * * The field is initialized to 0 for normal sync nodes, and * CONDITION for condition nodes. It is modified using CAS * (or when possible, unconditional volatile writes). * {@description.close} */ volatile int waitStatus; /** {@collect.stats} * {@description.open} * Link to predecessor node that current node/thread relies on * for checking waitStatus. Assigned during enqueing, and nulled * out (for sake of GC) only upon dequeuing. Also, upon * cancellation of a predecessor, we short-circuit while * finding a non-cancelled one, which will always exist * because the head node is never cancelled: A node becomes * head only as a result of successful acquire. A * cancelled thread never succeeds in acquiring, and a thread only * cancels itself, not any other node. * {@description.close} */ volatile Node prev; /** {@collect.stats} * {@description.open} * Link to the successor node that the current node/thread * unparks upon release. Assigned during enqueuing, adjusted * when bypassing cancelled predecessors, and nulled out (for * sake of GC) when dequeued. The enq operation does not * assign next field of a predecessor until after attachment, * so seeing a null next field does not necessarily mean that * node is at end of queue. However, if a next field appears * to be null, we can scan prev's from the tail to * double-check. The next field of cancelled nodes is set to * point to the node itself instead of null, to make life * easier for isOnSyncQueue. * {@description.close} */ volatile Node next; /** {@collect.stats} * {@description.open} * The thread that enqueued this node. Initialized on * construction and nulled out after use. * {@description.close} */ volatile Thread thread; /** {@collect.stats} * {@description.open} * Link to next node waiting on condition, or the special * value SHARED. Because condition queues are accessed only * when holding in exclusive mode, we just need a simple * linked queue to hold nodes while they are waiting on * conditions. They are then transferred to the queue to * re-acquire. And because conditions can only be exclusive, * we save a field by using special value to indicate shared * mode. * {@description.close} */ Node nextWaiter; /** {@collect.stats} * {@description.open} * Returns true if node is waiting in shared mode * {@description.close} */ final boolean isShared() { return nextWaiter == SHARED; } /** {@collect.stats} * {@description.open} * Returns previous node, or throws NullPointerException if null. * Use when predecessor cannot be null. The null check could * be elided, but is present to help the VM. * {@description.close} * * @return the predecessor of this node */ final Node predecessor() throws NullPointerException { Node p = prev; if (p == null) throw new NullPointerException(); else return p; } Node() { // Used to establish initial head or SHARED marker } Node(Thread thread, Node mode) { // Used by addWaiter this.nextWaiter = mode; this.thread = thread; } Node(Thread thread, int waitStatus) { // Used by Condition this.waitStatus = waitStatus; this.thread = thread; } } /** {@collect.stats} * {@description.open} * Head of the wait queue, lazily initialized. Except for * initialization, it is modified only via method setHead. Note: * If head exists, its waitStatus is guaranteed not to be * CANCELLED. * {@description.close} */ private transient volatile Node head; /** {@collect.stats} * {@description.open} * Tail of the wait queue, lazily initialized. Modified only via * method enq to add new wait node. * {@description.close} */ private transient volatile Node tail; /** {@collect.stats} * {@description.open} * The synchronization state. * {@description.close} */ private volatile int state; /** {@collect.stats} * {@description.open} * Returns the current value of synchronization state. * This operation has memory semantics of a <tt>volatile</tt> read. * {@description.close} * @return current state value */ protected final int getState() { return state; } /** {@collect.stats} * {@description.open} * Sets the value of synchronization state. * This operation has memory semantics of a <tt>volatile</tt> write. * {@description.close} * @param newState the new state value */ protected final void setState(int newState) { state = newState; } /** {@collect.stats} * {@description.open} * Atomically sets synchronization state to the given updated * value if the current state value equals the expected value. * This operation has memory semantics of a <tt>volatile</tt> read * and write. * {@description.close} * * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that the actual * value was not equal to the expected value. */ protected final boolean compareAndSetState(int expect, int update) { // See below for intrinsics setup to support this return unsafe.compareAndSwapInt(this, stateOffset, expect, update); } // Queuing utilities /** {@collect.stats} * {@description.open} * The number of nanoseconds for which it is faster to spin * rather than to use timed park. A rough estimate suffices * to improve responsiveness with very short timeouts. * {@description.close} */ static final long spinForTimeoutThreshold = 1000L; /** {@collect.stats} * {@description.open} * Inserts node into queue, initializing if necessary. See picture above. * {@description.close} * @param node the node to insert * @return node's predecessor */ private Node enq(final Node node) { for (;;) { Node t = tail; if (t == null) { // Must initialize if (compareAndSetHead(new Node())) tail = head; } else { node.prev = t; if (compareAndSetTail(t, node)) { t.next = node; return t; } } } } /** {@collect.stats} * {@description.open} * Creates and enqueues node for current thread and given mode. * {@description.close} * * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared * @return the new node */ private Node addWaiter(Node mode) { Node node = new Node(Thread.currentThread(), mode); // Try the fast path of enq; backup to full enq on failure Node pred = tail; if (pred != null) { node.prev = pred; if (compareAndSetTail(pred, node)) { pred.next = node; return node; } } enq(node); return node; } /** {@collect.stats} * {@description.open} * Sets head of queue to be node, thus dequeuing. Called only by * acquire methods. Also nulls out unused fields for sake of GC * and to suppress unnecessary signals and traversals. * {@description.close} * * @param node the node */ private void setHead(Node node) { head = node; node.thread = null; node.prev = null; } /** {@collect.stats} * {@description.open} * Wakes up node's successor, if one exists. * {@description.close} * * @param node the node */ private void unparkSuccessor(Node node) { /* * If status is negative (i.e., possibly needing signal) try * to clear in anticipation of signalling. It is OK if this * fails or if status is changed by waiting thread. */ int ws = node.waitStatus; if (ws < 0) compareAndSetWaitStatus(node, ws, 0); /* * Thread to unpark is held in successor, which is normally * just the next node. But if cancelled or apparently null, * traverse backwards from tail to find the actual * non-cancelled successor. */ Node s = node.next; if (s == null || s.waitStatus > 0) { s = null; for (Node t = tail; t != null && t != node; t = t.prev) if (t.waitStatus <= 0) s = t; } if (s != null) LockSupport.unpark(s.thread); } /** {@collect.stats} * {@description.open} * Release action for shared mode -- signal successor and ensure * propagation. (Note: For exclusive mode, release just amounts * to calling unparkSuccessor of head if it needs signal.) * {@description.close} */ private void doReleaseShared() { /* * Ensure that a release propagates, even if there are other * in-progress acquires/releases. This proceeds in the usual * way of trying to unparkSuccessor of head if it needs * signal. But if it does not, status is set to PROPAGATE to * ensure that upon release, propagation continues. * Additionally, we must loop in case a new node is added * while we are doing this. Also, unlike other uses of * unparkSuccessor, we need to know if CAS to reset status * fails, if so rechecking. */ for (;;) { Node h = head; if (h != null && h != tail) { int ws = h.waitStatus; if (ws == Node.SIGNAL) { if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) continue; // loop to recheck cases unparkSuccessor(h); } else if (ws == 0 && !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) continue; // loop on failed CAS } if (h == head) // loop if head changed break; } } /** {@collect.stats} * {@description.open} * Sets head of queue, and checks if successor may be waiting * in shared mode, if so propagating if either propagate > 0 or * PROPAGATE status was set. * {@description.close} * * @param node the node * @param propagate the return value from a tryAcquireShared */ private void setHeadAndPropagate(Node node, int propagate) { Node h = head; // Record old head for check below setHead(node); /* * Try to signal next queued node if: * Propagation was indicated by caller, * or was recorded (as h.waitStatus) by a previous operation * (note: this uses sign-check of waitStatus because * PROPAGATE status may transition to SIGNAL.) * and * The next node is waiting in shared mode, * or we don't know, because it appears null * * The conservatism in both of these checks may cause * unnecessary wake-ups, but only when there are multiple * racing acquires/releases, so most need signals now or soon * anyway. */ if (propagate > 0 || h == null || h.waitStatus < 0) { Node s = node.next; if (s == null || s.isShared()) doReleaseShared(); } } // Utilities for various versions of acquire /** {@collect.stats} * {@description.open} * Cancels an ongoing attempt to acquire. * {@description.close} * * @param node the node */ private void cancelAcquire(Node node) { // Ignore if node doesn't exist if (node == null) return; node.thread = null; // Skip cancelled predecessors Node pred = node.prev; while (pred.waitStatus > 0) node.prev = pred = pred.prev; // predNext is the apparent node to unsplice. CASes below will // fail if not, in which case, we lost race vs another cancel // or signal, so no further action is necessary. Node predNext = pred.next; // Can use unconditional write instead of CAS here. // After this atomic step, other Nodes can skip past us. // Before, we are free of interference from other threads. node.waitStatus = Node.CANCELLED; // If we are the tail, remove ourselves. if (node == tail && compareAndSetTail(node, pred)) { compareAndSetNext(pred, predNext, null); } else { // If successor needs signal, try to set pred's next-link // so it will get one. Otherwise wake it up to propagate. int ws; if (pred != head && ((ws = pred.waitStatus) == Node.SIGNAL || (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) && pred.thread != null) { Node next = node.next; if (next != null && next.waitStatus <= 0) compareAndSetNext(pred, predNext, next); } else { unparkSuccessor(node); } node.next = node; // help GC } } /** {@collect.stats} * {@description.open} * Checks and updates status for a node that failed to acquire. * Returns true if thread should block. This is the main signal * control in all acquire loops. Requires that pred == node.prev * {@description.close} * * @param pred node's predecessor holding status * @param node the node * @return {@code true} if thread should block */ private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { int ws = pred.waitStatus; if (ws == Node.SIGNAL) /* * This node has already set status asking a release * to signal it, so it can safely park. */ return true; if (ws > 0) { /* * Predecessor was cancelled. Skip over predecessors and * indicate retry. */ do { node.prev = pred = pred.prev; } while (pred.waitStatus > 0); pred.next = node; } else { /* * waitStatus must be 0 or PROPAGATE. Indicate that we * need a signal, but don't park yet. Caller will need to * retry to make sure it cannot acquire before parking. */ compareAndSetWaitStatus(pred, ws, Node.SIGNAL); } return false; } /** {@collect.stats} * {@description.open} * Convenience method to interrupt current thread. * {@description.close} */ private static void selfInterrupt() { Thread.currentThread().interrupt(); } /** {@collect.stats} * {@description.open} * Convenience method to park and then check if interrupted * {@description.close} * * @return {@code true} if interrupted */ private final boolean parkAndCheckInterrupt() { LockSupport.park(this); return Thread.interrupted(); } /* * Various flavors of acquire, varying in exclusive/shared and * control modes. Each is mostly the same, but annoyingly * different. Only a little bit of factoring is possible due to * interactions of exception mechanics (including ensuring that we * cancel if tryAcquire throws exception) and other control, at * least not without hurting performance too much. */ /** {@collect.stats} * {@description.open} * Acquires in exclusive uninterruptible mode for thread already in * queue. Used by condition wait methods as well as acquire. * {@description.close} * * @param node the node * @param arg the acquire argument * @return {@code true} if interrupted while waiting */ final boolean acquireQueued(final Node node, int arg) { boolean failed = true; try { boolean interrupted = false; for (;;) { final Node p = node.predecessor(); if (p == head && tryAcquire(arg)) { setHead(node); p.next = null; // help GC failed = false; return interrupted; } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true; } } finally { if (failed) cancelAcquire(node); } } /** {@collect.stats} * {@description.open} * Acquires in exclusive interruptible mode. * {@description.close} * @param arg the acquire argument */ private void doAcquireInterruptibly(int arg) throws InterruptedException { final Node node = addWaiter(Node.EXCLUSIVE); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head && tryAcquire(arg)) { setHead(node); p.next = null; // help GC failed = false; return; } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } /** {@collect.stats} * {@description.open} * Acquires in exclusive timed mode. * {@description.close} * * @param arg the acquire argument * @param nanosTimeout max wait time * @return {@code true} if acquired */ private boolean doAcquireNanos(int arg, long nanosTimeout) throws InterruptedException { long lastTime = System.nanoTime(); final Node node = addWaiter(Node.EXCLUSIVE); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head && tryAcquire(arg)) { setHead(node); p.next = null; // help GC failed = false; return true; } if (nanosTimeout <= 0) return false; if (shouldParkAfterFailedAcquire(p, node) && nanosTimeout > spinForTimeoutThreshold) LockSupport.parkNanos(this, nanosTimeout); long now = System.nanoTime(); nanosTimeout -= now - lastTime; lastTime = now; if (Thread.interrupted()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } /** {@collect.stats} * {@description.open} * Acquires in shared uninterruptible mode. * {@description.close} * @param arg the acquire argument */ private void doAcquireShared(int arg) { final Node node = addWaiter(Node.SHARED); boolean failed = true; try { boolean interrupted = false; for (;;) { final Node p = node.predecessor(); if (p == head) { int r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC if (interrupted) selfInterrupt(); failed = false; return; } } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true; } } finally { if (failed) cancelAcquire(node); } } /** {@collect.stats} * {@description.open} * Acquires in shared interruptible mode. * {@description.close} * @param arg the acquire argument */ private void doAcquireSharedInterruptibly(int arg) throws InterruptedException { final Node node = addWaiter(Node.SHARED); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head) { int r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return; } } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } /** {@collect.stats} * {@description.open} * Acquires in shared timed mode. * {@description.close} * * @param arg the acquire argument * @param nanosTimeout max wait time * @return {@code true} if acquired */ private boolean doAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException { long lastTime = System.nanoTime(); final Node node = addWaiter(Node.SHARED); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head) { int r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return true; } } if (nanosTimeout <= 0) return false; if (shouldParkAfterFailedAcquire(p, node) && nanosTimeout > spinForTimeoutThreshold) LockSupport.parkNanos(this, nanosTimeout); long now = System.nanoTime(); nanosTimeout -= now - lastTime; lastTime = now; if (Thread.interrupted()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } // Main exported methods /** {@collect.stats} * {@description.open} * Attempts to acquire in exclusive mode. This method should query * if the state of the object permits it to be acquired in the * exclusive mode, and if so to acquire it. * * <p>This method is always invoked by the thread performing * acquire. If this method reports failure, the acquire method * may queue the thread, if it is not already queued, until it is * signalled by a release from some other thread. This can be used * to implement method {@link Lock#tryLock()}. * * <p>The default * implementation throws {@link UnsupportedOperationException}. * {@description.close} * * @param arg the acquire argument. This value is always the one * passed to an acquire method, or is the value saved on entry * to a condition wait. The value is otherwise uninterpreted * and can represent anything you like. * @return {@code true} if successful. Upon success, this object has * been acquired. * @throws IllegalMonitorStateException if acquiring would place this * synchronizer in an illegal state. This exception must be * thrown in a consistent fashion for synchronization to work * correctly. * @throws UnsupportedOperationException if exclusive mode is not supported */ protected boolean tryAcquire(int arg) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Attempts to set the state to reflect a release in exclusive * mode. * * <p>This method is always invoked by the thread performing release. * * <p>The default implementation throws * {@link UnsupportedOperationException}. * {@description.close} * * @param arg the release argument. This value is always the one * passed to a release method, or the current state value upon * entry to a condition wait. The value is otherwise * uninterpreted and can represent anything you like. * @return {@code true} if this object is now in a fully released * state, so that any waiting threads may attempt to acquire; * and {@code false} otherwise. * @throws IllegalMonitorStateException if releasing would place this * synchronizer in an illegal state. This exception must be * thrown in a consistent fashion for synchronization to work * correctly. * @throws UnsupportedOperationException if exclusive mode is not supported */ protected boolean tryRelease(int arg) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Attempts to acquire in shared mode. This method should query if * the state of the object permits it to be acquired in the shared * mode, and if so to acquire it. * * <p>This method is always invoked by the thread performing * acquire. If this method reports failure, the acquire method * may queue the thread, if it is not already queued, until it is * signalled by a release from some other thread. * * <p>The default implementation throws {@link * UnsupportedOperationException}. * {@description.close} * * @param arg the acquire argument. This value is always the one * passed to an acquire method, or is the value saved on entry * to a condition wait. The value is otherwise uninterpreted * and can represent anything you like. * @return a negative value on failure; zero if acquisition in shared * mode succeeded but no subsequent shared-mode acquire can * succeed; and a positive value if acquisition in shared * mode succeeded and subsequent shared-mode acquires might * also succeed, in which case a subsequent waiting thread * must check availability. (Support for three different * return values enables this method to be used in contexts * where acquires only sometimes act exclusively.) Upon * success, this object has been acquired. * @throws IllegalMonitorStateException if acquiring would place this * synchronizer in an illegal state. This exception must be * thrown in a consistent fashion for synchronization to work * correctly. * @throws UnsupportedOperationException if shared mode is not supported */ protected int tryAcquireShared(int arg) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Attempts to set the state to reflect a release in shared mode. * * <p>This method is always invoked by the thread performing release. * * <p>The default implementation throws * {@link UnsupportedOperationException}. * {@description.close} * * @param arg the release argument. This value is always the one * passed to a release method, or the current state value upon * entry to a condition wait. The value is otherwise * uninterpreted and can represent anything you like. * @return {@code true} if this release of shared mode may permit a * waiting acquire (shared or exclusive) to succeed; and * {@code false} otherwise * @throws IllegalMonitorStateException if releasing would place this * synchronizer in an illegal state. This exception must be * thrown in a consistent fashion for synchronization to work * correctly. * @throws UnsupportedOperationException if shared mode is not supported */ protected boolean tryReleaseShared(int arg) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Returns {@code true} if synchronization is held exclusively with * respect to the current (calling) thread. This method is invoked * upon each call to a non-waiting {@link ConditionObject} method. * (Waiting methods instead invoke {@link #release}.) * * <p>The default implementation throws {@link * UnsupportedOperationException}. This method is invoked * internally only within {@link ConditionObject} methods, so need * not be defined if conditions are not used. * {@description.close} * * @return {@code true} if synchronization is held exclusively; * {@code false} otherwise * @throws UnsupportedOperationException if conditions are not supported */ protected boolean isHeldExclusively() { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Acquires in exclusive mode, ignoring interrupts. Implemented * by invoking at least once {@link #tryAcquire}, * returning on success. Otherwise the thread is queued, possibly * repeatedly blocking and unblocking, invoking {@link * #tryAcquire} until success. This method can be used * to implement method {@link Lock#lock}. * {@description.close} * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquire} but is otherwise uninterpreted and * can represent anything you like. */ public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } /** {@collect.stats} * {@description.open} * Acquires in exclusive mode, aborting if interrupted. * Implemented by first checking interrupt status, then invoking * at least once {@link #tryAcquire}, returning on * success. Otherwise the thread is queued, possibly repeatedly * blocking and unblocking, invoking {@link #tryAcquire} * until success or the thread is interrupted. This method can be * used to implement method {@link Lock#lockInterruptibly}. * {@description.close} * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquire} but is otherwise uninterpreted and * can represent anything you like. * @throws InterruptedException if the current thread is interrupted */ public final void acquireInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (!tryAcquire(arg)) doAcquireInterruptibly(arg); } /** {@collect.stats} * {@description.open} * Attempts to acquire in exclusive mode, aborting if interrupted, * and failing if the given timeout elapses. Implemented by first * checking interrupt status, then invoking at least once {@link * #tryAcquire}, returning on success. Otherwise, the thread is * queued, possibly repeatedly blocking and unblocking, invoking * {@link #tryAcquire} until success or the thread is interrupted * or the timeout elapses. This method can be used to implement * method {@link Lock#tryLock(long, TimeUnit)}. * {@description.close} * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquire} but is otherwise uninterpreted and * can represent anything you like. * @param nanosTimeout the maximum number of nanoseconds to wait * @return {@code true} if acquired; {@code false} if timed out * @throws InterruptedException if the current thread is interrupted */ public final boolean tryAcquireNanos(int arg, long nanosTimeout) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); return tryAcquire(arg) || doAcquireNanos(arg, nanosTimeout); } /** {@collect.stats} * {@description.open} * Releases in exclusive mode. Implemented by unblocking one or * more threads if {@link #tryRelease} returns true. * This method can be used to implement method {@link Lock#unlock}. * {@description.close} * * @param arg the release argument. This value is conveyed to * {@link #tryRelease} but is otherwise uninterpreted and * can represent anything you like. * @return the value returned from {@link #tryRelease} */ public final boolean release(int arg) { if (tryRelease(arg)) { Node h = head; if (h != null && h.waitStatus != 0) unparkSuccessor(h); return true; } return false; } /** {@collect.stats} * {@description.open} * Acquires in shared mode, ignoring interrupts. Implemented by * first invoking at least once {@link #tryAcquireShared}, * returning on success. Otherwise the thread is queued, possibly * repeatedly blocking and unblocking, invoking {@link * #tryAcquireShared} until success. * {@description.close} * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquireShared} but is otherwise uninterpreted * and can represent anything you like. */ public final void acquireShared(int arg) { if (tryAcquireShared(arg) < 0) doAcquireShared(arg); } /** {@collect.stats} * {@description.open} * Acquires in shared mode, aborting if interrupted. Implemented * by first checking interrupt status, then invoking at least once * {@link #tryAcquireShared}, returning on success. Otherwise the * thread is queued, possibly repeatedly blocking and unblocking, * invoking {@link #tryAcquireShared} until success or the thread * is interrupted. * {@description.close} * @param arg the acquire argument * This value is conveyed to {@link #tryAcquireShared} but is * otherwise uninterpreted and can represent anything * you like. * @throws InterruptedException if the current thread is interrupted */ public final void acquireSharedInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (tryAcquireShared(arg) < 0) doAcquireSharedInterruptibly(arg); } /** {@collect.stats} * {@description.open} * Attempts to acquire in shared mode, aborting if interrupted, and * failing if the given timeout elapses. Implemented by first * checking interrupt status, then invoking at least once {@link * #tryAcquireShared}, returning on success. Otherwise, the * thread is queued, possibly repeatedly blocking and unblocking, * invoking {@link #tryAcquireShared} until success or the thread * is interrupted or the timeout elapses. * {@description.close} * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquireShared} but is otherwise uninterpreted * and can represent anything you like. * @param nanosTimeout the maximum number of nanoseconds to wait * @return {@code true} if acquired; {@code false} if timed out * @throws InterruptedException if the current thread is interrupted */ public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); return tryAcquireShared(arg) >= 0 || doAcquireSharedNanos(arg, nanosTimeout); } /** {@collect.stats} * {@description.open} * Releases in shared mode. Implemented by unblocking one or more * threads if {@link #tryReleaseShared} returns true. * {@description.close} * * @param arg the release argument. This value is conveyed to * {@link #tryReleaseShared} but is otherwise uninterpreted * and can represent anything you like. * @return the value returned from {@link #tryReleaseShared} */ public final boolean releaseShared(int arg) { if (tryReleaseShared(arg)) { doReleaseShared(); return true; } return false; } // Queue inspection methods /** {@collect.stats} * {@description.open} * Queries whether any threads are waiting to acquire. Note that * because cancellations due to interrupts and timeouts may occur * at any time, a {@code true} return does not guarantee that any * other thread will ever acquire. * * <p>In this implementation, this operation returns in * constant time. * {@description.close} * * @return {@code true} if there may be other threads waiting to acquire */ public final boolean hasQueuedThreads() { return head != tail; } /** {@collect.stats} * {@description.open} * Queries whether any threads have ever contended to acquire this * synchronizer; that is if an acquire method has ever blocked. * * <p>In this implementation, this operation returns in * constant time. * {@description.close} * * @return {@code true} if there has ever been contention */ public final boolean hasContended() { return head != null; } /** {@collect.stats} * {@description.open} * Returns the first (longest-waiting) thread in the queue, or * {@code null} if no threads are currently queued. * * <p>In this implementation, this operation normally returns in * constant time, but may iterate upon contention if other threads are * concurrently modifying the queue. * {@description.close} * * @return the first (longest-waiting) thread in the queue, or * {@code null} if no threads are currently queued */ public final Thread getFirstQueuedThread() { // handle only fast path, else relay return (head == tail) ? null : fullGetFirstQueuedThread(); } /** {@collect.stats} * {@description.open} * Version of getFirstQueuedThread called when fastpath fails * {@description.close} */ private Thread fullGetFirstQueuedThread() { /* * The first node is normally head.next. Try to get its * thread field, ensuring consistent reads: If thread * field is nulled out or s.prev is no longer head, then * some other thread(s) concurrently performed setHead in * between some of our reads. We try this twice before * resorting to traversal. */ Node h, s; Thread st; if (((h = head) != null && (s = h.next) != null && s.prev == head && (st = s.thread) != null) || ((h = head) != null && (s = h.next) != null && s.prev == head && (st = s.thread) != null)) return st; /* * Head's next field might not have been set yet, or may have * been unset after setHead. So we must check to see if tail * is actually first node. If not, we continue on, safely * traversing from tail back to head to find first, * guaranteeing termination. */ Node t = tail; Thread firstThread = null; while (t != null && t != head) { Thread tt = t.thread; if (tt != null) firstThread = tt; t = t.prev; } return firstThread; } /** {@collect.stats} * {@description.open} * Returns true if the given thread is currently queued. * * <p>This implementation traverses the queue to determine * presence of the given thread. * {@description.close} * * @param thread the thread * @return {@code true} if the given thread is on the queue * @throws NullPointerException if the thread is null */ public final boolean isQueued(Thread thread) { if (thread == null) throw new NullPointerException(); for (Node p = tail; p != null; p = p.prev) if (p.thread == thread) return true; return false; } /** {@collect.stats} * {@description.open} * Returns {@code true} if the apparent first queued thread, if one * exists, is waiting in exclusive mode. If this method returns * {@code true}, and the current thread is attempting to acquire in * shared mode (that is, this method is invoked from {@link * #tryAcquireShared}) then it is guaranteed that the current thread * is not the first queued thread. Used only as a heuristic in * ReentrantReadWriteLock. * {@description.close} */ final boolean apparentlyFirstQueuedIsExclusive() { Node h, s; return (h = head) != null && (s = h.next) != null && !s.isShared() && s.thread != null; } /** {@collect.stats} * {@description.open} * Queries whether any threads have been waiting to acquire longer * than the current thread. * * <p>An invocation of this method is equivalent to (but may be * more efficient than): * <pre> {@code * getFirstQueuedThread() != Thread.currentThread() && * hasQueuedThreads()}</pre> * * <p>Note that because cancellations due to interrupts and * timeouts may occur at any time, a {@code true} return does not * guarantee that some other thread will acquire before the current * thread. Likewise, it is possible for another thread to win a * race to enqueue after this method has returned {@code false}, * due to the queue being empty. * * <p>This method is designed to be used by a fair synchronizer to * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>. * Such a synchronizer's {@link #tryAcquire} method should return * {@code false}, and its {@link #tryAcquireShared} method should * return a negative value, if this method returns {@code true} * (unless this is a reentrant acquire). For example, the {@code * tryAcquire} method for a fair, reentrant, exclusive mode * synchronizer might look like this: * * <pre> {@code * protected boolean tryAcquire(int arg) { * if (isHeldExclusively()) { * // A reentrant acquire; increment hold count * return true; * } else if (hasQueuedPredecessors()) { * return false; * } else { * // try to acquire normally * } * }}</pre> * {@description.close} * * @return {@code true} if there is a queued thread preceding the * current thread, and {@code false} if the current thread * is at the head of the queue or the queue is empty * @since 1.7 */ final boolean hasQueuedPredecessors() { // The correctness of this depends on head being initialized // before tail and on head.next being accurate if the current // thread is first in queue. Node t = tail; // Read fields in reverse initialization order Node h = head; Node s; return h != t && ((s = h.next) == null || s.thread != Thread.currentThread()); } // Instrumentation and monitoring methods /** {@collect.stats} * {@description.open} * Returns an estimate of the number of threads waiting to * acquire. The value is only an estimate because the number of * threads may change dynamically while this method traverses * internal data structures. This method is designed for use in * monitoring system state, not for synchronization * control. * {@description.close} * * @return the estimated number of threads waiting to acquire */ public final int getQueueLength() { int n = 0; for (Node p = tail; p != null; p = p.prev) { if (p.thread != null) ++n; } return n; } /** {@collect.stats} * {@description.open} * Returns a collection containing threads that may be waiting to * acquire. Because the actual set of threads may change * dynamically while constructing this result, the returned * collection is only a best-effort estimate. The elements of the * returned collection are in no particular order. This method is * designed to facilitate construction of subclasses that provide * more extensive monitoring facilities. * {@description.close} * * @return the collection of threads */ public final Collection<Thread> getQueuedThreads() { ArrayList<Thread> list = new ArrayList<Thread>(); for (Node p = tail; p != null; p = p.prev) { Thread t = p.thread; if (t != null) list.add(t); } return list; } /** {@collect.stats} * {@description.open} * Returns a collection containing threads that may be waiting to * acquire in exclusive mode. This has the same properties * as {@link #getQueuedThreads} except that it only returns * those threads waiting due to an exclusive acquire. * {@description.close} * * @return the collection of threads */ public final Collection<Thread> getExclusiveQueuedThreads() { ArrayList<Thread> list = new ArrayList<Thread>(); for (Node p = tail; p != null; p = p.prev) { if (!p.isShared()) { Thread t = p.thread; if (t != null) list.add(t); } } return list; } /** {@collect.stats} * {@description.open} * Returns a collection containing threads that may be waiting to * acquire in shared mode. This has the same properties * as {@link #getQueuedThreads} except that it only returns * those threads waiting due to a shared acquire. * {@description.close} * * @return the collection of threads */ public final Collection<Thread> getSharedQueuedThreads() { ArrayList<Thread> list = new ArrayList<Thread>(); for (Node p = tail; p != null; p = p.prev) { if (p.isShared()) { Thread t = p.thread; if (t != null) list.add(t); } } return list; } /** {@collect.stats} * {@description.open} * Returns a string identifying this synchronizer, as well as its state. * The state, in brackets, includes the String {@code "State ="} * followed by the current value of {@link #getState}, and either * {@code "nonempty"} or {@code "empty"} depending on whether the * queue is empty. * {@description.close} * * @return a string identifying this synchronizer, as well as its state */ public String toString() { int s = getState(); String q = hasQueuedThreads() ? "non" : ""; return super.toString() + "[State = " + s + ", " + q + "empty queue]"; } // Internal support methods for Conditions /** {@collect.stats} * {@description.open} * Returns true if a node, always one that was initially placed on * a condition queue, is now waiting to reacquire on sync queue. * {@description.close} * @param node the node * @return true if is reacquiring */ final boolean isOnSyncQueue(Node node) { if (node.waitStatus == Node.CONDITION || node.prev == null) return false; if (node.next != null) // If has successor, it must be on queue return true; /* * node.prev can be non-null, but not yet on queue because * the CAS to place it on queue can fail. So we have to * traverse from tail to make sure it actually made it. It * will always be near the tail in calls to this method, and * unless the CAS failed (which is unlikely), it will be * there, so we hardly ever traverse much. */ return findNodeFromTail(node); } /** {@collect.stats} * {@description.open} * Returns true if node is on sync queue by searching backwards from tail. * Called only when needed by isOnSyncQueue. * {@description.close} * @return true if present */ private boolean findNodeFromTail(Node node) { Node t = tail; for (;;) { if (t == node) return true; if (t == null) return false; t = t.prev; } } /** {@collect.stats} * {@description.open} * Transfers a node from a condition queue onto sync queue. * Returns true if successful. * {@description.close} * @param node the node * @return true if successfully transferred (else the node was * cancelled before signal). */ final boolean transferForSignal(Node node) { /* * If cannot change waitStatus, the node has been cancelled. */ if (!compareAndSetWaitStatus(node, Node.CONDITION, 0)) return false; /* * Splice onto queue and try to set waitStatus of predecessor to * indicate that thread is (probably) waiting. If cancelled or * attempt to set waitStatus fails, wake up to resync (in which * case the waitStatus can be transiently and harmlessly wrong). */ Node p = enq(node); int ws = p.waitStatus; if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)) LockSupport.unpark(node.thread); return true; } /** {@collect.stats} * {@description.open} * Transfers node, if necessary, to sync queue after a cancelled * wait. Returns true if thread was cancelled before being * signalled. * {@description.close} * @param current the waiting thread * @param node its node * @return true if cancelled before the node was signalled */ final boolean transferAfterCancelledWait(Node node) { if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) { enq(node); return true; } /* * If we lost out to a signal(), then we can't proceed * until it finishes its enq(). Cancelling during an * incomplete transfer is both rare and transient, so just * spin. */ while (!isOnSyncQueue(node)) Thread.yield(); return false; } /** {@collect.stats} * {@description.open} * Invokes release with current state value; returns saved state. * Cancels node and throws exception on failure. * {@description.close} * @param node the condition node for this wait * @return previous sync state */ final int fullyRelease(Node node) { boolean failed = true; try { int savedState = getState(); if (release(savedState)) { failed = false; return savedState; } else { throw new IllegalMonitorStateException(); } } finally { if (failed) node.waitStatus = Node.CANCELLED; } } // Instrumentation methods for conditions /** {@collect.stats} * {@description.open} * Queries whether the given ConditionObject * uses this synchronizer as its lock. * {@description.close} * * @param condition the condition * @return <tt>true</tt> if owned * @throws NullPointerException if the condition is null */ public final boolean owns(ConditionObject condition) { if (condition == null) throw new NullPointerException(); return condition.isOwnedBy(this); } /** {@collect.stats} * {@description.open} * Queries whether any threads are waiting on the given condition * associated with this synchronizer. Note that because timeouts * and interrupts may occur at any time, a <tt>true</tt> return * does not guarantee that a future <tt>signal</tt> will awaken * any threads. This method is designed primarily for use in * monitoring of the system state. * {@description.close} * * @param condition the condition * @return <tt>true</tt> if there are any waiting threads * @throws IllegalMonitorStateException if exclusive synchronization * is not held * @throws IllegalArgumentException if the given condition is * not associated with this synchronizer * @throws NullPointerException if the condition is null */ public final boolean hasWaiters(ConditionObject condition) { if (!owns(condition)) throw new IllegalArgumentException("Not owner"); return condition.hasWaiters(); } /** {@collect.stats} * {@description.open} * Returns an estimate of the number of threads waiting on the * given condition associated with this synchronizer. Note that * because timeouts and interrupts may occur at any time, the * estimate serves only as an upper bound on the actual number of * waiters. This method is designed for use in monitoring of the * system state, not for synchronization control. * {@description.close} * * @param condition the condition * @return the estimated number of waiting threads * @throws IllegalMonitorStateException if exclusive synchronization * is not held * @throws IllegalArgumentException if the given condition is * not associated with this synchronizer * @throws NullPointerException if the condition is null */ public final int getWaitQueueLength(ConditionObject condition) { if (!owns(condition)) throw new IllegalArgumentException("Not owner"); return condition.getWaitQueueLength(); } /** {@collect.stats} * {@description.open} * Returns a collection containing those threads that may be * waiting on the given condition associated with this * synchronizer. Because the actual set of threads may change * dynamically while constructing this result, the returned * collection is only a best-effort estimate. The elements of the * returned collection are in no particular order. * {@description.close} * * @param condition the condition * @return the collection of threads * @throws IllegalMonitorStateException if exclusive synchronization * is not held * @throws IllegalArgumentException if the given condition is * not associated with this synchronizer * @throws NullPointerException if the condition is null */ public final Collection<Thread> getWaitingThreads(ConditionObject condition) { if (!owns(condition)) throw new IllegalArgumentException("Not owner"); return condition.getWaitingThreads(); } /** {@collect.stats} * {@description.open} * Condition implementation for a {@link * AbstractQueuedSynchronizer} serving as the basis of a {@link * Lock} implementation. * * <p>Method documentation for this class describes mechanics, * not behavioral specifications from the point of view of Lock * and Condition users. Exported versions of this class will in * general need to be accompanied by documentation describing * condition semantics that rely on those of the associated * <tt>AbstractQueuedSynchronizer</tt>. * * <p>This class is Serializable, but all fields are transient, * so deserialized conditions have no waiters. * {@description.close} */ public class ConditionObject implements Condition, java.io.Serializable { private static final long serialVersionUID = 1173984872572414699L; /** {@collect.stats} * {@description.open} * First node of condition queue. * {@description.close} */ private transient Node firstWaiter; /** {@collect.stats} * {@description.open} * Last node of condition queue. * {@description.close} */ private transient Node lastWaiter; /** {@collect.stats} * {@description.open} * Creates a new <tt>ConditionObject</tt> instance. * {@description.close} */ public ConditionObject() { } // Internal methods /** {@collect.stats} * {@description.open} * Adds a new waiter to wait queue. * {@description.close} * @return its new wait node */ private Node addConditionWaiter() { Node t = lastWaiter; // If lastWaiter is cancelled, clean out. if (t != null && t.waitStatus != Node.CONDITION) { unlinkCancelledWaiters(); t = lastWaiter; } Node node = new Node(Thread.currentThread(), Node.CONDITION); if (t == null) firstWaiter = node; else t.nextWaiter = node; lastWaiter = node; return node; } /** {@collect.stats} * {@description.open} * Removes and transfers nodes until hit non-cancelled one or * null. Split out from signal in part to encourage compilers * to inline the case of no waiters. * {@description.close} * @param first (non-null) the first node on condition queue */ private void doSignal(Node first) { do { if ( (firstWaiter = first.nextWaiter) == null) lastWaiter = null; first.nextWaiter = null; } while (!transferForSignal(first) && (first = firstWaiter) != null); } /** {@collect.stats} * {@description.open} * Removes and transfers all nodes. * {@description.close} * @param first (non-null) the first node on condition queue */ private void doSignalAll(Node first) { lastWaiter = firstWaiter = null; do { Node next = first.nextWaiter; first.nextWaiter = null; transferForSignal(first); first = next; } while (first != null); } /** {@collect.stats} * {@description.open} * Unlinks cancelled waiter nodes from condition queue. * Called only while holding lock. This is called when * cancellation occurred during condition wait, and upon * insertion of a new waiter when lastWaiter is seen to have * been cancelled. This method is needed to avoid garbage * retention in the absence of signals. So even though it may * require a full traversal, it comes into play only when * timeouts or cancellations occur in the absence of * signals. It traverses all nodes rather than stopping at a * particular target to unlink all pointers to garbage nodes * without requiring many re-traversals during cancellation * storms. * {@description.close} */ private void unlinkCancelledWaiters() { Node t = firstWaiter; Node trail = null; while (t != null) { Node next = t.nextWaiter; if (t.waitStatus != Node.CONDITION) { t.nextWaiter = null; if (trail == null) firstWaiter = next; else trail.nextWaiter = next; if (next == null) lastWaiter = trail; } else trail = t; t = next; } } // public methods /** {@collect.stats} * {@description.open} * Moves the longest-waiting thread, if one exists, from the * wait queue for this condition to the wait queue for the * owning lock. * {@description.close} * * @throws IllegalMonitorStateException if {@link #isHeldExclusively} * returns {@code false} */ public final void signal() { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); Node first = firstWaiter; if (first != null) doSignal(first); } /** {@collect.stats} * {@description.open} * Moves all threads from the wait queue for this condition to * the wait queue for the owning lock. * {@description.close} * * @throws IllegalMonitorStateException if {@link #isHeldExclusively} * returns {@code false} */ public final void signalAll() { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); Node first = firstWaiter; if (first != null) doSignalAll(first); } /** {@collect.stats} * {@description.open} * Implements uninterruptible condition wait. * <ol> * <li> Save lock state returned by {@link #getState}. * <li> Invoke {@link #release} with * saved state as argument, throwing * IllegalMonitorStateException if it fails. * <li> Block until signalled. * <li> Reacquire by invoking specialized version of * {@link #acquire} with saved state as argument. * </ol> * {@description.close} */ public final void awaitUninterruptibly() { Node node = addConditionWaiter(); int savedState = fullyRelease(node); boolean interrupted = false; while (!isOnSyncQueue(node)) { LockSupport.park(this); if (Thread.interrupted()) interrupted = true; } if (acquireQueued(node, savedState) || interrupted) selfInterrupt(); } /* * For interruptible waits, we need to track whether to throw * InterruptedException, if interrupted while blocked on * condition, versus reinterrupt current thread, if * interrupted while blocked waiting to re-acquire. */ /** {@collect.stats} * {@description.open} * Mode meaning to reinterrupt on exit from wait * {@description.close} */ private static final int REINTERRUPT = 1; /** {@collect.stats} * {@description.open} * Mode meaning to throw InterruptedException on exit from wait * {@description.close} */ private static final int THROW_IE = -1; /** {@collect.stats} * {@description.open} * Checks for interrupt, returning THROW_IE if interrupted * before signalled, REINTERRUPT if after signalled, or * 0 if not interrupted. * {@description.close} */ private int checkInterruptWhileWaiting(Node node) { return Thread.interrupted() ? (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) : 0; } /** {@collect.stats} * {@description.open} * Throws InterruptedException, reinterrupts current thread, or * does nothing, depending on mode. * {@description.close} */ private void reportInterruptAfterWait(int interruptMode) throws InterruptedException { if (interruptMode == THROW_IE) throw new InterruptedException(); else if (interruptMode == REINTERRUPT) selfInterrupt(); } /** {@collect.stats} * {@description.open} * Implements interruptible condition wait. * <ol> * <li> If current thread is interrupted, throw InterruptedException. * <li> Save lock state returned by {@link #getState}. * <li> Invoke {@link #release} with * saved state as argument, throwing * IllegalMonitorStateException if it fails. * <li> Block until signalled or interrupted. * <li> Reacquire by invoking specialized version of * {@link #acquire} with saved state as argument. * <li> If interrupted while blocked in step 4, throw InterruptedException. * </ol> * {@description.close} */ public final void await() throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); int savedState = fullyRelease(node); int interruptMode = 0; while (!isOnSyncQueue(node)) { LockSupport.park(this); if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) break; } if (acquireQueued(node, savedState) && interruptMode != THROW_IE) interruptMode = REINTERRUPT; if (node.nextWaiter != null) // clean up if cancelled unlinkCancelledWaiters(); if (interruptMode != 0) reportInterruptAfterWait(interruptMode); } /** {@collect.stats} * {@description.open} * Implements timed condition wait. * <ol> * <li> If current thread is interrupted, throw InterruptedException. * <li> Save lock state returned by {@link #getState}. * <li> Invoke {@link #release} with * saved state as argument, throwing * IllegalMonitorStateException if it fails. * <li> Block until signalled, interrupted, or timed out. * <li> Reacquire by invoking specialized version of * {@link #acquire} with saved state as argument. * <li> If interrupted while blocked in step 4, throw InterruptedException. * </ol> * {@description.close} */ public final long awaitNanos(long nanosTimeout) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); int savedState = fullyRelease(node); long lastTime = System.nanoTime(); int interruptMode = 0; while (!isOnSyncQueue(node)) { if (nanosTimeout <= 0L) { transferAfterCancelledWait(node); break; } LockSupport.parkNanos(this, nanosTimeout); if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) break; long now = System.nanoTime(); nanosTimeout -= now - lastTime; lastTime = now; } if (acquireQueued(node, savedState) && interruptMode != THROW_IE) interruptMode = REINTERRUPT; if (node.nextWaiter != null) unlinkCancelledWaiters(); if (interruptMode != 0) reportInterruptAfterWait(interruptMode); return nanosTimeout - (System.nanoTime() - lastTime); } /** {@collect.stats} * {@description.open} * Implements absolute timed condition wait. * <ol> * <li> If current thread is interrupted, throw InterruptedException. * <li> Save lock state returned by {@link #getState}. * <li> Invoke {@link #release} with * saved state as argument, throwing * IllegalMonitorStateException if it fails. * <li> Block until signalled, interrupted, or timed out. * <li> Reacquire by invoking specialized version of * {@link #acquire} with saved state as argument. * <li> If interrupted while blocked in step 4, throw InterruptedException. * <li> If timed out while blocked in step 4, return false, else true. * </ol> * {@description.close} */ public final boolean awaitUntil(Date deadline) throws InterruptedException { if (deadline == null) throw new NullPointerException(); long abstime = deadline.getTime(); if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); int savedState = fullyRelease(node); boolean timedout = false; int interruptMode = 0; while (!isOnSyncQueue(node)) { if (System.currentTimeMillis() > abstime) { timedout = transferAfterCancelledWait(node); break; } LockSupport.parkUntil(this, abstime); if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) break; } if (acquireQueued(node, savedState) && interruptMode != THROW_IE) interruptMode = REINTERRUPT; if (node.nextWaiter != null) unlinkCancelledWaiters(); if (interruptMode != 0) reportInterruptAfterWait(interruptMode); return !timedout; } /** {@collect.stats} * {@description.open} * Implements timed condition wait. * <ol> * <li> If current thread is interrupted, throw InterruptedException. * <li> Save lock state returned by {@link #getState}. * <li> Invoke {@link #release} with * saved state as argument, throwing * IllegalMonitorStateException if it fails. * <li> Block until signalled, interrupted, or timed out. * <li> Reacquire by invoking specialized version of * {@link #acquire} with saved state as argument. * <li> If interrupted while blocked in step 4, throw InterruptedException. * <li> If timed out while blocked in step 4, return false, else true. * </ol> * {@description.close} */ public final boolean await(long time, TimeUnit unit) throws InterruptedException { if (unit == null) throw new NullPointerException(); long nanosTimeout = unit.toNanos(time); if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); int savedState = fullyRelease(node); long lastTime = System.nanoTime(); boolean timedout = false; int interruptMode = 0; while (!isOnSyncQueue(node)) { if (nanosTimeout <= 0L) { timedout = transferAfterCancelledWait(node); break; } if (nanosTimeout >= spinForTimeoutThreshold) LockSupport.parkNanos(this, nanosTimeout); if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) break; long now = System.nanoTime(); nanosTimeout -= now - lastTime; lastTime = now; } if (acquireQueued(node, savedState) && interruptMode != THROW_IE) interruptMode = REINTERRUPT; if (node.nextWaiter != null) unlinkCancelledWaiters(); if (interruptMode != 0) reportInterruptAfterWait(interruptMode); return !timedout; } // support for instrumentation /** {@collect.stats} * {@description.open} * Returns true if this condition was created by the given * synchronization object. * {@description.close} * * @return {@code true} if owned */ final boolean isOwnedBy(AbstractQueuedSynchronizer sync) { return sync == AbstractQueuedSynchronizer.this; } /** {@collect.stats} * {@description.open} * Queries whether any threads are waiting on this condition. * Implements {@link AbstractQueuedSynchronizer#hasWaiters}. * {@description.close} * * @return {@code true} if there are any waiting threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} * returns {@code false} */ protected final boolean hasWaiters() { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); for (Node w = firstWaiter; w != null; w = w.nextWaiter) { if (w.waitStatus == Node.CONDITION) return true; } return false; } /** {@collect.stats} * {@description.open} * Returns an estimate of the number of threads waiting on * this condition. * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}. * {@description.close} * * @return the estimated number of waiting threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} * returns {@code false} */ protected final int getWaitQueueLength() { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); int n = 0; for (Node w = firstWaiter; w != null; w = w.nextWaiter) { if (w.waitStatus == Node.CONDITION) ++n; } return n; } /** {@collect.stats} * {@description.open} * Returns a collection containing those threads that may be * waiting on this Condition. * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}. * {@description.close} * * @return the collection of threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} * returns {@code false} */ protected final Collection<Thread> getWaitingThreads() { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); ArrayList<Thread> list = new ArrayList<Thread>(); for (Node w = firstWaiter; w != null; w = w.nextWaiter) { if (w.waitStatus == Node.CONDITION) { Thread t = w.thread; if (t != null) list.add(t); } } return list; } } /** {@collect.stats} * {@description.open} * Setup to support compareAndSet. We need to natively implement * this here: For the sake of permitting future enhancements, we * cannot explicitly subclass AtomicInteger, which would be * efficient and useful otherwise. So, as the lesser of evils, we * natively implement using hotspot intrinsics API. And while we * are at it, we do the same for other CASable fields (which could * otherwise be done with atomic field updaters). * {@description.close} */ private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long stateOffset; private static final long headOffset; private static final long tailOffset; private static final long waitStatusOffset; private static final long nextOffset; static { try { stateOffset = unsafe.objectFieldOffset (AbstractQueuedSynchronizer.class.getDeclaredField("state")); headOffset = unsafe.objectFieldOffset (AbstractQueuedSynchronizer.class.getDeclaredField("head")); tailOffset = unsafe.objectFieldOffset (AbstractQueuedSynchronizer.class.getDeclaredField("tail")); waitStatusOffset = unsafe.objectFieldOffset (Node.class.getDeclaredField("waitStatus")); nextOffset = unsafe.objectFieldOffset (Node.class.getDeclaredField("next")); } catch (Exception ex) { throw new Error(ex); } } /** {@collect.stats} * {@description.open} * CAS head field. Used only by enq. * {@description.close} */ private final boolean compareAndSetHead(Node update) { return unsafe.compareAndSwapObject(this, headOffset, null, update); } /** {@collect.stats} * {@description.open} * CAS tail field. Used only by enq. * {@description.close} */ private final boolean compareAndSetTail(Node expect, Node update) { return unsafe.compareAndSwapObject(this, tailOffset, expect, update); } /** {@collect.stats} * {@description.open} * CAS waitStatus field of a node. * {@description.close} */ private final static boolean compareAndSetWaitStatus(Node node, int expect, int update) { return unsafe.compareAndSwapInt(node, waitStatusOffset, expect, update); } /** {@collect.stats} * {@description.open} * CAS next field of a node. * {@description.close} */ private final static boolean compareAndSetNext(Node node, Node expect, Node update) { return unsafe.compareAndSwapObject(node, nextOffset, expect, update); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.locks; /** {@collect.stats} * {@description.open} * A <tt>ReadWriteLock</tt> maintains a pair of associated {@link * Lock locks}, one for read-only operations and one for writing. * The {@link #readLock read lock} may be held simultaneously by * multiple reader threads, so long as there are no writers. The * {@link #writeLock write lock} is exclusive. * * <p>All <tt>ReadWriteLock</tt> implementations must guarantee that * the memory synchronization effects of <tt>writeLock</tt> operations * (as specified in the {@link Lock} interface) also hold with respect * to the associated <tt>readLock</tt>. That is, a thread successfully * acquiring the read lock will see all updates made upon previous * release of the write lock. * * <p>A read-write lock allows for a greater level of concurrency in * accessing shared data than that permitted by a mutual exclusion lock. * It exploits the fact that while only a single thread at a time (a * <em>writer</em> thread) can modify the shared data, in many cases any * number of threads can concurrently read the data (hence <em>reader</em> * threads). * In theory, the increase in concurrency permitted by the use of a read-write * lock will lead to performance improvements over the use of a mutual * exclusion lock. In practice this increase in concurrency will only be fully * realized on a multi-processor, and then only if the access patterns for * the shared data are suitable. * * <p>Whether or not a read-write lock will improve performance over the use * of a mutual exclusion lock depends on the frequency that the data is * read compared to being modified, the duration of the read and write * operations, and the contention for the data - that is, the number of * threads that will try to read or write the data at the same time. * For example, a collection that is initially populated with data and * thereafter infrequently modified, while being frequently searched * (such as a directory of some kind) is an ideal candidate for the use of * a read-write lock. However, if updates become frequent then the data * spends most of its time being exclusively locked and there is little, if any * increase in concurrency. Further, if the read operations are too short * the overhead of the read-write lock implementation (which is inherently * more complex than a mutual exclusion lock) can dominate the execution * cost, particularly as many read-write lock implementations still serialize * all threads through a small section of code. Ultimately, only profiling * and measurement will establish whether the use of a read-write lock is * suitable for your application. * * * <p>Although the basic operation of a read-write lock is straight-forward, * there are many policy decisions that an implementation must make, which * may affect the effectiveness of the read-write lock in a given application. * Examples of these policies include: * <ul> * <li>Determining whether to grant the read lock or the write lock, when * both readers and writers are waiting, at the time that a writer releases * the write lock. Writer preference is common, as writes are expected to be * short and infrequent. Reader preference is less common as it can lead to * lengthy delays for a write if the readers are frequent and long-lived as * expected. Fair, or &quot;in-order&quot; implementations are also possible. * * <li>Determining whether readers that request the read lock while a * reader is active and a writer is waiting, are granted the read lock. * Preference to the reader can delay the writer indefinitely, while * preference to the writer can reduce the potential for concurrency. * * <li>Determining whether the locks are reentrant: can a thread with the * write lock reacquire it? Can it acquire a read lock while holding the * write lock? Is the read lock itself reentrant? * * <li>Can the write lock be downgraded to a read lock without allowing * an intervening writer? Can a read lock be upgraded to a write lock, * in preference to other waiting readers or writers? * * </ul> * You should consider all of these things when evaluating the suitability * of a given implementation for your application. * {@description.close} * * @see ReentrantReadWriteLock * @see Lock * @see ReentrantLock * * @since 1.5 * @author Doug Lea */ public interface ReadWriteLock { /** {@collect.stats} * {@description.open} * Returns the lock used for reading. * {@description.close} * * @return the lock used for reading. */ Lock readLock(); /** {@collect.stats} * {@description.open} * Returns the lock used for writing. * {@description.close} * * @return the lock used for writing. */ Lock writeLock(); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.locks; import java.util.concurrent.*; import sun.misc.Unsafe; /** {@collect.stats} * {@description.open} * Basic thread blocking primitives for creating locks and other * synchronization classes. * * <p>This class associates, with each thread that uses it, a permit * (in the sense of the {@link java.util.concurrent.Semaphore * Semaphore} class). A call to {@code park} will return immediately * if the permit is available, consuming it in the process; otherwise * it <em>may</em> block. A call to {@code unpark} makes the permit * available, if it was not already available. (Unlike with Semaphores * though, permits do not accumulate. There is at most one.) * * <p>Methods {@code park} and {@code unpark} provide efficient * means of blocking and unblocking threads that do not encounter the * problems that cause the deprecated methods {@code Thread.suspend} * and {@code Thread.resume} to be unusable for such purposes: Races * between one thread invoking {@code park} and another thread trying * to {@code unpark} it will preserve liveness, due to the * permit. Additionally, {@code park} will return if the caller's * thread was interrupted, and timeout versions are supported. The * {@code park} method may also return at any other time, for "no * reason", so in general must be invoked within a loop that rechecks * conditions upon return. In this sense {@code park} serves as an * optimization of a "busy wait" that does not waste as much time * spinning, but must be paired with an {@code unpark} to be * effective. * * <p>The three forms of {@code park} each also support a * {@code blocker} object parameter. This object is recorded while * the thread is blocked to permit monitoring and diagnostic tools to * identify the reasons that threads are blocked. (Such tools may * access blockers using method {@link #getBlocker}.) The use of these * forms rather than the original forms without this parameter is * strongly encouraged. The normal argument to supply as a * {@code blocker} within a lock implementation is {@code this}. * * <p>These methods are designed to be used as tools for creating * higher-level synchronization utilities, and are not in themselves * useful for most concurrency control applications. The {@code park} * method is designed for use only in constructions of the form: * <pre>while (!canProceed()) { ... LockSupport.park(this); }</pre> * where neither {@code canProceed} nor any other actions prior to the * call to {@code park} entail locking or blocking. Because only one * permit is associated with each thread, any intermediary uses of * {@code park} could interfere with its intended effects. * * <p><b>Sample Usage.</b> Here is a sketch of a first-in-first-out * non-reentrant lock class: * <pre>{@code * class FIFOMutex { * private final AtomicBoolean locked = new AtomicBoolean(false); * private final Queue<Thread> waiters * = new ConcurrentLinkedQueue<Thread>(); * * public void lock() { * boolean wasInterrupted = false; * Thread current = Thread.currentThread(); * waiters.add(current); * * // Block while not first in queue or cannot acquire lock * while (waiters.peek() != current || * !locked.compareAndSet(false, true)) { * LockSupport.park(this); * if (Thread.interrupted()) // ignore interrupts while waiting * wasInterrupted = true; * } * * waiters.remove(); * if (wasInterrupted) // reassert interrupt status on exit * current.interrupt(); * } * * public void unlock() { * locked.set(false); * LockSupport.unpark(waiters.peek()); * } * }}</pre> * {@description.close} */ public class LockSupport { private LockSupport() {} // Cannot be instantiated. // Hotspot implementation via intrinsics API private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long parkBlockerOffset; static { try { parkBlockerOffset = unsafe.objectFieldOffset (java.lang.Thread.class.getDeclaredField("parkBlocker")); } catch (Exception ex) { throw new Error(ex); } } private static void setBlocker(Thread t, Object arg) { // Even though volatile, hotspot doesn't need a write barrier here. unsafe.putObject(t, parkBlockerOffset, arg); } /** {@collect.stats} * {@description.open} * Makes available the permit for the given thread, if it * was not already available. If the thread was blocked on * {@code park} then it will unblock. Otherwise, its next call * to {@code park} is guaranteed not to block. This operation * is not guaranteed to have any effect at all if the given * thread has not been started. * {@description.close} * * @param thread the thread to unpark, or {@code null}, in which case * this operation has no effect */ public static void unpark(Thread thread) { if (thread != null) unsafe.unpark(thread); } /** {@collect.stats} * {@description.open} * Disables the current thread for thread scheduling purposes unless the * permit is available. * * <p>If the permit is available then it is consumed and the call returns * immediately; otherwise * the current thread becomes disabled for thread scheduling * purposes and lies dormant until one of three things happens: * * <ul> * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread upon return. * {@description.close} * * @param blocker the synchronization object responsible for this * thread parking * @since 1.6 */ public static void park(Object blocker) { Thread t = Thread.currentThread(); setBlocker(t, blocker); unsafe.park(false, 0L); setBlocker(t, null); } /** {@collect.stats} * {@description.open} * Disables the current thread for thread scheduling purposes, for up to * the specified waiting time, unless the permit is available. * * <p>If the permit is available then it is consumed and the call * returns immediately; otherwise the current thread becomes disabled * for thread scheduling purposes and lies dormant until one of four * things happens: * * <ul> * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} the current * thread; or * * <li>The specified waiting time elapses; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread, or the elapsed time * upon return. * {@description.close} * * @param blocker the synchronization object responsible for this * thread parking * @param nanos the maximum number of nanoseconds to wait * @since 1.6 */ public static void parkNanos(Object blocker, long nanos) { if (nanos > 0) { Thread t = Thread.currentThread(); setBlocker(t, blocker); unsafe.park(false, nanos); setBlocker(t, null); } } /** {@collect.stats} * {@description.open} * Disables the current thread for thread scheduling purposes, until * the specified deadline, unless the permit is available. * * <p>If the permit is available then it is consumed and the call * returns immediately; otherwise the current thread becomes disabled * for thread scheduling purposes and lies dormant until one of four * things happens: * * <ul> * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} the * current thread; or * * <li>The specified deadline passes; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread, or the current time * upon return. * {@description.close} * * @param blocker the synchronization object responsible for this * thread parking * @param deadline the absolute time, in milliseconds from the Epoch, * to wait until * @since 1.6 */ public static void parkUntil(Object blocker, long deadline) { Thread t = Thread.currentThread(); setBlocker(t, blocker); unsafe.park(true, deadline); setBlocker(t, null); } /** {@collect.stats} * {@description.open} * Returns the blocker object supplied to the most recent * invocation of a park method that has not yet unblocked, or null * if not blocked. The value returned is just a momentary * snapshot -- the thread may have since unblocked or blocked on a * different blocker object. * {@description.close} * * @return the blocker * @since 1.6 */ public static Object getBlocker(Thread t) { return unsafe.getObjectVolatile(t, parkBlockerOffset); } /** {@collect.stats} * {@description.open} * Disables the current thread for thread scheduling purposes unless the * permit is available. * * <p>If the permit is available then it is consumed and the call * returns immediately; otherwise the current thread becomes disabled * for thread scheduling purposes and lies dormant until one of three * things happens: * * <ul> * * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread upon return. * {@description.close} */ public static void park() { unsafe.park(false, 0L); } /** {@collect.stats} * {@description.open} * Disables the current thread for thread scheduling purposes, for up to * the specified waiting time, unless the permit is available. * * <p>If the permit is available then it is consumed and the call * returns immediately; otherwise the current thread becomes disabled * for thread scheduling purposes and lies dormant until one of four * things happens: * * <ul> * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The specified waiting time elapses; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread, or the elapsed time * upon return. * {@description.close} * * @param nanos the maximum number of nanoseconds to wait */ public static void parkNanos(long nanos) { if (nanos > 0) unsafe.park(false, nanos); } /** {@collect.stats} * {@description.open} * Disables the current thread for thread scheduling purposes, until * the specified deadline, unless the permit is available. * * <p>If the permit is available then it is consumed and the call * returns immediately; otherwise the current thread becomes disabled * for thread scheduling purposes and lies dormant until one of four * things happens: * * <ul> * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The specified deadline passes; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread, or the current time * upon return. * {@description.close} * * @param deadline the absolute time, in milliseconds from the Epoch, * to wait until */ public static void parkUntil(long deadline) { unsafe.park(true, deadline); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.locks; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; /** {@collect.stats} * {@description.open} * A reentrant mutual exclusion {@link Lock} with the same basic * behavior and semantics as the implicit monitor lock accessed using * {@code synchronized} methods and statements, but with extended * capabilities. * {@description.close} * * {@property.open} * <p>A {@code ReentrantLock} is <em>owned</em> by the thread last * successfully locking, but not yet unlocking it. A thread invoking * {@code lock} will return, successfully acquiring the lock, when * the lock is not owned by another thread. The method will return * immediately if the current thread already owns the lock. This can * be checked using methods {@link #isHeldByCurrentThread}, and {@link * #getHoldCount}. * {@property.close} * * {@description.open} * <p>The constructor for this class accepts an optional * <em>fairness</em> parameter. When set {@code true}, under * contention, locks favor granting access to the longest-waiting * thread. Otherwise this lock does not guarantee any particular * access order. Programs using fair locks accessed by many threads * may display lower overall throughput (i.e., are slower; often much * slower) than those using the default setting, but have smaller * variances in times to obtain locks and guarantee lack of * starvation. Note however, that fairness of locks does not guarantee * fairness of thread scheduling. Thus, one of many threads using a * fair lock may obtain it multiple times in succession while other * active threads are not progressing and not currently holding the * lock. * Also note that the untimed {@link #tryLock() tryLock} method does not * honor the fairness setting. It will succeed if the lock * is available even if other threads are waiting. * {@description.close} * * {@property.open} * <p>It is recommended practice to <em>always</em> immediately * follow a call to {@code lock} with a {@code try} block, most * typically in a before/after construction such as: * * <pre> * class X { * private final ReentrantLock lock = new ReentrantLock(); * // ... * * public void m() { * lock.lock(); // block until condition holds * try { * // ... method body * } finally { * lock.unlock() * } * } * } * </pre> * {@property.close} * * {@description.open} * <p>In addition to implementing the {@link Lock} interface, this * class defines methods {@code isLocked} and * {@code getLockQueueLength}, as well as some associated * {@code protected} access methods that may be useful for * instrumentation and monitoring. * * <p>Serialization of this class behaves in the same way as built-in * locks: a deserialized lock is in the unlocked state, regardless of * its state when serialized. * * <p>This lock supports a maximum of 2147483647 recursive locks by * the same thread. Attempts to exceed this limit result in * {@link Error} throws from locking methods. * {@description.close} * * @since 1.5 * @author Doug Lea */ public class ReentrantLock implements Lock, java.io.Serializable { private static final long serialVersionUID = 7373984872572414699L; /** {@collect.stats} * {@description.open} * Synchronizer providing all implementation mechanics * {@description.close} */ private final Sync sync; /** {@collect.stats} * {@description.open} * Base of synchronization control for this lock. Subclassed * into fair and nonfair versions below. Uses AQS state to * represent the number of holds on the lock. * {@description.close} */ static abstract class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = -5179523762034025860L; /** {@collect.stats} * {@description.open} * Performs {@link Lock#lock}. The main reason for subclassing * is to allow fast path for nonfair version. * {@description.close} */ abstract void lock(); /** {@collect.stats} * {@description.open} * Performs non-fair tryLock. tryAcquire is * implemented in subclasses, but both need nonfair * try for trylock method. * {@description.close} */ final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } protected final boolean tryRelease(int releases) { int c = getState() - releases; if (Thread.currentThread() != getExclusiveOwnerThread()) throw new IllegalMonitorStateException(); boolean free = false; if (c == 0) { free = true; setExclusiveOwnerThread(null); } setState(c); return free; } protected final boolean isHeldExclusively() { // While we must in general read state before owner, // we don't need to do so to check if current thread is owner return getExclusiveOwnerThread() == Thread.currentThread(); } final ConditionObject newCondition() { return new ConditionObject(); } // Methods relayed from outer class final Thread getOwner() { return getState() == 0 ? null : getExclusiveOwnerThread(); } final int getHoldCount() { return isHeldExclusively() ? getState() : 0; } final boolean isLocked() { return getState() != 0; } /** {@collect.stats} * {@description.open} * Reconstitutes this lock instance from a stream. * {@description.close} * @param s the stream */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); setState(0); // reset to unlocked state } } /** {@collect.stats} * {@description.open} * Sync object for non-fair locks * {@description.close} */ final static class NonfairSync extends Sync { private static final long serialVersionUID = 7316153563782823691L; /** {@collect.stats} * {@description.open} * Performs lock. Try immediate barge, backing up to normal * acquire on failure. * {@description.close} */ final void lock() { if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); } protected final boolean tryAcquire(int acquires) { return nonfairTryAcquire(acquires); } } /** {@collect.stats} * {@description.open} * Sync object for fair locks * {@description.close} */ final static class FairSync extends Sync { private static final long serialVersionUID = -3000897897090466540L; final void lock() { acquire(1); } /** {@collect.stats} * {@description.open} * Fair version of tryAcquire. Don't grant access unless * recursive call or no waiters or is first. * {@description.close} */ protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } } /** {@collect.stats} * {@description.open} * Creates an instance of {@code ReentrantLock}. * This is equivalent to using {@code ReentrantLock(false)}. * {@description.close} */ public ReentrantLock() { sync = new NonfairSync(); } /** {@collect.stats} * {@description.open} * Creates an instance of {@code ReentrantLock} with the * given fairness policy. * {@description.close} * * @param fair {@code true} if this lock should use a fair ordering policy */ public ReentrantLock(boolean fair) { sync = (fair)? new FairSync() : new NonfairSync(); } /** {@collect.stats} * {@description.open} * Acquires the lock. * {@description.close} * * {@property.open} * <p>Acquires the lock if it is not held by another thread and returns * immediately, setting the lock hold count to one. * * <p>If the current thread already holds the lock then the hold * count is incremented by one and the method returns immediately. * {@property.close} * * {@description.open} * <p>If the lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until the lock has been acquired, * at which time the lock hold count is set to one. * {@description.close} */ public void lock() { sync.lock(); } /** {@collect.stats} * {@description.open} * Acquires the lock unless the current thread is * {@linkplain Thread#interrupt interrupted}. * {@description.close} * * {@property.open} * <p>Acquires the lock if it is not held by another thread and returns * immediately, setting the lock hold count to one. * * <p>If the current thread already holds this lock then the hold count * is incremented by one and the method returns immediately. * {@property.close} * * {@property.open} * <p>If the lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until one of two things happens: * * <ul> * * <li>The lock is acquired by the current thread; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} the * current thread. * * </ul> * {@property.close} * * {@description.open} * <p>If the lock is acquired by the current thread then the lock hold * count is set to one. * * <p>If the current thread: * * <ul> * * <li>has its interrupted status set on entry to this method; or * * <li>is {@linkplain Thread#interrupt interrupted} while acquiring * the lock, * * </ul> * * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>In this implementation, as this method is an explicit * interruption point, preference is given to responding to the * interrupt over normal or reentrant acquisition of the lock. * {@description.close} * * @throws InterruptedException if the current thread is interrupted */ public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } /** {@collect.stats} * {@description.open} * Acquires the lock only if it is not held by another thread at the time * of invocation. * * <p>Acquires the lock if it is not held by another thread and * returns immediately with the value {@code true}, setting the * lock hold count to one. Even when this lock has been set to use a * fair ordering policy, a call to {@code tryLock()} <em>will</em> * immediately acquire the lock if it is available, whether or not * other threads are currently waiting for the lock. * This &quot;barging&quot; behavior can be useful in certain * circumstances, even though it breaks fairness. If you want to honor * the fairness setting for this lock, then use * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } * which is almost equivalent (it also detects interruption). * * <p> If the current thread already holds this lock then the hold * count is incremented by one and the method returns {@code true}. * * <p>If the lock is held by another thread then this method will return * immediately with the value {@code false}. * {@description.close} * * @return {@code true} if the lock was free and was acquired by the * current thread, or the lock was already held by the current * thread; and {@code false} otherwise */ public boolean tryLock() { return sync.nonfairTryAcquire(1); } /** {@collect.stats} * {@description.open} * Acquires the lock if it is not held by another thread within the given * waiting time and the current thread has not been * {@linkplain Thread#interrupt interrupted}. * * <p>Acquires the lock if it is not held by another thread and returns * immediately with the value {@code true}, setting the lock hold count * to one. If this lock has been set to use a fair ordering policy then * an available lock <em>will not</em> be acquired if any other threads * are waiting for the lock. This is in contrast to the {@link #tryLock()} * method. If you want a timed {@code tryLock} that does permit barging on * a fair lock then combine the timed and un-timed forms together: * * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... } * </pre> * {@description.close} * * {@property.open} * <p>If the current thread * already holds this lock then the hold count is incremented by one and * the method returns {@code true}. * * <p>If the lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until one of three things happens: * * <ul> * * <li>The lock is acquired by the current thread; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The specified waiting time elapses * * </ul> * {@property.close} * * {@description.open} * <p>If the lock is acquired then the value {@code true} is returned and * the lock hold count is set to one. * * <p>If the current thread: * * <ul> * * <li>has its interrupted status set on entry to this method; or * * <li>is {@linkplain Thread#interrupt interrupted} while * acquiring the lock, * * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the specified waiting time elapses then the value {@code false} * is returned. If the time is less than or equal to zero, the method * will not wait at all. * * <p>In this implementation, as this method is an explicit * interruption point, preference is given to responding to the * interrupt over normal or reentrant acquisition of the lock, and * over reporting the elapse of the waiting time. * {@description.close} * * @param timeout the time to wait for the lock * @param unit the time unit of the timeout argument * @return {@code true} if the lock was free and was acquired by the * current thread, or the lock was already held by the current * thread; and {@code false} if the waiting time elapsed before * the lock could be acquired * @throws InterruptedException if the current thread is interrupted * @throws NullPointerException if the time unit is null * */ public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(timeout)); } /** {@collect.stats} * {@description.open} * Attempts to release this lock. * {@description.close} * * {@property.open} * <p>If the current thread is the holder of this lock then the hold * count is decremented. If the hold count is now zero then the lock * is released. If the current thread is not the holder of this * lock then {@link IllegalMonitorStateException} is thrown. * {@property.close} * * @throws IllegalMonitorStateException if the current thread does not * hold this lock */ public void unlock() { sync.release(1); } /** {@collect.stats} * {@description.open} * Returns a {@link Condition} instance for use with this * {@link Lock} instance. * * <p>The returned {@link Condition} instance supports the same * usages as do the {@link Object} monitor methods ({@link * Object#wait() wait}, {@link Object#notify notify}, and {@link * Object#notifyAll notifyAll}) when used with the built-in * monitor lock. * * <ul> * * <li>If this lock is not held when any of the {@link Condition} * {@linkplain Condition#await() waiting} or {@linkplain * Condition#signal signalling} methods are called, then an {@link * IllegalMonitorStateException} is thrown. * * <li>When the condition {@linkplain Condition#await() waiting} * methods are called the lock is released and, before they * return, the lock is reacquired and the lock hold count restored * to what it was when the method was called. * * <li>If a thread is {@linkplain Thread#interrupt interrupted} * while waiting then the wait will terminate, an {@link * InterruptedException} will be thrown, and the thread's * interrupted status will be cleared. * * <li> Waiting threads are signalled in FIFO order. * * <li>The ordering of lock reacquisition for threads returning * from waiting methods is the same as for threads initially * acquiring the lock, which is in the default case not specified, * but for <em>fair</em> locks favors those threads that have been * waiting the longest. * * </ul> * {@description.close} * * @return the Condition object */ public Condition newCondition() { return sync.newCondition(); } /** {@collect.stats} * {@description.open} * Queries the number of holds on this lock by the current thread. * * <p>A thread has a hold on a lock for each lock action that is not * matched by an unlock action. * * <p>The hold count information is typically only used for testing and * debugging purposes. For example, if a certain section of code should * not be entered with the lock already held then we can assert that * fact: * * <pre> * class X { * ReentrantLock lock = new ReentrantLock(); * // ... * public void m() { * assert lock.getHoldCount() == 0; * lock.lock(); * try { * // ... method body * } finally { * lock.unlock(); * } * } * } * </pre> * {@description.close} * * @return the number of holds on this lock by the current thread, * or zero if this lock is not held by the current thread */ public int getHoldCount() { return sync.getHoldCount(); } /** {@collect.stats} * {@description.open} * Queries if this lock is held by the current thread. * * <p>Analogous to the {@link Thread#holdsLock} method for built-in * monitor locks, this method is typically used for debugging and * testing. For example, a method that should only be called while * a lock is held can assert that this is the case: * * <pre> * class X { * ReentrantLock lock = new ReentrantLock(); * // ... * * public void m() { * assert lock.isHeldByCurrentThread(); * // ... method body * } * } * </pre> * * <p>It can also be used to ensure that a reentrant lock is used * in a non-reentrant manner, for example: * * <pre> * class X { * ReentrantLock lock = new ReentrantLock(); * // ... * * public void m() { * assert !lock.isHeldByCurrentThread(); * lock.lock(); * try { * // ... method body * } finally { * lock.unlock(); * } * } * } * </pre> * {@description.close} * * @return {@code true} if current thread holds this lock and * {@code false} otherwise */ public boolean isHeldByCurrentThread() { return sync.isHeldExclusively(); } /** {@collect.stats} * {@description.open} * Queries if this lock is held by any thread. This method is * designed for use in monitoring of the system state, * not for synchronization control. * {@description.close} * * @return {@code true} if any thread holds this lock and * {@code false} otherwise */ public boolean isLocked() { return sync.isLocked(); } /** {@collect.stats} * {@description.open} * Returns {@code true} if this lock has fairness set true. * {@description.close} * * @return {@code true} if this lock has fairness set true */ public final boolean isFair() { return sync instanceof FairSync; } /** {@collect.stats} * {@description.open} * Returns the thread that currently owns this lock, or * {@code null} if not owned. When this method is called by a * thread that is not the owner, the return value reflects a * best-effort approximation of current lock status. For example, * the owner may be momentarily {@code null} even if there are * threads trying to acquire the lock but have not yet done so. * This method is designed to facilitate construction of * subclasses that provide more extensive lock monitoring * facilities. * {@description.close} * * @return the owner, or {@code null} if not owned */ protected Thread getOwner() { return sync.getOwner(); } /** {@collect.stats} * {@description.open} * Queries whether any threads are waiting to acquire this lock. Note that * because cancellations may occur at any time, a {@code true} * return does not guarantee that any other thread will ever * acquire this lock. This method is designed primarily for use in * monitoring of the system state. * {@description.close} * * @return {@code true} if there may be other threads waiting to * acquire the lock */ public final boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } /** {@collect.stats} * {@description.open} * Queries whether the given thread is waiting to acquire this * lock. Note that because cancellations may occur at any time, a * {@code true} return does not guarantee that this thread * will ever acquire this lock. This method is designed primarily for use * in monitoring of the system state. * {@description.close} * * @param thread the thread * @return {@code true} if the given thread is queued waiting for this lock * @throws NullPointerException if the thread is null */ public final boolean hasQueuedThread(Thread thread) { return sync.isQueued(thread); } /** {@collect.stats} * {@description.open} * Returns an estimate of the number of threads waiting to * acquire this lock. The value is only an estimate because the number of * threads may change dynamically while this method traverses * internal data structures. This method is designed for use in * monitoring of the system state, not for synchronization * control. * {@description.close} * * @return the estimated number of threads waiting for this lock */ public final int getQueueLength() { return sync.getQueueLength(); } /** {@collect.stats} * {@description.open} * Returns a collection containing threads that may be waiting to * acquire this lock. Because the actual set of threads may change * dynamically while constructing this result, the returned * collection is only a best-effort estimate. The elements of the * returned collection are in no particular order. This method is * designed to facilitate construction of subclasses that provide * more extensive monitoring facilities. * {@description.close} * * @return the collection of threads */ protected Collection<Thread> getQueuedThreads() { return sync.getQueuedThreads(); } /** {@collect.stats} * {@description.open} * Queries whether any threads are waiting on the given condition * associated with this lock. Note that because timeouts and * interrupts may occur at any time, a {@code true} return does * not guarantee that a future {@code signal} will awaken any * threads. This method is designed primarily for use in * monitoring of the system state. * {@description.close} * * @param condition the condition * @return {@code true} if there are any waiting threads * @throws IllegalMonitorStateException if this lock is not held * @throws IllegalArgumentException if the given condition is * not associated with this lock * @throws NullPointerException if the condition is null */ public boolean hasWaiters(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); } /** {@collect.stats} * {@description.open} * Returns an estimate of the number of threads waiting on the * given condition associated with this lock. Note that because * timeouts and interrupts may occur at any time, the estimate * serves only as an upper bound on the actual number of waiters. * This method is designed for use in monitoring of the system * state, not for synchronization control. * {@description.close} * * @param condition the condition * @return the estimated number of waiting threads * @throws IllegalMonitorStateException if this lock is not held * @throws IllegalArgumentException if the given condition is * not associated with this lock * @throws NullPointerException if the condition is null */ public int getWaitQueueLength(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); } /** {@collect.stats} * {@description.open} * Returns a collection containing those threads that may be * waiting on the given condition associated with this lock. * Because the actual set of threads may change dynamically while * constructing this result, the returned collection is only a * best-effort estimate. The elements of the returned collection * are in no particular order. This method is designed to * facilitate construction of subclasses that provide more * extensive condition monitoring facilities. * {@description.close} * * @param condition the condition * @return the collection of threads * @throws IllegalMonitorStateException if this lock is not held * @throws IllegalArgumentException if the given condition is * not associated with this lock * @throws NullPointerException if the condition is null */ protected Collection<Thread> getWaitingThreads(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition); } /** {@collect.stats} * {@description.open} * Returns a string identifying this lock, as well as its lock state. * The state, in brackets, includes either the String {@code "Unlocked"} * or the String {@code "Locked by"} followed by the * {@linkplain Thread#getName name} of the owning thread. * {@description.close} * * @return a string identifying this lock, as well as its lock state */ public String toString() { Thread o = sync.getOwner(); return super.toString() + ((o == null) ? "[Unlocked]" : "[Locked by thread " + o.getName() + "]"); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.locks; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import sun.misc.Unsafe; /** {@collect.stats} * {@description.open} * A version of {@link AbstractQueuedSynchronizer} in * which synchronization state is maintained as a <tt>long</tt>. * This class has exactly the same structure, properties, and methods * as <tt>AbstractQueuedSynchronizer</tt> with the exception * that all state-related parameters and results are defined * as <tt>long</tt> rather than <tt>int</tt>. This class * may be useful when creating synchronizers such as * multilevel locks and barriers that require * 64 bits of state. * * <p>See {@link AbstractQueuedSynchronizer} for usage * notes and examples. * {@description.close} * * @since 1.6 * @author Doug Lea */ public abstract class AbstractQueuedLongSynchronizer extends AbstractOwnableSynchronizer implements java.io.Serializable { private static final long serialVersionUID = 7373984972572414692L; /* To keep sources in sync, the remainder of this source file is exactly cloned from AbstractQueuedSynchronizer, replacing class name and changing ints related with sync state to longs. Please keep it that way. */ /** {@collect.stats} * {@description.open} * Creates a new <tt>AbstractQueuedLongSynchronizer</tt> instance * with initial synchronization state of zero. * {@description.close} */ protected AbstractQueuedLongSynchronizer() { } /** {@collect.stats} * {@description.open} * Wait queue node class. * * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and * Hagersten) lock queue. CLH locks are normally used for * spinlocks. We instead use them for blocking synchronizers, but * use the same basic tactic of holding some of the control * information about a thread in the predecessor of its node. A * "status" field in each node keeps track of whether a thread * should block. A node is signalled when its predecessor * releases. Each node of the queue otherwise serves as a * specific-notification-style monitor holding a single waiting * thread. The status field does NOT control whether threads are * granted locks etc though. A thread may try to acquire if it is * first in the queue. But being first does not guarantee success; * it only gives the right to contend. So the currently released * contender thread may need to rewait. * * <p>To enqueue into a CLH lock, you atomically splice it in as new * tail. To dequeue, you just set the head field. * <pre> * +------+ prev +-----+ +-----+ * head | | <---- | | <---- | | tail * +------+ +-----+ +-----+ * </pre> * * <p>Insertion into a CLH queue requires only a single atomic * operation on "tail", so there is a simple atomic point of * demarcation from unqueued to queued. Similarly, dequeing * involves only updating the "head". However, it takes a bit * more work for nodes to determine who their successors are, * in part to deal with possible cancellation due to timeouts * and interrupts. * * <p>The "prev" links (not used in original CLH locks), are mainly * needed to handle cancellation. If a node is cancelled, its * successor is (normally) relinked to a non-cancelled * predecessor. For explanation of similar mechanics in the case * of spin locks, see the papers by Scott and Scherer at * http://www.cs.rochester.edu/u/scott/synchronization/ * * <p>We also use "next" links to implement blocking mechanics. * The thread id for each node is kept in its own node, so a * predecessor signals the next node to wake up by traversing * next link to determine which thread it is. Determination of * successor must avoid races with newly queued nodes to set * the "next" fields of their predecessors. This is solved * when necessary by checking backwards from the atomically * updated "tail" when a node's successor appears to be null. * (Or, said differently, the next-links are an optimization * so that we don't usually need a backward scan.) * * <p>Cancellation introduces some conservatism to the basic * algorithms. Since we must poll for cancellation of other * nodes, we can miss noticing whether a cancelled node is * ahead or behind us. This is dealt with by always unparking * successors upon cancellation, allowing them to stabilize on * a new predecessor, unless we can identify an uncancelled * predecessor who will carry this responsibility. * * <p>CLH queues need a dummy header node to get started. But * we don't create them on construction, because it would be wasted * effort if there is never contention. Instead, the node * is constructed and head and tail pointers are set upon first * contention. * * <p>Threads waiting on Conditions use the same nodes, but * use an additional link. Conditions only need to link nodes * in simple (non-concurrent) linked queues because they are * only accessed when exclusively held. Upon await, a node is * inserted into a condition queue. Upon signal, the node is * transferred to the main queue. A special value of status * field is used to mark which queue a node is on. * * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill * Scherer and Michael Scott, along with members of JSR-166 * expert group, for helpful ideas, discussions, and critiques * on the design of this class. * {@description.close} */ static final class Node { /** {@collect.stats} * {@description.open} * Marker to indicate a node is waiting in shared mode * {@description.close} */ static final Node SHARED = new Node(); /** {@collect.stats} * {@description.open} * Marker to indicate a node is waiting in exclusive mode * {@description.close} */ static final Node EXCLUSIVE = null; /** {@collect.stats} * {@description.open} * waitStatus value to indicate thread has cancelled * {@description.close} */ static final int CANCELLED = 1; /** {@collect.stats} * {@description.open} * waitStatus value to indicate successor's thread needs unparking * {@description.close} */ static final int SIGNAL = -1; /** {@collect.stats} * {@description.open} * waitStatus value to indicate thread is waiting on condition * {@description.close} */ static final int CONDITION = -2; /** {@collect.stats} * {@description.open} * waitStatus value to indicate the next acquireShared should * unconditionally propagate * {@description.close} */ static final int PROPAGATE = -3; /** {@collect.stats} * {@description.open} * Status field, taking on only the values: * SIGNAL: The successor of this node is (or will soon be) * blocked (via park), so the current node must * unpark its successor when it releases or * cancels. To avoid races, acquire methods must * first indicate they need a signal, * then retry the atomic acquire, and then, * on failure, block. * CANCELLED: This node is cancelled due to timeout or interrupt. * Nodes never leave this state. In particular, * a thread with cancelled node never again blocks. * CONDITION: This node is currently on a condition queue. * It will not be used as a sync queue node * until transferred, at which time the status * will be set to 0. (Use of this value here has * nothing to do with the other uses of the * field, but simplifies mechanics.) * PROPAGATE: A releaseShared should be propagated to other * nodes. This is set (for head node only) in * doReleaseShared to ensure propagation * continues, even if other operations have * since intervened. * 0: None of the above * * The values are arranged numerically to simplify use. * Non-negative values mean that a node doesn't need to * signal. So, most code doesn't need to check for particular * values, just for sign. * * The field is initialized to 0 for normal sync nodes, and * CONDITION for condition nodes. It is modified using CAS * (or when possible, unconditional volatile writes). * {@description.close} */ volatile int waitStatus; /** {@collect.stats} * {@description.open} * Link to predecessor node that current node/thread relies on * for checking waitStatus. Assigned during enqueing, and nulled * out (for sake of GC) only upon dequeuing. Also, upon * cancellation of a predecessor, we short-circuit while * finding a non-cancelled one, which will always exist * because the head node is never cancelled: A node becomes * head only as a result of successful acquire. A * cancelled thread never succeeds in acquiring, and a thread only * cancels itself, not any other node. * {@description.close} */ volatile Node prev; /** {@collect.stats} * {@description.open} * Link to the successor node that the current node/thread * unparks upon release. Assigned during enqueuing, adjusted * when bypassing cancelled predecessors, and nulled out (for * sake of GC) when dequeued. The enq operation does not * assign next field of a predecessor until after attachment, * so seeing a null next field does not necessarily mean that * node is at end of queue. However, if a next field appears * to be null, we can scan prev's from the tail to * double-check. The next field of cancelled nodes is set to * point to the node itself instead of null, to make life * easier for isOnSyncQueue. * {@description.close} */ volatile Node next; /** {@collect.stats} * {@description.open} * The thread that enqueued this node. Initialized on * construction and nulled out after use. * {@description.close} */ volatile Thread thread; /** {@collect.stats} * {@description.open} * Link to next node waiting on condition, or the special * value SHARED. Because condition queues are accessed only * when holding in exclusive mode, we just need a simple * linked queue to hold nodes while they are waiting on * conditions. They are then transferred to the queue to * re-acquire. And because conditions can only be exclusive, * we save a field by using special value to indicate shared * mode. * {@description.close} */ Node nextWaiter; /** {@collect.stats} * {@description.open} * Returns true if node is waiting in shared mode * {@description.close} */ final boolean isShared() { return nextWaiter == SHARED; } /** {@collect.stats} * {@description.open} * Returns previous node, or throws NullPointerException if null. * Use when predecessor cannot be null. The null check could * be elided, but is present to help the VM. * {@description.close} * * @return the predecessor of this node */ final Node predecessor() throws NullPointerException { Node p = prev; if (p == null) throw new NullPointerException(); else return p; } Node() { // Used to establish initial head or SHARED marker } Node(Thread thread, Node mode) { // Used by addWaiter this.nextWaiter = mode; this.thread = thread; } Node(Thread thread, int waitStatus) { // Used by Condition this.waitStatus = waitStatus; this.thread = thread; } } /** {@collect.stats} * {@description.open} * Head of the wait queue, lazily initialized. Except for * initialization, it is modified only via method setHead. Note: * If head exists, its waitStatus is guaranteed not to be * CANCELLED. * {@description.close} */ private transient volatile Node head; /** {@collect.stats} * {@description.open} * Tail of the wait queue, lazily initialized. Modified only via * method enq to add new wait node. * {@description.close} */ private transient volatile Node tail; /** {@collect.stats} * {@description.open} * The synchronization state. * {@description.close} */ private volatile long state; /** {@collect.stats} * {@description.open} * Returns the current value of synchronization state. * This operation has memory semantics of a <tt>volatile</tt> read. * {@description.close} * @return current state value */ protected final long getState() { return state; } /** {@collect.stats} * {@description.open} * Sets the value of synchronization state. * This operation has memory semantics of a <tt>volatile</tt> write. * {@description.close} * @param newState the new state value */ protected final void setState(long newState) { state = newState; } /** {@collect.stats} * {@description.open} * Atomically sets synchronization state to the given updated * value if the current state value equals the expected value. * This operation has memory semantics of a <tt>volatile</tt> read * and write. * {@description.close} * * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that the actual * value was not equal to the expected value. */ protected final boolean compareAndSetState(long expect, long update) { // See below for intrinsics setup to support this return unsafe.compareAndSwapLong(this, stateOffset, expect, update); } // Queuing utilities /** {@collect.stats} * {@description.open} * The number of nanoseconds for which it is faster to spin * rather than to use timed park. A rough estimate suffices * to improve responsiveness with very short timeouts. * {@description.close} */ static final long spinForTimeoutThreshold = 1000L; /** {@collect.stats} * {@description.open} * Inserts node into queue, initializing if necessary. See picture above. * {@description.close} * @param node the node to insert * @return node's predecessor */ private Node enq(final Node node) { for (;;) { Node t = tail; if (t == null) { // Must initialize if (compareAndSetHead(new Node())) tail = head; } else { node.prev = t; if (compareAndSetTail(t, node)) { t.next = node; return t; } } } } /** {@collect.stats} * {@description.open} * Creates and enqueues node for current thread and given mode. * {@description.close} * * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared * @return the new node */ private Node addWaiter(Node mode) { Node node = new Node(Thread.currentThread(), mode); // Try the fast path of enq; backup to full enq on failure Node pred = tail; if (pred != null) { node.prev = pred; if (compareAndSetTail(pred, node)) { pred.next = node; return node; } } enq(node); return node; } /** {@collect.stats} * {@description.open} * Sets head of queue to be node, thus dequeuing. Called only by * acquire methods. Also nulls out unused fields for sake of GC * and to suppress unnecessary signals and traversals. * {@description.close} * * @param node the node */ private void setHead(Node node) { head = node; node.thread = null; node.prev = null; } /** {@collect.stats} * {@description.open} * Wakes up node's successor, if one exists. * {@description.close} * * @param node the node */ private void unparkSuccessor(Node node) { /* * If status is negative (i.e., possibly needing signal) try * to clear in anticipation of signalling. It is OK if this * fails or if status is changed by waiting thread. */ int ws = node.waitStatus; if (ws < 0) compareAndSetWaitStatus(node, ws, 0); /* * Thread to unpark is held in successor, which is normally * just the next node. But if cancelled or apparently null, * traverse backwards from tail to find the actual * non-cancelled successor. */ Node s = node.next; if (s == null || s.waitStatus > 0) { s = null; for (Node t = tail; t != null && t != node; t = t.prev) if (t.waitStatus <= 0) s = t; } if (s != null) LockSupport.unpark(s.thread); } /** {@collect.stats} * {@description.open} * Release action for shared mode -- signal successor and ensure * propagation. (Note: For exclusive mode, release just amounts * to calling unparkSuccessor of head if it needs signal.) * {@description.close} */ private void doReleaseShared() { /* * Ensure that a release propagates, even if there are other * in-progress acquires/releases. This proceeds in the usual * way of trying to unparkSuccessor of head if it needs * signal. But if it does not, status is set to PROPAGATE to * ensure that upon release, propagation continues. * Additionally, we must loop in case a new node is added * while we are doing this. Also, unlike other uses of * unparkSuccessor, we need to know if CAS to reset status * fails, if so rechecking. */ for (;;) { Node h = head; if (h != null && h != tail) { int ws = h.waitStatus; if (ws == Node.SIGNAL) { if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) continue; // loop to recheck cases unparkSuccessor(h); } else if (ws == 0 && !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) continue; // loop on failed CAS } if (h == head) // loop if head changed break; } } /** {@collect.stats} * {@description.open} * Sets head of queue, and checks if successor may be waiting * in shared mode, if so propagating if either propagate > 0 or * PROPAGATE status was set. * {@description.close} * * @param node the node * @param propagate the return value from a tryAcquireShared */ private void setHeadAndPropagate(Node node, long propagate) { Node h = head; // Record old head for check below setHead(node); /* * Try to signal next queued node if: * Propagation was indicated by caller, * or was recorded (as h.waitStatus) by a previous operation * (note: this uses sign-check of waitStatus because * PROPAGATE status may transition to SIGNAL.) * and * The next node is waiting in shared mode, * or we don't know, because it appears null * * The conservatism in both of these checks may cause * unnecessary wake-ups, but only when there are multiple * racing acquires/releases, so most need signals now or soon * anyway. */ if (propagate > 0 || h == null || h.waitStatus < 0) { Node s = node.next; if (s == null || s.isShared()) doReleaseShared(); } } // Utilities for various versions of acquire /** {@collect.stats} * {@description.open} * Cancels an ongoing attempt to acquire. * {@description.close} * * @param node the node */ private void cancelAcquire(Node node) { // Ignore if node doesn't exist if (node == null) return; node.thread = null; // Skip cancelled predecessors Node pred = node.prev; while (pred.waitStatus > 0) node.prev = pred = pred.prev; // predNext is the apparent node to unsplice. CASes below will // fail if not, in which case, we lost race vs another cancel // or signal, so no further action is necessary. Node predNext = pred.next; // Can use unconditional write instead of CAS here. // After this atomic step, other Nodes can skip past us. // Before, we are free of interference from other threads. node.waitStatus = Node.CANCELLED; // If we are the tail, remove ourselves. if (node == tail && compareAndSetTail(node, pred)) { compareAndSetNext(pred, predNext, null); } else { // If successor needs signal, try to set pred's next-link // so it will get one. Otherwise wake it up to propagate. int ws; if (pred != head && ((ws = pred.waitStatus) == Node.SIGNAL || (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) && pred.thread != null) { Node next = node.next; if (next != null && next.waitStatus <= 0) compareAndSetNext(pred, predNext, next); } else { unparkSuccessor(node); } node.next = node; // help GC } } /** {@collect.stats} * {@description.open} * Checks and updates status for a node that failed to acquire. * Returns true if thread should block. This is the main signal * control in all acquire loops. Requires that pred == node.prev * {@description.close} * * @param pred node's predecessor holding status * @param node the node * @return {@code true} if thread should block */ private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { int ws = pred.waitStatus; if (ws == Node.SIGNAL) /* * This node has already set status asking a release * to signal it, so it can safely park. */ return true; if (ws > 0) { /* * Predecessor was cancelled. Skip over predecessors and * indicate retry. */ do { node.prev = pred = pred.prev; } while (pred.waitStatus > 0); pred.next = node; } else { /* * waitStatus must be 0 or PROPAGATE. Indicate that we * need a signal, but don't park yet. Caller will need to * retry to make sure it cannot acquire before parking. */ compareAndSetWaitStatus(pred, ws, Node.SIGNAL); } return false; } /** {@collect.stats} * {@description.open} * Convenience method to interrupt current thread. * {@description.close} */ private static void selfInterrupt() { Thread.currentThread().interrupt(); } /** {@collect.stats} * {@description.open} * Convenience method to park and then check if interrupted * {@description.close} * * @return {@code true} if interrupted */ private final boolean parkAndCheckInterrupt() { LockSupport.park(this); return Thread.interrupted(); } /* * Various flavors of acquire, varying in exclusive/shared and * control modes. Each is mostly the same, but annoyingly * different. Only a little bit of factoring is possible due to * interactions of exception mechanics (including ensuring that we * cancel if tryAcquire throws exception) and other control, at * least not without hurting performance too much. */ /** {@collect.stats} * {@description.open} * Acquires in exclusive uninterruptible mode for thread already in * queue. Used by condition wait methods as well as acquire. * {@description.close} * * @param node the node * @param arg the acquire argument * @return {@code true} if interrupted while waiting */ final boolean acquireQueued(final Node node, long arg) { boolean failed = true; try { boolean interrupted = false; for (;;) { final Node p = node.predecessor(); if (p == head && tryAcquire(arg)) { setHead(node); p.next = null; // help GC failed = false; return interrupted; } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true; } } finally { if (failed) cancelAcquire(node); } } /** {@collect.stats} * {@description.open} * Acquires in exclusive interruptible mode. * {@description.close} * @param arg the acquire argument */ private void doAcquireInterruptibly(long arg) throws InterruptedException { final Node node = addWaiter(Node.EXCLUSIVE); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head && tryAcquire(arg)) { setHead(node); p.next = null; // help GC failed = false; return; } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } /** {@collect.stats} * {@description.open} * Acquires in exclusive timed mode. * {@description.close} * * @param arg the acquire argument * @param nanosTimeout max wait time * @return {@code true} if acquired */ private boolean doAcquireNanos(long arg, long nanosTimeout) throws InterruptedException { long lastTime = System.nanoTime(); final Node node = addWaiter(Node.EXCLUSIVE); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head && tryAcquire(arg)) { setHead(node); p.next = null; // help GC failed = false; return true; } if (nanosTimeout <= 0) return false; if (shouldParkAfterFailedAcquire(p, node) && nanosTimeout > spinForTimeoutThreshold) LockSupport.parkNanos(this, nanosTimeout); long now = System.nanoTime(); nanosTimeout -= now - lastTime; lastTime = now; if (Thread.interrupted()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } /** {@collect.stats} * {@description.open} * Acquires in shared uninterruptible mode. * {@description.close} * @param arg the acquire argument */ private void doAcquireShared(long arg) { final Node node = addWaiter(Node.SHARED); boolean failed = true; try { boolean interrupted = false; for (;;) { final Node p = node.predecessor(); if (p == head) { long r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC if (interrupted) selfInterrupt(); failed = false; return; } } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true; } } finally { if (failed) cancelAcquire(node); } } /** {@collect.stats} * {@description.open} * Acquires in shared interruptible mode. * {@description.close} * @param arg the acquire argument */ private void doAcquireSharedInterruptibly(long arg) throws InterruptedException { final Node node = addWaiter(Node.SHARED); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head) { long r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return; } } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } /** {@collect.stats} * {@description.open} * Acquires in shared timed mode. * {@description.close} * * @param arg the acquire argument * @param nanosTimeout max wait time * @return {@code true} if acquired */ private boolean doAcquireSharedNanos(long arg, long nanosTimeout) throws InterruptedException { long lastTime = System.nanoTime(); final Node node = addWaiter(Node.SHARED); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head) { long r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return true; } } if (nanosTimeout <= 0) return false; if (shouldParkAfterFailedAcquire(p, node) && nanosTimeout > spinForTimeoutThreshold) LockSupport.parkNanos(this, nanosTimeout); long now = System.nanoTime(); nanosTimeout -= now - lastTime; lastTime = now; if (Thread.interrupted()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } // Main exported methods /** {@collect.stats} * {@description.open} * Attempts to acquire in exclusive mode. This method should query * if the state of the object permits it to be acquired in the * exclusive mode, and if so to acquire it. * * <p>This method is always invoked by the thread performing * acquire. If this method reports failure, the acquire method * may queue the thread, if it is not already queued, until it is * signalled by a release from some other thread. This can be used * to implement method {@link Lock#tryLock()}. * * <p>The default * implementation throws {@link UnsupportedOperationException}. * {@description.close} * * @param arg the acquire argument. This value is always the one * passed to an acquire method, or is the value saved on entry * to a condition wait. The value is otherwise uninterpreted * and can represent anything you like. * @return {@code true} if successful. Upon success, this object has * been acquired. * @throws IllegalMonitorStateException if acquiring would place this * synchronizer in an illegal state. This exception must be * thrown in a consistent fashion for synchronization to work * correctly. * @throws UnsupportedOperationException if exclusive mode is not supported */ protected boolean tryAcquire(long arg) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Attempts to set the state to reflect a release in exclusive * mode. * * <p>This method is always invoked by the thread performing release. * * <p>The default implementation throws * {@link UnsupportedOperationException}. * {@description.close} * * @param arg the release argument. This value is always the one * passed to a release method, or the current state value upon * entry to a condition wait. The value is otherwise * uninterpreted and can represent anything you like. * @return {@code true} if this object is now in a fully released * state, so that any waiting threads may attempt to acquire; * and {@code false} otherwise. * @throws IllegalMonitorStateException if releasing would place this * synchronizer in an illegal state. This exception must be * thrown in a consistent fashion for synchronization to work * correctly. * @throws UnsupportedOperationException if exclusive mode is not supported */ protected boolean tryRelease(long arg) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Attempts to acquire in shared mode. This method should query if * the state of the object permits it to be acquired in the shared * mode, and if so to acquire it. * * <p>This method is always invoked by the thread performing * acquire. If this method reports failure, the acquire method * may queue the thread, if it is not already queued, until it is * signalled by a release from some other thread. * * <p>The default implementation throws {@link * UnsupportedOperationException}. * {@description.close} * * @param arg the acquire argument. This value is always the one * passed to an acquire method, or is the value saved on entry * to a condition wait. The value is otherwise uninterpreted * and can represent anything you like. * @return a negative value on failure; zero if acquisition in shared * mode succeeded but no subsequent shared-mode acquire can * succeed; and a positive value if acquisition in shared * mode succeeded and subsequent shared-mode acquires might * also succeed, in which case a subsequent waiting thread * must check availability. (Support for three different * return values enables this method to be used in contexts * where acquires only sometimes act exclusively.) Upon * success, this object has been acquired. * @throws IllegalMonitorStateException if acquiring would place this * synchronizer in an illegal state. This exception must be * thrown in a consistent fashion for synchronization to work * correctly. * @throws UnsupportedOperationException if shared mode is not supported */ protected long tryAcquireShared(long arg) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Attempts to set the state to reflect a release in shared mode. * * <p>This method is always invoked by the thread performing release. * * <p>The default implementation throws * {@link UnsupportedOperationException}. * {@description.close} * * @param arg the release argument. This value is always the one * passed to a release method, or the current state value upon * entry to a condition wait. The value is otherwise * uninterpreted and can represent anything you like. * @return {@code true} if this release of shared mode may permit a * waiting acquire (shared or exclusive) to succeed; and * {@code false} otherwise * @throws IllegalMonitorStateException if releasing would place this * synchronizer in an illegal state. This exception must be * thrown in a consistent fashion for synchronization to work * correctly. * @throws UnsupportedOperationException if shared mode is not supported */ protected boolean tryReleaseShared(long arg) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Returns {@code true} if synchronization is held exclusively with * respect to the current (calling) thread. This method is invoked * upon each call to a non-waiting {@link ConditionObject} method. * (Waiting methods instead invoke {@link #release}.) * * <p>The default implementation throws {@link * UnsupportedOperationException}. This method is invoked * internally only within {@link ConditionObject} methods, so need * not be defined if conditions are not used. * {@description.close} * * @return {@code true} if synchronization is held exclusively; * {@code false} otherwise * @throws UnsupportedOperationException if conditions are not supported */ protected boolean isHeldExclusively() { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Acquires in exclusive mode, ignoring interrupts. Implemented * by invoking at least once {@link #tryAcquire}, * returning on success. Otherwise the thread is queued, possibly * repeatedly blocking and unblocking, invoking {@link * #tryAcquire} until success. This method can be used * to implement method {@link Lock#lock}. * {@description.close} * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquire} but is otherwise uninterpreted and * can represent anything you like. */ public final void acquire(long arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } /** {@collect.stats} * {@description.open} * Acquires in exclusive mode, aborting if interrupted. * Implemented by first checking interrupt status, then invoking * at least once {@link #tryAcquire}, returning on * success. Otherwise the thread is queued, possibly repeatedly * blocking and unblocking, invoking {@link #tryAcquire} * until success or the thread is interrupted. This method can be * used to implement method {@link Lock#lockInterruptibly}. * {@description.close} * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquire} but is otherwise uninterpreted and * can represent anything you like. * @throws InterruptedException if the current thread is interrupted */ public final void acquireInterruptibly(long arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (!tryAcquire(arg)) doAcquireInterruptibly(arg); } /** {@collect.stats} * {@description.open} * Attempts to acquire in exclusive mode, aborting if interrupted, * and failing if the given timeout elapses. Implemented by first * checking interrupt status, then invoking at least once {@link * #tryAcquire}, returning on success. Otherwise, the thread is * queued, possibly repeatedly blocking and unblocking, invoking * {@link #tryAcquire} until success or the thread is interrupted * or the timeout elapses. This method can be used to implement * method {@link Lock#tryLock(long, TimeUnit)}. * {@description.close} * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquire} but is otherwise uninterpreted and * can represent anything you like. * @param nanosTimeout the maximum number of nanoseconds to wait * @return {@code true} if acquired; {@code false} if timed out * @throws InterruptedException if the current thread is interrupted */ public final boolean tryAcquireNanos(long arg, long nanosTimeout) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); return tryAcquire(arg) || doAcquireNanos(arg, nanosTimeout); } /** {@collect.stats} * {@description.open} * Releases in exclusive mode. Implemented by unblocking one or * more threads if {@link #tryRelease} returns true. * This method can be used to implement method {@link Lock#unlock}. * {@description.close} * * @param arg the release argument. This value is conveyed to * {@link #tryRelease} but is otherwise uninterpreted and * can represent anything you like. * @return the value returned from {@link #tryRelease} */ public final boolean release(long arg) { if (tryRelease(arg)) { Node h = head; if (h != null && h.waitStatus != 0) unparkSuccessor(h); return true; } return false; } /** {@collect.stats} * {@description.open} * Acquires in shared mode, ignoring interrupts. Implemented by * first invoking at least once {@link #tryAcquireShared}, * returning on success. Otherwise the thread is queued, possibly * repeatedly blocking and unblocking, invoking {@link * #tryAcquireShared} until success. * {@description.close} * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquireShared} but is otherwise uninterpreted * and can represent anything you like. */ public final void acquireShared(long arg) { if (tryAcquireShared(arg) < 0) doAcquireShared(arg); } /** {@collect.stats} * {@description.open} * Acquires in shared mode, aborting if interrupted. Implemented * by first checking interrupt status, then invoking at least once * {@link #tryAcquireShared}, returning on success. Otherwise the * thread is queued, possibly repeatedly blocking and unblocking, * invoking {@link #tryAcquireShared} until success or the thread * is interrupted. * {@description.close} * @param arg the acquire argument * This value is conveyed to {@link #tryAcquireShared} but is * otherwise uninterpreted and can represent anything * you like. * @throws InterruptedException if the current thread is interrupted */ public final void acquireSharedInterruptibly(long arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (tryAcquireShared(arg) < 0) doAcquireSharedInterruptibly(arg); } /** {@collect.stats} * {@description.open} * Attempts to acquire in shared mode, aborting if interrupted, and * failing if the given timeout elapses. Implemented by first * checking interrupt status, then invoking at least once {@link * #tryAcquireShared}, returning on success. Otherwise, the * thread is queued, possibly repeatedly blocking and unblocking, * invoking {@link #tryAcquireShared} until success or the thread * is interrupted or the timeout elapses. * {@description.close} * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquireShared} but is otherwise uninterpreted * and can represent anything you like. * @param nanosTimeout the maximum number of nanoseconds to wait * @return {@code true} if acquired; {@code false} if timed out * @throws InterruptedException if the current thread is interrupted */ public final boolean tryAcquireSharedNanos(long arg, long nanosTimeout) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); return tryAcquireShared(arg) >= 0 || doAcquireSharedNanos(arg, nanosTimeout); } /** {@collect.stats} * {@description.open} * Releases in shared mode. Implemented by unblocking one or more * threads if {@link #tryReleaseShared} returns true. * {@description.close} * * @param arg the release argument. This value is conveyed to * {@link #tryReleaseShared} but is otherwise uninterpreted * and can represent anything you like. * @return the value returned from {@link #tryReleaseShared} */ public final boolean releaseShared(long arg) { if (tryReleaseShared(arg)) { doReleaseShared(); return true; } return false; } // Queue inspection methods /** {@collect.stats} * {@description.open} * Queries whether any threads are waiting to acquire. Note that * because cancellations due to interrupts and timeouts may occur * at any time, a {@code true} return does not guarantee that any * other thread will ever acquire. * * <p>In this implementation, this operation returns in * constant time. * {@description.close} * * @return {@code true} if there may be other threads waiting to acquire */ public final boolean hasQueuedThreads() { return head != tail; } /** {@collect.stats} * {@description.open} * Queries whether any threads have ever contended to acquire this * synchronizer; that is if an acquire method has ever blocked. * * <p>In this implementation, this operation returns in * constant time. * {@description.close} * * @return {@code true} if there has ever been contention */ public final boolean hasContended() { return head != null; } /** {@collect.stats} * {@description.open} * Returns the first (longest-waiting) thread in the queue, or * {@code null} if no threads are currently queued. * * <p>In this implementation, this operation normally returns in * constant time, but may iterate upon contention if other threads are * concurrently modifying the queue. * {@description.close} * * @return the first (longest-waiting) thread in the queue, or * {@code null} if no threads are currently queued */ public final Thread getFirstQueuedThread() { // handle only fast path, else relay return (head == tail) ? null : fullGetFirstQueuedThread(); } /** {@collect.stats} * {@description.open} * Version of getFirstQueuedThread called when fastpath fails * {@description.close} */ private Thread fullGetFirstQueuedThread() { /* * The first node is normally head.next. Try to get its * thread field, ensuring consistent reads: If thread * field is nulled out or s.prev is no longer head, then * some other thread(s) concurrently performed setHead in * between some of our reads. We try this twice before * resorting to traversal. */ Node h, s; Thread st; if (((h = head) != null && (s = h.next) != null && s.prev == head && (st = s.thread) != null) || ((h = head) != null && (s = h.next) != null && s.prev == head && (st = s.thread) != null)) return st; /* * Head's next field might not have been set yet, or may have * been unset after setHead. So we must check to see if tail * is actually first node. If not, we continue on, safely * traversing from tail back to head to find first, * guaranteeing termination. */ Node t = tail; Thread firstThread = null; while (t != null && t != head) { Thread tt = t.thread; if (tt != null) firstThread = tt; t = t.prev; } return firstThread; } /** {@collect.stats} * {@description.open} * Returns true if the given thread is currently queued. * * <p>This implementation traverses the queue to determine * presence of the given thread. * {@description.close} * * @param thread the thread * @return {@code true} if the given thread is on the queue * @throws NullPointerException if the thread is null */ public final boolean isQueued(Thread thread) { if (thread == null) throw new NullPointerException(); for (Node p = tail; p != null; p = p.prev) if (p.thread == thread) return true; return false; } /** {@collect.stats} * {@description.open} * Returns {@code true} if the apparent first queued thread, if one * exists, is waiting in exclusive mode. If this method returns * {@code true}, and the current thread is attempting to acquire in * shared mode (that is, this method is invoked from {@link * #tryAcquireShared}) then it is guaranteed that the current thread * is not the first queued thread. Used only as a heuristic in * ReentrantReadWriteLock. * {@description.close} */ final boolean apparentlyFirstQueuedIsExclusive() { Node h, s; return (h = head) != null && (s = h.next) != null && !s.isShared() && s.thread != null; } /** {@collect.stats} * {@description.open} * Queries whether any threads have been waiting to acquire longer * than the current thread. * * <p>An invocation of this method is equivalent to (but may be * more efficient than): * <pre> {@code * getFirstQueuedThread() != Thread.currentThread() && * hasQueuedThreads()}</pre> * * <p>Note that because cancellations due to interrupts and * timeouts may occur at any time, a {@code true} return does not * guarantee that some other thread will acquire before the current * thread. Likewise, it is possible for another thread to win a * race to enqueue after this method has returned {@code false}, * due to the queue being empty. * * <p>This method is designed to be used by a fair synchronizer to * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>. * Such a synchronizer's {@link #tryAcquire} method should return * {@code false}, and its {@link #tryAcquireShared} method should * return a negative value, if this method returns {@code true} * (unless this is a reentrant acquire). For example, the {@code * tryAcquire} method for a fair, reentrant, exclusive mode * synchronizer might look like this: * * <pre> {@code * protected boolean tryAcquire(int arg) { * if (isHeldExclusively()) { * // A reentrant acquire; increment hold count * return true; * } else if (hasQueuedPredecessors()) { * return false; * } else { * // try to acquire normally * } * }}</pre> * {@description.close} * * @return {@code true} if there is a queued thread preceding the * current thread, and {@code false} if the current thread * is at the head of the queue or the queue is empty * @since 1.7 */ final boolean hasQueuedPredecessors() { // The correctness of this depends on head being initialized // before tail and on head.next being accurate if the current // thread is first in queue. Node t = tail; // Read fields in reverse initialization order Node h = head; Node s; return h != t && ((s = h.next) == null || s.thread != Thread.currentThread()); } // Instrumentation and monitoring methods /** {@collect.stats} * {@description.open} * Returns an estimate of the number of threads waiting to * acquire. The value is only an estimate because the number of * threads may change dynamically while this method traverses * internal data structures. This method is designed for use in * monitoring system state, not for synchronization * control. * {@description.close} * * @return the estimated number of threads waiting to acquire */ public final int getQueueLength() { int n = 0; for (Node p = tail; p != null; p = p.prev) { if (p.thread != null) ++n; } return n; } /** {@collect.stats} * {@description.open} * Returns a collection containing threads that may be waiting to * acquire. Because the actual set of threads may change * dynamically while constructing this result, the returned * collection is only a best-effort estimate. The elements of the * returned collection are in no particular order. This method is * designed to facilitate construction of subclasses that provide * more extensive monitoring facilities. * {@description.close} * * @return the collection of threads */ public final Collection<Thread> getQueuedThreads() { ArrayList<Thread> list = new ArrayList<Thread>(); for (Node p = tail; p != null; p = p.prev) { Thread t = p.thread; if (t != null) list.add(t); } return list; } /** {@collect.stats} * {@description.open} * Returns a collection containing threads that may be waiting to * acquire in exclusive mode. This has the same properties * as {@link #getQueuedThreads} except that it only returns * those threads waiting due to an exclusive acquire. * {@description.close} * * @return the collection of threads */ public final Collection<Thread> getExclusiveQueuedThreads() { ArrayList<Thread> list = new ArrayList<Thread>(); for (Node p = tail; p != null; p = p.prev) { if (!p.isShared()) { Thread t = p.thread; if (t != null) list.add(t); } } return list; } /** {@collect.stats} * {@description.open} * Returns a collection containing threads that may be waiting to * acquire in shared mode. This has the same properties * as {@link #getQueuedThreads} except that it only returns * those threads waiting due to a shared acquire. * {@description.close} * * @return the collection of threads */ public final Collection<Thread> getSharedQueuedThreads() { ArrayList<Thread> list = new ArrayList<Thread>(); for (Node p = tail; p != null; p = p.prev) { if (p.isShared()) { Thread t = p.thread; if (t != null) list.add(t); } } return list; } /** {@collect.stats} * {@description.open} * Returns a string identifying this synchronizer, as well as its state. * The state, in brackets, includes the String {@code "State ="} * followed by the current value of {@link #getState}, and either * {@code "nonempty"} or {@code "empty"} depending on whether the * queue is empty. * {@description.close} * * @return a string identifying this synchronizer, as well as its state */ public String toString() { long s = getState(); String q = hasQueuedThreads() ? "non" : ""; return super.toString() + "[State = " + s + ", " + q + "empty queue]"; } // Internal support methods for Conditions /** {@collect.stats} * {@description.open} * Returns true if a node, always one that was initially placed on * a condition queue, is now waiting to reacquire on sync queue. * {@description.close} * @param node the node * @return true if is reacquiring */ final boolean isOnSyncQueue(Node node) { if (node.waitStatus == Node.CONDITION || node.prev == null) return false; if (node.next != null) // If has successor, it must be on queue return true; /* * node.prev can be non-null, but not yet on queue because * the CAS to place it on queue can fail. So we have to * traverse from tail to make sure it actually made it. It * will always be near the tail in calls to this method, and * unless the CAS failed (which is unlikely), it will be * there, so we hardly ever traverse much. */ return findNodeFromTail(node); } /** {@collect.stats} * {@description.open} * Returns true if node is on sync queue by searching backwards from tail. * Called only when needed by isOnSyncQueue. * {@description.close} * @return true if present */ private boolean findNodeFromTail(Node node) { Node t = tail; for (;;) { if (t == node) return true; if (t == null) return false; t = t.prev; } } /** {@collect.stats} * {@description.open} * Transfers a node from a condition queue onto sync queue. * Returns true if successful. * {@description.close} * @param node the node * @return true if successfully transferred (else the node was * cancelled before signal). */ final boolean transferForSignal(Node node) { /* * If cannot change waitStatus, the node has been cancelled. */ if (!compareAndSetWaitStatus(node, Node.CONDITION, 0)) return false; /* * Splice onto queue and try to set waitStatus of predecessor to * indicate that thread is (probably) waiting. If cancelled or * attempt to set waitStatus fails, wake up to resync (in which * case the waitStatus can be transiently and harmlessly wrong). */ Node p = enq(node); int ws = p.waitStatus; if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)) LockSupport.unpark(node.thread); return true; } /** {@collect.stats} * {@description.open} * Transfers node, if necessary, to sync queue after a cancelled * wait. Returns true if thread was cancelled before being * signalled. * {@description.close} * @param current the waiting thread * @param node its node * @return true if cancelled before the node was signalled */ final boolean transferAfterCancelledWait(Node node) { if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) { enq(node); return true; } /* * If we lost out to a signal(), then we can't proceed * until it finishes its enq(). Cancelling during an * incomplete transfer is both rare and transient, so just * spin. */ while (!isOnSyncQueue(node)) Thread.yield(); return false; } /** {@collect.stats} * {@description.open} * Invokes release with current state value; returns saved state. * Cancels node and throws exception on failure. * {@description.close} * @param node the condition node for this wait * @return previous sync state */ final long fullyRelease(Node node) { boolean failed = true; try { long savedState = getState(); if (release(savedState)) { failed = false; return savedState; } else { throw new IllegalMonitorStateException(); } } finally { if (failed) node.waitStatus = Node.CANCELLED; } } // Instrumentation methods for conditions /** {@collect.stats} * {@description.open} * Queries whether the given ConditionObject * uses this synchronizer as its lock. * {@description.close} * * @param condition the condition * @return <tt>true</tt> if owned * @throws NullPointerException if the condition is null */ public final boolean owns(ConditionObject condition) { if (condition == null) throw new NullPointerException(); return condition.isOwnedBy(this); } /** {@collect.stats} * {@description.open} * Queries whether any threads are waiting on the given condition * associated with this synchronizer. Note that because timeouts * and interrupts may occur at any time, a <tt>true</tt> return * does not guarantee that a future <tt>signal</tt> will awaken * any threads. This method is designed primarily for use in * monitoring of the system state. * {@description.close} * * @param condition the condition * @return <tt>true</tt> if there are any waiting threads * @throws IllegalMonitorStateException if exclusive synchronization * is not held * @throws IllegalArgumentException if the given condition is * not associated with this synchronizer * @throws NullPointerException if the condition is null */ public final boolean hasWaiters(ConditionObject condition) { if (!owns(condition)) throw new IllegalArgumentException("Not owner"); return condition.hasWaiters(); } /** {@collect.stats} * {@description.open} * Returns an estimate of the number of threads waiting on the * given condition associated with this synchronizer. Note that * because timeouts and interrupts may occur at any time, the * estimate serves only as an upper bound on the actual number of * waiters. This method is designed for use in monitoring of the * system state, not for synchronization control. * {@description.close} * * @param condition the condition * @return the estimated number of waiting threads * @throws IllegalMonitorStateException if exclusive synchronization * is not held * @throws IllegalArgumentException if the given condition is * not associated with this synchronizer * @throws NullPointerException if the condition is null */ public final int getWaitQueueLength(ConditionObject condition) { if (!owns(condition)) throw new IllegalArgumentException("Not owner"); return condition.getWaitQueueLength(); } /** {@collect.stats} * {@description.open} * Returns a collection containing those threads that may be * waiting on the given condition associated with this * synchronizer. Because the actual set of threads may change * dynamically while constructing this result, the returned * collection is only a best-effort estimate. The elements of the * returned collection are in no particular order. * {@description.close} * * @param condition the condition * @return the collection of threads * @throws IllegalMonitorStateException if exclusive synchronization * is not held * @throws IllegalArgumentException if the given condition is * not associated with this synchronizer * @throws NullPointerException if the condition is null */ public final Collection<Thread> getWaitingThreads(ConditionObject condition) { if (!owns(condition)) throw new IllegalArgumentException("Not owner"); return condition.getWaitingThreads(); } /** {@collect.stats} * {@description.open} * Condition implementation for a {@link * AbstractQueuedLongSynchronizer} serving as the basis of a {@link * Lock} implementation. * * <p>Method documentation for this class describes mechanics, * not behavioral specifications from the point of view of Lock * and Condition users. Exported versions of this class will in * general need to be accompanied by documentation describing * condition semantics that rely on those of the associated * <tt>AbstractQueuedLongSynchronizer</tt>. * * <p>This class is Serializable, but all fields are transient, * so deserialized conditions have no waiters. * {@description.close} * * @since 1.6 */ public class ConditionObject implements Condition, java.io.Serializable { private static final long serialVersionUID = 1173984872572414699L; /** {@collect.stats} * {@description.open} * First node of condition queue. * {@description.close} */ private transient Node firstWaiter; /** {@collect.stats} * {@description.open} * Last node of condition queue. * {@description.close} */ private transient Node lastWaiter; /** {@collect.stats} * {@description.open} * Creates a new <tt>ConditionObject</tt> instance. * {@description.close} */ public ConditionObject() { } // Internal methods /** {@collect.stats} * {@description.open} * Adds a new waiter to wait queue. * {@description.close} * @return its new wait node */ private Node addConditionWaiter() { Node t = lastWaiter; // If lastWaiter is cancelled, clean out. if (t != null && t.waitStatus != Node.CONDITION) { unlinkCancelledWaiters(); t = lastWaiter; } Node node = new Node(Thread.currentThread(), Node.CONDITION); if (t == null) firstWaiter = node; else t.nextWaiter = node; lastWaiter = node; return node; } /** {@collect.stats} * {@description.open} * Removes and transfers nodes until hit non-cancelled one or * null. Split out from signal in part to encourage compilers * to inline the case of no waiters. * {@description.close} * @param first (non-null) the first node on condition queue */ private void doSignal(Node first) { do { if ( (firstWaiter = first.nextWaiter) == null) lastWaiter = null; first.nextWaiter = null; } while (!transferForSignal(first) && (first = firstWaiter) != null); } /** {@collect.stats} * {@description.open} * Removes and transfers all nodes. * {@description.close} * @param first (non-null) the first node on condition queue */ private void doSignalAll(Node first) { lastWaiter = firstWaiter = null; do { Node next = first.nextWaiter; first.nextWaiter = null; transferForSignal(first); first = next; } while (first != null); } /** {@collect.stats} * {@description.open} * Unlinks cancelled waiter nodes from condition queue. * Called only while holding lock. This is called when * cancellation occurred during condition wait, and upon * insertion of a new waiter when lastWaiter is seen to have * been cancelled. This method is needed to avoid garbage * retention in the absence of signals. So even though it may * require a full traversal, it comes into play only when * timeouts or cancellations occur in the absence of * signals. It traverses all nodes rather than stopping at a * particular target to unlink all pointers to garbage nodes * without requiring many re-traversals during cancellation * storms. * {@description.close} */ private void unlinkCancelledWaiters() { Node t = firstWaiter; Node trail = null; while (t != null) { Node next = t.nextWaiter; if (t.waitStatus != Node.CONDITION) { t.nextWaiter = null; if (trail == null) firstWaiter = next; else trail.nextWaiter = next; if (next == null) lastWaiter = trail; } else trail = t; t = next; } } // public methods /** {@collect.stats} * {@description.open} * Moves the longest-waiting thread, if one exists, from the * wait queue for this condition to the wait queue for the * owning lock. * {@description.close} * * @throws IllegalMonitorStateException if {@link #isHeldExclusively} * returns {@code false} */ public final void signal() { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); Node first = firstWaiter; if (first != null) doSignal(first); } /** {@collect.stats} * {@description.open} * Moves all threads from the wait queue for this condition to * the wait queue for the owning lock. * {@description.close} * * @throws IllegalMonitorStateException if {@link #isHeldExclusively} * returns {@code false} */ public final void signalAll() { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); Node first = firstWaiter; if (first != null) doSignalAll(first); } /** {@collect.stats} * {@description.open} * Implements uninterruptible condition wait. * <ol> * <li> Save lock state returned by {@link #getState}. * <li> Invoke {@link #release} with * saved state as argument, throwing * IllegalMonitorStateException if it fails. * <li> Block until signalled. * <li> Reacquire by invoking specialized version of * {@link #acquire} with saved state as argument. * </ol> * {@description.close} */ public final void awaitUninterruptibly() { Node node = addConditionWaiter(); long savedState = fullyRelease(node); boolean interrupted = false; while (!isOnSyncQueue(node)) { LockSupport.park(this); if (Thread.interrupted()) interrupted = true; } if (acquireQueued(node, savedState) || interrupted) selfInterrupt(); } /* * For interruptible waits, we need to track whether to throw * InterruptedException, if interrupted while blocked on * condition, versus reinterrupt current thread, if * interrupted while blocked waiting to re-acquire. */ /** {@collect.stats} * {@description.open} * Mode meaning to reinterrupt on exit from wait * {@description.close} */ private static final int REINTERRUPT = 1; /** {@collect.stats} * {@description.open} * Mode meaning to throw InterruptedException on exit from wait * {@description.close} */ private static final int THROW_IE = -1; /** {@collect.stats} * {@description.open} * Checks for interrupt, returning THROW_IE if interrupted * before signalled, REINTERRUPT if after signalled, or * 0 if not interrupted. * {@description.close} */ private int checkInterruptWhileWaiting(Node node) { return Thread.interrupted() ? (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) : 0; } /** {@collect.stats} * {@description.open} * Throws InterruptedException, reinterrupts current thread, or * does nothing, depending on mode. * {@description.close} */ private void reportInterruptAfterWait(int interruptMode) throws InterruptedException { if (interruptMode == THROW_IE) throw new InterruptedException(); else if (interruptMode == REINTERRUPT) selfInterrupt(); } /** {@collect.stats} * {@description.open} * Implements interruptible condition wait. * <ol> * <li> If current thread is interrupted, throw InterruptedException. * <li> Save lock state returned by {@link #getState}. * <li> Invoke {@link #release} with * saved state as argument, throwing * IllegalMonitorStateException if it fails. * <li> Block until signalled or interrupted. * <li> Reacquire by invoking specialized version of * {@link #acquire} with saved state as argument. * <li> If interrupted while blocked in step 4, throw InterruptedException. * </ol> * {@description.close} */ public final void await() throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); long savedState = fullyRelease(node); int interruptMode = 0; while (!isOnSyncQueue(node)) { LockSupport.park(this); if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) break; } if (acquireQueued(node, savedState) && interruptMode != THROW_IE) interruptMode = REINTERRUPT; if (node.nextWaiter != null) // clean up if cancelled unlinkCancelledWaiters(); if (interruptMode != 0) reportInterruptAfterWait(interruptMode); } /** {@collect.stats} * {@description.open} * Implements timed condition wait. * <ol> * <li> If current thread is interrupted, throw InterruptedException. * <li> Save lock state returned by {@link #getState}. * <li> Invoke {@link #release} with * saved state as argument, throwing * IllegalMonitorStateException if it fails. * <li> Block until signalled, interrupted, or timed out. * <li> Reacquire by invoking specialized version of * {@link #acquire} with saved state as argument. * <li> If interrupted while blocked in step 4, throw InterruptedException. * </ol> * {@description.close} */ public final long awaitNanos(long nanosTimeout) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); long savedState = fullyRelease(node); long lastTime = System.nanoTime(); int interruptMode = 0; while (!isOnSyncQueue(node)) { if (nanosTimeout <= 0L) { transferAfterCancelledWait(node); break; } LockSupport.parkNanos(this, nanosTimeout); if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) break; long now = System.nanoTime(); nanosTimeout -= now - lastTime; lastTime = now; } if (acquireQueued(node, savedState) && interruptMode != THROW_IE) interruptMode = REINTERRUPT; if (node.nextWaiter != null) unlinkCancelledWaiters(); if (interruptMode != 0) reportInterruptAfterWait(interruptMode); return nanosTimeout - (System.nanoTime() - lastTime); } /** {@collect.stats} * {@description.open} * Implements absolute timed condition wait. * <ol> * <li> If current thread is interrupted, throw InterruptedException. * <li> Save lock state returned by {@link #getState}. * <li> Invoke {@link #release} with * saved state as argument, throwing * IllegalMonitorStateException if it fails. * <li> Block until signalled, interrupted, or timed out. * <li> Reacquire by invoking specialized version of * {@link #acquire} with saved state as argument. * <li> If interrupted while blocked in step 4, throw InterruptedException. * <li> If timed out while blocked in step 4, return false, else true. * </ol> * {@description.close} */ public final boolean awaitUntil(Date deadline) throws InterruptedException { if (deadline == null) throw new NullPointerException(); long abstime = deadline.getTime(); if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); long savedState = fullyRelease(node); boolean timedout = false; int interruptMode = 0; while (!isOnSyncQueue(node)) { if (System.currentTimeMillis() > abstime) { timedout = transferAfterCancelledWait(node); break; } LockSupport.parkUntil(this, abstime); if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) break; } if (acquireQueued(node, savedState) && interruptMode != THROW_IE) interruptMode = REINTERRUPT; if (node.nextWaiter != null) unlinkCancelledWaiters(); if (interruptMode != 0) reportInterruptAfterWait(interruptMode); return !timedout; } /** {@collect.stats} * {@description.open} * Implements timed condition wait. * <ol> * <li> If current thread is interrupted, throw InterruptedException. * <li> Save lock state returned by {@link #getState}. * <li> Invoke {@link #release} with * saved state as argument, throwing * IllegalMonitorStateException if it fails. * <li> Block until signalled, interrupted, or timed out. * <li> Reacquire by invoking specialized version of * {@link #acquire} with saved state as argument. * <li> If interrupted while blocked in step 4, throw InterruptedException. * <li> If timed out while blocked in step 4, return false, else true. * </ol> * {@description.close} */ public final boolean await(long time, TimeUnit unit) throws InterruptedException { if (unit == null) throw new NullPointerException(); long nanosTimeout = unit.toNanos(time); if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); long savedState = fullyRelease(node); long lastTime = System.nanoTime(); boolean timedout = false; int interruptMode = 0; while (!isOnSyncQueue(node)) { if (nanosTimeout <= 0L) { timedout = transferAfterCancelledWait(node); break; } if (nanosTimeout >= spinForTimeoutThreshold) LockSupport.parkNanos(this, nanosTimeout); if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) break; long now = System.nanoTime(); nanosTimeout -= now - lastTime; lastTime = now; } if (acquireQueued(node, savedState) && interruptMode != THROW_IE) interruptMode = REINTERRUPT; if (node.nextWaiter != null) unlinkCancelledWaiters(); if (interruptMode != 0) reportInterruptAfterWait(interruptMode); return !timedout; } // support for instrumentation /** {@collect.stats} * {@description.open} * Returns true if this condition was created by the given * synchronization object. * {@description.close} * * @return {@code true} if owned */ final boolean isOwnedBy(AbstractQueuedLongSynchronizer sync) { return sync == AbstractQueuedLongSynchronizer.this; } /** {@collect.stats} * {@description.open} * Queries whether any threads are waiting on this condition. * Implements {@link AbstractQueuedLongSynchronizer#hasWaiters}. * {@description.close} * * @return {@code true} if there are any waiting threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} * returns {@code false} */ protected final boolean hasWaiters() { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); for (Node w = firstWaiter; w != null; w = w.nextWaiter) { if (w.waitStatus == Node.CONDITION) return true; } return false; } /** {@collect.stats} * {@description.open} * Returns an estimate of the number of threads waiting on * this condition. * Implements {@link AbstractQueuedLongSynchronizer#getWaitQueueLength}. * {@description.close} * * @return the estimated number of waiting threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} * returns {@code false} */ protected final int getWaitQueueLength() { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); int n = 0; for (Node w = firstWaiter; w != null; w = w.nextWaiter) { if (w.waitStatus == Node.CONDITION) ++n; } return n; } /** {@collect.stats} * {@description.open} * Returns a collection containing those threads that may be * waiting on this Condition. * Implements {@link AbstractQueuedLongSynchronizer#getWaitingThreads}. * {@description.close} * * @return the collection of threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} * returns {@code false} */ protected final Collection<Thread> getWaitingThreads() { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); ArrayList<Thread> list = new ArrayList<Thread>(); for (Node w = firstWaiter; w != null; w = w.nextWaiter) { if (w.waitStatus == Node.CONDITION) { Thread t = w.thread; if (t != null) list.add(t); } } return list; } } /** {@collect.stats} * {@description.open} * Setup to support compareAndSet. We need to natively implement * this here: For the sake of permitting future enhancements, we * cannot explicitly subclass AtomicLong, which would be * efficient and useful otherwise. So, as the lesser of evils, we * natively implement using hotspot intrinsics API. And while we * are at it, we do the same for other CASable fields (which could * otherwise be done with atomic field updaters). * {@description.close} */ private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long stateOffset; private static final long headOffset; private static final long tailOffset; private static final long waitStatusOffset; private static final long nextOffset; static { try { stateOffset = unsafe.objectFieldOffset (AbstractQueuedLongSynchronizer.class.getDeclaredField("state")); headOffset = unsafe.objectFieldOffset (AbstractQueuedLongSynchronizer.class.getDeclaredField("head")); tailOffset = unsafe.objectFieldOffset (AbstractQueuedLongSynchronizer.class.getDeclaredField("tail")); waitStatusOffset = unsafe.objectFieldOffset (Node.class.getDeclaredField("waitStatus")); nextOffset = unsafe.objectFieldOffset (Node.class.getDeclaredField("next")); } catch (Exception ex) { throw new Error(ex); } } /** {@collect.stats} * {@description.open} * CAS head field. Used only by enq. * {@description.close} */ private final boolean compareAndSetHead(Node update) { return unsafe.compareAndSwapObject(this, headOffset, null, update); } /** {@collect.stats} * {@description.open} * CAS tail field. Used only by enq. * {@description.close} */ private final boolean compareAndSetTail(Node expect, Node update) { return unsafe.compareAndSwapObject(this, tailOffset, expect, update); } /** {@collect.stats} * {@description.open} * CAS waitStatus field of a node. * {@description.close} */ private final static boolean compareAndSetWaitStatus(Node node, int expect, int update) { return unsafe.compareAndSwapInt(node, waitStatusOffset, expect, update); } /** {@collect.stats} * {@description.open} * CAS next field of a node. * {@description.close} */ private final static boolean compareAndSetNext(Node node, Node expect, Node update) { return unsafe.compareAndSwapObject(node, nextOffset, expect, update); } }
Java
/* * Copyright (c) 1994, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * A class can implement the <code>Observer</code> interface when it * wants to be informed of changes in observable objects. * {@description.close} * * @author Chris Warth * @see java.util.Observable * @since JDK1.0 */ public interface Observer { /** {@collect.stats} * {@description.open} * This method is called whenever the observed object is changed. An * application calls an <tt>Observable</tt> object's * <code>notifyObservers</code> method to have all the object's * observers notified of the change. * {@description.close} * * @param o the observable object. * @param arg an argument passed to the <code>notifyObservers</code> * method. */ void update(Observable o, Object arg); }
Java
/* * Copyright (c) 1994, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * This class represents an observable object, or "data" * in the model-view paradigm. It can be subclassed to represent an * object that the application wants to have observed. * <p> * An observable object can have one or more observers. An observer * may be any object that implements interface <tt>Observer</tt>. After an * observable instance changes, an application calling the * <code>Observable</code>'s <code>notifyObservers</code> method * causes all of its observers to be notified of the change by a call * to their <code>update</code> method. * <p> * The order in which notifications will be delivered is unspecified. * The default implementation provided in the Observable class will * notify Observers in the order in which they registered interest, but * subclasses may change this order, use no guaranteed order, deliver * notifications on separate threads, or may guarantee that their * subclass follows this order, as they choose. * <p> * Note that this notification mechanism is has nothing to do with threads * and is completely separate from the <tt>wait</tt> and <tt>notify</tt> * mechanism of class <tt>Object</tt>. * <p> * When an observable object is newly created, its set of observers is * empty. Two observers are considered the same if and only if the * <tt>equals</tt> method returns true for them. * {@description.close} * * @author Chris Warth * @see java.util.Observable#notifyObservers() * @see java.util.Observable#notifyObservers(java.lang.Object) * @see java.util.Observer * @see java.util.Observer#update(java.util.Observable, java.lang.Object) * @since JDK1.0 */ public class Observable { private boolean changed = false; private Vector obs; /** {@collect.stats} * {@description.open} * Construct an Observable with zero Observers. * {@description.close} */ public Observable() { obs = new Vector(); } /** {@collect.stats} * {@description.open} * Adds an observer to the set of observers for this object, provided * that it is not the same as some observer already in the set. * The order in which notifications will be delivered to multiple * observers is not specified. See the class comment. * {@description.close} * * @param o an observer to be added. * @throws NullPointerException if the parameter o is null. */ public synchronized void addObserver(Observer o) { if (o == null) throw new NullPointerException(); if (!obs.contains(o)) { obs.addElement(o); } } /** {@collect.stats} * {@description.open} * Deletes an observer from the set of observers of this object. * Passing <CODE>null</CODE> to this method will have no effect. * {@description.close} * @param o the observer to be deleted. */ public synchronized void deleteObserver(Observer o) { obs.removeElement(o); } /** {@collect.stats} * {@description.open} * If this object has changed, as indicated by the * <code>hasChanged</code> method, then notify all of its observers * and then call the <code>clearChanged</code> method to * indicate that this object has no longer changed. * <p> * Each observer has its <code>update</code> method called with two * arguments: this observable object and <code>null</code>. In other * words, this method is equivalent to: * <blockquote><tt> * notifyObservers(null)</tt></blockquote> * {@description.close} * * @see java.util.Observable#clearChanged() * @see java.util.Observable#hasChanged() * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ public void notifyObservers() { notifyObservers(null); } /** {@collect.stats} * {@description.open} * If this object has changed, as indicated by the * <code>hasChanged</code> method, then notify all of its observers * and then call the <code>clearChanged</code> method to indicate * that this object has no longer changed. * <p> * Each observer has its <code>update</code> method called with two * arguments: this observable object and the <code>arg</code> argument. * {@description.close} * * @param arg any object. * @see java.util.Observable#clearChanged() * @see java.util.Observable#hasChanged() * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ public void notifyObservers(Object arg) { /* * a temporary array buffer, used as a snapshot of the state of * current Observers. */ Object[] arrLocal; synchronized (this) { /* We don't want the Observer doing callbacks into * arbitrary code while holding its own Monitor. * The code where we extract each Observable from * the Vector and store the state of the Observer * needs synchronization, but notifying observers * does not (should not). The worst result of any * potential race-condition here is that: * 1) a newly-added Observer will miss a * notification in progress * 2) a recently unregistered Observer will be * wrongly notified when it doesn't care */ if (!changed) return; arrLocal = obs.toArray(); clearChanged(); } for (int i = arrLocal.length-1; i>=0; i--) ((Observer)arrLocal[i]).update(this, arg); } /** {@collect.stats} * {@description.open} * Clears the observer list so that this object no longer has any observers. * {@description.close} */ public synchronized void deleteObservers() { obs.removeAllElements(); } /** {@collect.stats} * {@description.open} * Marks this <tt>Observable</tt> object as having been changed; the * <tt>hasChanged</tt> method will now return <tt>true</tt>. * {@description.close} */ protected synchronized void setChanged() { changed = true; } /** {@collect.stats} * {@description.open} * Indicates that this object has no longer changed, or that it has * already notified all of its observers of its most recent change, * so that the <tt>hasChanged</tt> method will now return <tt>false</tt>. * This method is called automatically by the * <code>notifyObservers</code> methods. * {@description.close} * * @see java.util.Observable#notifyObservers() * @see java.util.Observable#notifyObservers(java.lang.Object) */ protected synchronized void clearChanged() { changed = false; } /** {@collect.stats} * {@description.open} * Tests if this object has changed. * {@description.close} * * @return <code>true</code> if and only if the <code>setChanged</code> * method has been called more recently than the * <code>clearChanged</code> method on this object; * <code>false</code> otherwise. * @see java.util.Observable#clearChanged() * @see java.util.Observable#setChanged() */ public synchronized boolean hasChanged() { return changed; } /** {@collect.stats} * {@description.open} * Returns the number of observers of this <tt>Observable</tt> object. * {@description.close} * * @return the number of observers of this object. */ public synchronized int countObservers() { return obs.size(); } }
Java
/* * Copyright (c) 1994, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * The <code>Stack</code> class represents a last-in-first-out * (LIFO) stack of objects. It extends class <tt>Vector</tt> with five * operations that allow a vector to be treated as a stack. The usual * <tt>push</tt> and <tt>pop</tt> operations are provided, as well as a * method to <tt>peek</tt> at the top item on the stack, a method to test * for whether the stack is <tt>empty</tt>, and a method to <tt>search</tt> * the stack for an item and discover how far it is from the top. * <p> * When a stack is first created, it contains no items. * * <p>A more complete and consistent set of LIFO stack operations is * provided by the {@link Deque} interface and its implementations, which * should be used in preference to this class. For example: * <pre> {@code * Deque<Integer> stack = new ArrayDeque<Integer>();}</pre> * {@description.close} * * @author Jonathan Payne * @since JDK1.0 */ public class Stack<E> extends Vector<E> { /** {@collect.stats} * {@description.open} * Creates an empty Stack. * {@description.close} */ public Stack() { } /** {@collect.stats} * {@description.open} * Pushes an item onto the top of this stack. This has exactly * the same effect as: * <blockquote><pre> * addElement(item)</pre></blockquote> * {@description.close} * * @param item the item to be pushed onto this stack. * @return the <code>item</code> argument. * @see java.util.Vector#addElement */ public E push(E item) { addElement(item); return item; } /** {@collect.stats} * {@description.open} * Removes the object at the top of this stack and returns that * object as the value of this function. * {@description.close} * * @return The object at the top of this stack (the last item * of the <tt>Vector</tt> object). * @exception EmptyStackException if this stack is empty. */ public synchronized E pop() { E obj; int len = size(); obj = peek(); removeElementAt(len - 1); return obj; } /** {@collect.stats} * {@description.open} * Looks at the object at the top of this stack without removing it * from the stack. * {@description.close} * * @return the object at the top of this stack (the last item * of the <tt>Vector</tt> object). * @exception EmptyStackException if this stack is empty. */ public synchronized E peek() { int len = size(); if (len == 0) throw new EmptyStackException(); return elementAt(len - 1); } /** {@collect.stats} * {@description.open} * Tests if this stack is empty. * {@description.close} * * @return <code>true</code> if and only if this stack contains * no items; <code>false</code> otherwise. */ public boolean empty() { return size() == 0; } /** {@collect.stats} * {@description.open} * Returns the 1-based position where an object is on this stack. * If the object <tt>o</tt> occurs as an item in this stack, this * method returns the distance from the top of the stack of the * occurrence nearest the top of the stack; the topmost item on the * stack is considered to be at distance <tt>1</tt>. The <tt>equals</tt> * method is used to compare <tt>o</tt> to the * items in this stack. * {@description.close} * * @param o the desired object. * @return the 1-based position from the top of the stack where * the object is located; the return value <code>-1</code> * indicates that the object is not on the stack. */ public synchronized int search(Object o) { int i = lastIndexOf(o); if (i >= 0) { return size() - i; } return -1; } /** {@collect.stats} * {@description.open} * use serialVersionUID from JDK 1.0.2 for interoperability * {@description.close} */ private static final long serialVersionUID = 1224463164541339165L; }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea and Josh Bloch with assistance from members of * JCP JSR-166 Expert Group and released to the public domain, as explained * at http://creativecommons.org/licenses/publicdomain */ package java.util; /** {@collect.stats} * {@description.open} * A linear collection that supports element insertion and removal at * both ends. The name <i>deque</i> is short for "double ended queue" * and is usually pronounced "deck". Most <tt>Deque</tt> * implementations place no fixed limits on the number of elements * they may contain, but this interface supports capacity-restricted * deques as well as those with no fixed size limit. * * <p>This interface defines methods to access the elements at both * ends of the deque. Methods are provided to insert, remove, and * examine the element. Each of these methods exists in two forms: * one throws an exception if the operation fails, the other returns a * special value (either <tt>null</tt> or <tt>false</tt>, depending on * the operation). The latter form of the insert operation is * designed specifically for use with capacity-restricted * <tt>Deque</tt> implementations; in most implementations, insert * operations cannot fail. * * <p>The twelve methods described above are summarized in the * following table: * * <p> * <table BORDER CELLPADDING=3 CELLSPACING=1> * <tr> * <td></td> * <td ALIGN=CENTER COLSPAN = 2> <b>First Element (Head)</b></td> * <td ALIGN=CENTER COLSPAN = 2> <b>Last Element (Tail)</b></td> * </tr> * <tr> * <td></td> * <td ALIGN=CENTER><em>Throws exception</em></td> * <td ALIGN=CENTER><em>Special value</em></td> * <td ALIGN=CENTER><em>Throws exception</em></td> * <td ALIGN=CENTER><em>Special value</em></td> * </tr> * <tr> * <td><b>Insert</b></td> * <td>{@link #addFirst addFirst(e)}</td> * <td>{@link #offerFirst offerFirst(e)}</td> * <td>{@link #addLast addLast(e)}</td> * <td>{@link #offerLast offerLast(e)}</td> * </tr> * <tr> * <td><b>Remove</b></td> * <td>{@link #removeFirst removeFirst()}</td> * <td>{@link #pollFirst pollFirst()}</td> * <td>{@link #removeLast removeLast()}</td> * <td>{@link #pollLast pollLast()}</td> * </tr> * <tr> * <td><b>Examine</b></td> * <td>{@link #getFirst getFirst()}</td> * <td>{@link #peekFirst peekFirst()}</td> * <td>{@link #getLast getLast()}</td> * <td>{@link #peekLast peekLast()}</td> * </tr> * </table> * * <p>This interface extends the {@link Queue} interface. When a deque is * used as a queue, FIFO (First-In-First-Out) behavior results. Elements are * added at the end of the deque and removed from the beginning. The methods * inherited from the <tt>Queue</tt> interface are precisely equivalent to * <tt>Deque</tt> methods as indicated in the following table: * * <p> * <table BORDER CELLPADDING=3 CELLSPACING=1> * <tr> * <td ALIGN=CENTER> <b><tt>Queue</tt> Method</b></td> * <td ALIGN=CENTER> <b>Equivalent <tt>Deque</tt> Method</b></td> * </tr> * <tr> * <td>{@link java.util.Queue#add add(e)}</td> * <td>{@link #addLast addLast(e)}</td> * </tr> * <tr> * <td>{@link java.util.Queue#offer offer(e)}</td> * <td>{@link #offerLast offerLast(e)}</td> * </tr> * <tr> * <td>{@link java.util.Queue#remove remove()}</td> * <td>{@link #removeFirst removeFirst()}</td> * </tr> * <tr> * <td>{@link java.util.Queue#poll poll()}</td> * <td>{@link #pollFirst pollFirst()}</td> * </tr> * <tr> * <td>{@link java.util.Queue#element element()}</td> * <td>{@link #getFirst getFirst()}</td> * </tr> * <tr> * <td>{@link java.util.Queue#peek peek()}</td> * <td>{@link #peek peekFirst()}</td> * </tr> * </table> * * <p>Deques can also be used as LIFO (Last-In-First-Out) stacks. This * interface should be used in preference to the legacy {@link Stack} class. * When a deque is used as a stack, elements are pushed and popped from the * beginning of the deque. Stack methods are precisely equivalent to * <tt>Deque</tt> methods as indicated in the table below: * * <p> * <table BORDER CELLPADDING=3 CELLSPACING=1> * <tr> * <td ALIGN=CENTER> <b>Stack Method</b></td> * <td ALIGN=CENTER> <b>Equivalent <tt>Deque</tt> Method</b></td> * </tr> * <tr> * <td>{@link #push push(e)}</td> * <td>{@link #addFirst addFirst(e)}</td> * </tr> * <tr> * <td>{@link #pop pop()}</td> * <td>{@link #removeFirst removeFirst()}</td> * </tr> * <tr> * <td>{@link #peek peek()}</td> * <td>{@link #peekFirst peekFirst()}</td> * </tr> * </table> * * <p>Note that the {@link #peek peek} method works equally well when * a deque is used as a queue or a stack; in either case, elements are * drawn from the beginning of the deque. * * <p>This interface provides two methods to remove interior * elements, {@link #removeFirstOccurrence removeFirstOccurrence} and * {@link #removeLastOccurrence removeLastOccurrence}. * * <p>Unlike the {@link List} interface, this interface does not * provide support for indexed access to elements. * * <p>While <tt>Deque</tt> implementations are not strictly required * to prohibit the insertion of null elements, they are strongly * encouraged to do so. Users of any <tt>Deque</tt> implementations * that do allow null elements are strongly encouraged <i>not</i> to * take advantage of the ability to insert nulls. This is so because * <tt>null</tt> is used as a special return value by various methods * to indicated that the deque is empty. * * <p><tt>Deque</tt> implementations generally do not define * element-based versions of the <tt>equals</tt> and <tt>hashCode</tt> * methods, but instead inherit the identity-based versions from class * <tt>Object</tt>. * * <p>This interface is a member of the <a * href="{@docRoot}/../technotes/guides/collections/index.html"> Java Collections * Framework</a>. * {@description.close} * * @author Doug Lea * @author Josh Bloch * @since 1.6 * @param <E> the type of elements held in this collection */ public interface Deque<E> extends Queue<E> { /** {@collect.stats} * {@description.open} * Inserts the specified element at the front of this deque if it is * possible to do so immediately without violating capacity restrictions. * {@description.close} * {@property.open formal:java.util.Deque_OfferRatherThanAdd} * When using a capacity-restricted deque, it is generally preferable to * use method {@link #offerFirst}. * {@property.close} * * @param e the element to add * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ void addFirst(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this deque if it is * possible to do so immediately without violating capacity restrictions. * {@description.close} * {@property.open formal:java.util.Deque_OfferRatherThanAdd} * When using a capacity-restricted deque, it is generally preferable to * use method {@link #offerLast}. * {@property.close} * * {@description.open} * <p>This method is equivalent to {@link #add}. * {@description.close} * * @param e the element to add * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ void addLast(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element at the front of this deque unless it would * violate capacity restrictions. * {@description.close} * {@property.open formal:java.util.Deque_OfferRatherThanAdd} * When using a capacity-restricted deque, * this method is generally preferable to the {@link #addFirst} method, * which can fail to insert an element only by throwing an exception. * {@property.close} * * @param e the element to add * @return <tt>true</tt> if the element was added to this deque, else * <tt>false</tt> * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ boolean offerFirst(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this deque unless it would * violate capacity restrictions. * {@description.close} * {@property.open formal:java.util.Deque_OfferRatherThanAdd} * When using a capacity-restricted deque, * this method is generally preferable to the {@link #addLast} method, * which can fail to insert an element only by throwing an exception. * {@property.close} * * @param e the element to add * @return <tt>true</tt> if the element was added to this deque, else * <tt>false</tt> * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ boolean offerLast(E e); /** {@collect.stats} * {@description.open} * Retrieves and removes the first element of this deque. This method * differs from {@link #pollFirst pollFirst} only in that it throws an * exception if this deque is empty. * {@description.close} * * @return the head of this deque * @throws NoSuchElementException if this deque is empty */ E removeFirst(); /** {@collect.stats} * {@description.open} * Retrieves and removes the last element of this deque. This method * differs from {@link #pollLast pollLast} only in that it throws an * exception if this deque is empty. * {@description.close} * * @return the tail of this deque * @throws NoSuchElementException if this deque is empty */ E removeLast(); /** {@collect.stats} * {@description.open} * Retrieves and removes the first element of this deque, * or returns <tt>null</tt> if this deque is empty. * {@description.close} * * @return the head of this deque, or <tt>null</tt> if this deque is empty */ E pollFirst(); /** {@collect.stats} * {@description.open} * Retrieves and removes the last element of this deque, * or returns <tt>null</tt> if this deque is empty. * {@description.close} * * @return the tail of this deque, or <tt>null</tt> if this deque is empty */ E pollLast(); /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the first element of this deque. * * This method differs from {@link #peekFirst peekFirst} only in that it * throws an exception if this deque is empty. * {@description.close} * * @return the head of this deque * @throws NoSuchElementException if this deque is empty */ E getFirst(); /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the last element of this deque. * This method differs from {@link #peekLast peekLast} only in that it * throws an exception if this deque is empty. * {@description.close} * * @return the tail of this deque * @throws NoSuchElementException if this deque is empty */ E getLast(); /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the first element of this deque, * or returns <tt>null</tt> if this deque is empty. * {@description.close} * * @return the head of this deque, or <tt>null</tt> if this deque is empty */ E peekFirst(); /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the last element of this deque, * or returns <tt>null</tt> if this deque is empty. * {@description.close} * * @return the tail of this deque, or <tt>null</tt> if this deque is empty */ E peekLast(); /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt> * (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * {@description.close} * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if an element was removed as a result of this call * @throws ClassCastException if the class of the specified element * is incompatible with this deque (optional) * @throws NullPointerException if the specified element is null and this * deque does not permit null elements (optional) */ boolean removeFirstOccurrence(Object o); /** {@collect.stats} * {@description.open} * Removes the last occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the last element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt> * (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * {@description.close} * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if an element was removed as a result of this call * @throws ClassCastException if the class of the specified element * is incompatible with this deque (optional) * @throws NullPointerException if the specified element is null and this * deque does not permit null elements (optional) */ boolean removeLastOccurrence(Object o); // *** Queue methods *** /** {@collect.stats} * {@description.open} * Inserts the specified element into the queue represented by this deque * (in other words, at the tail of this deque) if it is possible to do so * immediately without violating capacity restrictions, returning * <tt>true</tt> upon success and throwing an * <tt>IllegalStateException</tt> if no space is currently available. * {@description.close} * {@property.open formal:java.util.Deque_OfferRatherThanAdd} * When using a capacity-restricted deque, it is generally preferable to * use {@link #offer(Object) offer}. * * <p>This method is equivalent to {@link #addLast}. * {@property.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ boolean add(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element into the queue represented by this deque * (in other words, at the tail of this deque) if it is possible to do so * immediately without violating capacity restrictions, returning * <tt>true</tt> upon success and <tt>false</tt> if no space is currently * available. * {@description.close} * {@property.open formal:java.util.Deque_OfferRatherThanAdd} * When using a capacity-restricted deque, this method is * generally preferable to the {@link #add} method, which can fail to * insert an element only by throwing an exception. * {@property.close} * * {@description.open} * <p>This method is equivalent to {@link #offerLast}. * {@description.close} * * @param e the element to add * @return <tt>true</tt> if the element was added to this deque, else * <tt>false</tt> * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ boolean offer(E e); /** {@collect.stats} * {@description.open} * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque). * This method differs from {@link #poll poll} only in that it throws an * exception if this deque is empty. * * <p>This method is equivalent to {@link #removeFirst()}. * {@description.close} * * @return the head of the queue represented by this deque * @throws NoSuchElementException if this deque is empty */ E remove(); /** {@collect.stats} * {@description.open} * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque), or returns * <tt>null</tt> if this deque is empty. * * <p>This method is equivalent to {@link #pollFirst()}. * {@description.close} * * @return the first element of this deque, or <tt>null</tt> if * this deque is empty */ E poll(); /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head of the queue represented by * this deque (in other words, the first element of this deque). * This method differs from {@link #peek peek} only in that it throws an * exception if this deque is empty. * * <p>This method is equivalent to {@link #getFirst()}. * {@description.close} * * @return the head of the queue represented by this deque * @throws NoSuchElementException if this deque is empty */ E element(); /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head of the queue represented by * this deque (in other words, the first element of this deque), or * returns <tt>null</tt> if this deque is empty. * * <p>This method is equivalent to {@link #peekFirst()}. * {@description.close} * * @return the head of the queue represented by this deque, or * <tt>null</tt> if this deque is empty */ E peek(); // *** Stack methods *** /** {@collect.stats} * {@description.open} * Pushes an element onto the stack represented by this deque (in other * words, at the head of this deque) if it is possible to do so * immediately without violating capacity restrictions, returning * <tt>true</tt> upon success and throwing an * <tt>IllegalStateException</tt> if no space is currently available. * {@description.close} * * {@property.open formal:java.util.Deque_OfferRatherThanAdd} * <p>This method is equivalent to {@link #addFirst}. * {@new.open} * As {@link #offerFirst} is generally preferable to the {@link #addFirst} * method, this method is not preferable, when using a capacity-restricted * deque. * {@new.close} * {@property.close} * * @param e the element to push * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ void push(E e); /** {@collect.stats} * {@description.open} * Pops an element from the stack represented by this deque. In other * words, removes and returns the first element of this deque. * * <p>This method is equivalent to {@link #removeFirst()}. * {@description.close} * * @return the element at the front of this deque (which is the top * of the stack represented by this deque) * @throws NoSuchElementException if this deque is empty */ E pop(); // *** Collection methods *** /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt> * (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * <p>This method is equivalent to {@link #removeFirstOccurrence}. * {@description.close} * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if an element was removed as a result of this call * @throws ClassCastException if the class of the specified element * is incompatible with this deque (optional) * @throws NullPointerException if the specified element is null and this * deque does not permit null elements (optional) */ boolean remove(Object o); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this deque contains the specified element. * More formally, returns <tt>true</tt> if and only if this deque contains * at least one element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * {@description.close} * * @param o element whose presence in this deque is to be tested * @return <tt>true</tt> if this deque contains the specified element * @throws ClassCastException if the type of the specified element * is incompatible with this deque (optional) * @throws NullPointerException if the specified element is null and this * deque does not permit null elements (optional) */ boolean contains(Object o); /** {@collect.stats} * {@description.open} * Returns the number of elements in this deque. * {@description.close} * * @return the number of elements in this deque */ public int size(); /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this deque in proper sequence. * The elements will be returned in order from first (head) to last (tail). * {@description.close} * * @return an iterator over the elements in this deque in proper sequence */ Iterator<E> iterator(); /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this deque in reverse * sequential order. The elements will be returned in order from * last (tail) to first (head). * {@description.close} * * @return an iterator over the elements in this deque in reverse * sequence */ Iterator<E> descendingIterator(); }
Java
/* * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.util.Date; /** {@collect.stats} * {@description.open} * A facility for threads to schedule tasks for future execution in a * background thread. Tasks may be scheduled for one-time execution, or for * repeated execution at regular intervals. * {@description.close} * * {@property.open uncheckable} * <p>Corresponding to each <tt>Timer</tt> object is a single background * thread that is used to execute all of the timer's tasks, sequentially. * Timer tasks should complete quickly. If a timer task takes excessive time * to complete, it "hogs" the timer's task execution thread. This can, in * turn, delay the execution of subsequent tasks, which may "bunch up" and * execute in rapid succession when (and if) the offending task finally * completes. * {@property.close} * * {@description.open} * <p>After the last live reference to a <tt>Timer</tt> object goes away * <i>and</i> all outstanding tasks have completed execution, the timer's task * execution thread terminates gracefully (and becomes subject to garbage * collection). However, this can take arbitrarily long to occur. By * default, the task execution thread does not run as a <i>daemon thread</i>, * so it is capable of keeping an application from terminating. If a caller * wants to terminate a timer's task execution thread rapidly, the caller * should invoke the timer's <tt>cancel</tt> method. * * <p>If the timer's task execution thread terminates unexpectedly, for * example, because its <tt>stop</tt> method is invoked, any further * attempt to schedule a task on the timer will result in an * <tt>IllegalStateException</tt>, as if the timer's <tt>cancel</tt> * method had been invoked. * * <p>This class is thread-safe: multiple threads can share a single * <tt>Timer</tt> object without the need for external synchronization. * * <p>This class does <i>not</i> offer real-time guarantees: it schedules * tasks using the <tt>Object.wait(long)</tt> method. * * <p>Java 5.0 introduced the {@code java.util.concurrent} package and * one of the concurrency utilities therein is the {@link * java.util.concurrent.ScheduledThreadPoolExecutor * ScheduledThreadPoolExecutor} which is a thread pool for repeatedly * executing tasks at a given rate or delay. It is effectively a more * versatile replacement for the {@code Timer}/{@code TimerTask} * combination, as it allows multiple service threads, accepts various * time units, and doesn't require subclassing {@code TimerTask} (just * implement {@code Runnable}). Configuring {@code * ScheduledThreadPoolExecutor} with one thread makes it equivalent to * {@code Timer}. * * <p>Implementation note: This class scales to large numbers of concurrently * scheduled tasks (thousands should present no problem). Internally, * it uses a binary heap to represent its task queue, so the cost to schedule * a task is O(log n), where n is the number of concurrently scheduled tasks. * * <p>Implementation note: All constructors start a timer thread. * {@description.close} * * @author Josh Bloch * @see TimerTask * @see Object#wait(long) * @since 1.3 */ public class Timer { /** {@collect.stats} * {@description.open} * The timer task queue. This data structure is shared with the timer * thread. The timer produces tasks, via its various schedule calls, * and the timer thread consumes, executing timer tasks as appropriate, * and removing them from the queue when they're obsolete. * {@description.close} */ private TaskQueue queue = new TaskQueue(); /** {@collect.stats} * {@description.open} * The timer thread. * {@description.close} */ private TimerThread thread = new TimerThread(queue); /** {@collect.stats} * {@description.open} * This object causes the timer's task execution thread to exit * gracefully when there are no live references to the Timer object and no * tasks in the timer queue. It is used in preference to a finalizer on * Timer as such a finalizer would be susceptible to a subclass's * finalizer forgetting to call it. * {@description.close} */ private Object threadReaper = new Object() { protected void finalize() throws Throwable { synchronized(queue) { thread.newTasksMayBeScheduled = false; queue.notify(); // In case queue is empty. } } }; /** {@collect.stats} * {@description.open} * This ID is used to generate thread names. (It could be replaced * by an AtomicInteger as soon as they become available.) * {@description.close} */ private static int nextSerialNumber = 0; private static synchronized int serialNumber() { return nextSerialNumber++; } /** {@collect.stats} * {@description.open} * Creates a new timer. The associated thread does <i>not</i> * {@linkplain Thread#setDaemon run as a daemon}. * {@description.close} */ public Timer() { this("Timer-" + serialNumber()); } /** {@collect.stats} * {@description.open} * Creates a new timer whose associated thread may be specified to * {@linkplain Thread#setDaemon run as a daemon}. * A daemon thread is called for if the timer will be used to * schedule repeating "maintenance activities", which must be * performed as long as the application is running, but should not * prolong the lifetime of the application. * {@description.close} * * @param isDaemon true if the associated thread should run as a daemon. */ public Timer(boolean isDaemon) { this("Timer-" + serialNumber(), isDaemon); } /** {@collect.stats} * {@description.open} * Creates a new timer whose associated thread has the specified name. * The associated thread does <i>not</i> * {@linkplain Thread#setDaemon run as a daemon}. * {@description.close} * * @param name the name of the associated thread * @throws NullPointerException if name is null * @since 1.5 */ public Timer(String name) { thread.setName(name); thread.start(); } /** {@collect.stats} * {@description.open} * Creates a new timer whose associated thread has the specified name, * and may be specified to * {@linkplain Thread#setDaemon run as a daemon}. * {@description.close} * * @param name the name of the associated thread * @param isDaemon true if the associated thread should run as a daemon * @throws NullPointerException if name is null * @since 1.5 */ public Timer(String name, boolean isDaemon) { thread.setName(name); thread.setDaemon(isDaemon); thread.start(); } /** {@collect.stats} * {@description.open} * Schedules the specified task for execution after the specified delay. * {@description.close} * * @param task task to be scheduled. * @param delay delay in milliseconds before task is to be executed. * @throws IllegalArgumentException if <tt>delay</tt> is negative, or * <tt>delay + System.currentTimeMillis()</tt> is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, or timer was cancelled. */ public void schedule(TimerTask task, long delay) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); sched(task, System.currentTimeMillis()+delay, 0); } /** {@collect.stats} * {@description.open} * Schedules the specified task for execution at the specified time. If * the time is in the past, the task is scheduled for immediate execution. * {@description.close} * * @param task task to be scheduled. * @param time time at which task is to be executed. * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. */ public void schedule(TimerTask task, Date time) { sched(task, time.getTime(), 0); } /** {@collect.stats} * {@description.open} * Schedules the specified task for repeated <i>fixed-delay execution</i>, * beginning after the specified delay. Subsequent executions take place * at approximately regular intervals separated by the specified period. * * <p>In fixed-delay execution, each execution is scheduled relative to * the actual execution time of the previous execution. If an execution * is delayed for any reason (such as garbage collection or other * background activity), subsequent executions will be delayed as well. * In the long run, the frequency of execution will generally be slightly * lower than the reciprocal of the specified period (assuming the system * clock underlying <tt>Object.wait(long)</tt> is accurate). * * <p>Fixed-delay execution is appropriate for recurring activities * that require "smoothness." In other words, it is appropriate for * activities where it is more important to keep the frequency accurate * in the short run than in the long run. This includes most animation * tasks, such as blinking a cursor at regular intervals. It also includes * tasks wherein regular activity is performed in response to human * input, such as automatically repeating a character as long as a key * is held down. * {@description.close} * * @param task task to be scheduled. * @param delay delay in milliseconds before task is to be executed. * @param period time in milliseconds between successive task executions. * @throws IllegalArgumentException if <tt>delay</tt> is negative, or * <tt>delay + System.currentTimeMillis()</tt> is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. */ public void schedule(TimerTask task, long delay, long period) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, System.currentTimeMillis()+delay, -period); } /** {@collect.stats} * {@description.open} * Schedules the specified task for repeated <i>fixed-delay execution</i>, * beginning at the specified time. Subsequent executions take place at * approximately regular intervals, separated by the specified period. * * <p>In fixed-delay execution, each execution is scheduled relative to * the actual execution time of the previous execution. If an execution * is delayed for any reason (such as garbage collection or other * background activity), subsequent executions will be delayed as well. * In the long run, the frequency of execution will generally be slightly * lower than the reciprocal of the specified period (assuming the system * clock underlying <tt>Object.wait(long)</tt> is accurate). * * <p>Fixed-delay execution is appropriate for recurring activities * that require "smoothness." In other words, it is appropriate for * activities where it is more important to keep the frequency accurate * in the short run than in the long run. This includes most animation * tasks, such as blinking a cursor at regular intervals. It also includes * tasks wherein regular activity is performed in response to human * input, such as automatically repeating a character as long as a key * is held down. * {@description.close} * * @param task task to be scheduled. * @param firstTime First time at which task is to be executed. * @param period time in milliseconds between successive task executions. * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. */ public void schedule(TimerTask task, Date firstTime, long period) { if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, firstTime.getTime(), -period); } /** {@collect.stats} * {@description.open} * Schedules the specified task for repeated <i>fixed-rate execution</i>, * beginning after the specified delay. Subsequent executions take place * at approximately regular intervals, separated by the specified period. * * <p>In fixed-rate execution, each execution is scheduled relative to the * scheduled execution time of the initial execution. If an execution is * delayed for any reason (such as garbage collection or other background * activity), two or more executions will occur in rapid succession to * "catch up." In the long run, the frequency of execution will be * exactly the reciprocal of the specified period (assuming the system * clock underlying <tt>Object.wait(long)</tt> is accurate). * * <p>Fixed-rate execution is appropriate for recurring activities that * are sensitive to <i>absolute</i> time, such as ringing a chime every * hour on the hour, or running scheduled maintenance every day at a * particular time. It is also appropriate for recurring activities * where the total time to perform a fixed number of executions is * important, such as a countdown timer that ticks once every second for * ten seconds. Finally, fixed-rate execution is appropriate for * scheduling multiple repeating timer tasks that must remain synchronized * with respect to one another. * {@description.close} * * @param task task to be scheduled. * @param delay delay in milliseconds before task is to be executed. * @param period time in milliseconds between successive task executions. * @throws IllegalArgumentException if <tt>delay</tt> is negative, or * <tt>delay + System.currentTimeMillis()</tt> is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. */ public void scheduleAtFixedRate(TimerTask task, long delay, long period) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, System.currentTimeMillis()+delay, period); } /** {@collect.stats} * {@description.open} * Schedules the specified task for repeated <i>fixed-rate execution</i>, * beginning at the specified time. Subsequent executions take place at * approximately regular intervals, separated by the specified period. * * <p>In fixed-rate execution, each execution is scheduled relative to the * scheduled execution time of the initial execution. If an execution is * delayed for any reason (such as garbage collection or other background * activity), two or more executions will occur in rapid succession to * "catch up." In the long run, the frequency of execution will be * exactly the reciprocal of the specified period (assuming the system * clock underlying <tt>Object.wait(long)</tt> is accurate). * * <p>Fixed-rate execution is appropriate for recurring activities that * are sensitive to <i>absolute</i> time, such as ringing a chime every * hour on the hour, or running scheduled maintenance every day at a * particular time. It is also appropriate for recurring activities * where the total time to perform a fixed number of executions is * important, such as a countdown timer that ticks once every second for * ten seconds. Finally, fixed-rate execution is appropriate for * scheduling multiple repeating timer tasks that must remain synchronized * with respect to one another. * {@description.close} * * @param task task to be scheduled. * @param firstTime First time at which task is to be executed. * @param period time in milliseconds between successive task executions. * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. */ public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) { if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, firstTime.getTime(), period); } /** {@collect.stats} * {@description.open} * Schedule the specified timer task for execution at the specified * time with the specified period, in milliseconds. If period is * positive, the task is scheduled for repeated execution; if period is * zero, the task is scheduled for one-time execution. Time is specified * in Date.getTime() format. This method checks timer state, task state, * and initial execution time, but not period. * {@description.close} * * @throws IllegalArgumentException if <tt>time()</tt> is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. */ private void sched(TimerTask task, long time, long period) { if (time < 0) throw new IllegalArgumentException("Illegal execution time."); synchronized(queue) { if (!thread.newTasksMayBeScheduled) throw new IllegalStateException("Timer already cancelled."); synchronized(task.lock) { if (task.state != TimerTask.VIRGIN) throw new IllegalStateException( "Task already scheduled or cancelled"); task.nextExecutionTime = time; task.period = period; task.state = TimerTask.SCHEDULED; } queue.add(task); if (queue.getMin() == task) queue.notify(); } } /** {@collect.stats} * {@description.open} * Terminates this timer, discarding any currently scheduled tasks. * Does not interfere with a currently executing task (if it exists). * Once a timer has been terminated, its execution thread terminates * gracefully, and no more tasks may be scheduled on it. * * <p>Note that calling this method from within the run method of a * timer task that was invoked by this timer absolutely guarantees that * the ongoing task execution is the last task execution that will ever * be performed by this timer. * * <p>This method may be called repeatedly; the second and subsequent * calls have no effect. * {@description.close} */ public void cancel() { synchronized(queue) { thread.newTasksMayBeScheduled = false; queue.clear(); queue.notify(); // In case queue was already empty. } } /** {@collect.stats} * {@description.open} * Removes all cancelled tasks from this timer's task queue. <i>Calling * this method has no effect on the behavior of the timer</i>, but * eliminates the references to the cancelled tasks from the queue. * If there are no external references to these tasks, they become * eligible for garbage collection. * * <p>Most programs will have no need to call this method. * It is designed for use by the rare application that cancels a large * number of tasks. Calling this method trades time for space: the * runtime of the method may be proportional to n + c log n, where n * is the number of tasks in the queue and c is the number of cancelled * tasks. * * <p>Note that it is permissible to call this method from within a * a task scheduled on this timer. * {@description.close} * * @return the number of tasks removed from the queue. * @since 1.5 */ public int purge() { int result = 0; synchronized(queue) { for (int i = queue.size(); i > 0; i--) { if (queue.get(i).state == TimerTask.CANCELLED) { queue.quickRemove(i); result++; } } if (result != 0) queue.heapify(); } return result; } } /** {@collect.stats} * {@description.open} * This "helper class" implements the timer's task execution thread, which * waits for tasks on the timer queue, executions them when they fire, * reschedules repeating tasks, and removes cancelled tasks and spent * non-repeating tasks from the queue. * {@description.close} */ class TimerThread extends Thread { /** {@collect.stats} * {@description.open} * This flag is set to false by the reaper to inform us that there * are no more live references to our Timer object. Once this flag * is true and there are no more tasks in our queue, there is no * work left for us to do, so we terminate gracefully. Note that * this field is protected by queue's monitor! * {@description.close} */ boolean newTasksMayBeScheduled = true; /** {@collect.stats} * {@description.open} * Our Timer's queue. We store this reference in preference to * a reference to the Timer so the reference graph remains acyclic. * Otherwise, the Timer would never be garbage-collected and this * thread would never go away. * {@description.close} */ private TaskQueue queue; TimerThread(TaskQueue queue) { this.queue = queue; } public void run() { try { mainLoop(); } finally { // Someone killed this Thread, behave as if Timer cancelled synchronized(queue) { newTasksMayBeScheduled = false; queue.clear(); // Eliminate obsolete references } } } /** {@collect.stats} * {@description.open} * The main timer loop. (See class comment.) * {@description.close} */ private void mainLoop() { while (true) { try { TimerTask task; boolean taskFired; synchronized(queue) { // Wait for queue to become non-empty while (queue.isEmpty() && newTasksMayBeScheduled) queue.wait(); if (queue.isEmpty()) break; // Queue is empty and will forever remain; die // Queue nonempty; look at first evt and do the right thing long currentTime, executionTime; task = queue.getMin(); synchronized(task.lock) { if (task.state == TimerTask.CANCELLED) { queue.removeMin(); continue; // No action required, poll queue again } currentTime = System.currentTimeMillis(); executionTime = task.nextExecutionTime; if (taskFired = (executionTime<=currentTime)) { if (task.period == 0) { // Non-repeating, remove queue.removeMin(); task.state = TimerTask.EXECUTED; } else { // Repeating task, reschedule queue.rescheduleMin( task.period<0 ? currentTime - task.period : executionTime + task.period); } } } if (!taskFired) // Task hasn't yet fired; wait queue.wait(executionTime - currentTime); } if (taskFired) // Task fired; run it, holding no locks task.run(); } catch(InterruptedException e) { } } } } /** {@collect.stats} * {@description.open} * This class represents a timer task queue: a priority queue of TimerTasks, * ordered on nextExecutionTime. Each Timer object has one of these, which it * shares with its TimerThread. Internally this class uses a heap, which * offers log(n) performance for the add, removeMin and rescheduleMin * operations, and constant time performance for the getMin operation. * {@description.close} */ class TaskQueue { /** {@collect.stats} * {@description.open} * Priority queue represented as a balanced binary heap: the two children * of queue[n] are queue[2*n] and queue[2*n+1]. The priority queue is * ordered on the nextExecutionTime field: The TimerTask with the lowest * nextExecutionTime is in queue[1] (assuming the queue is nonempty). For * each node n in the heap, and each descendant of n, d, * n.nextExecutionTime <= d.nextExecutionTime. * {@description.close} */ private TimerTask[] queue = new TimerTask[128]; /** {@collect.stats} * {@description.open} * The number of tasks in the priority queue. (The tasks are stored in * queue[1] up to queue[size]). * {@description.close} */ private int size = 0; /** {@collect.stats} * {@description.open} * Returns the number of tasks currently on the queue. * {@description.close} */ int size() { return size; } /** {@collect.stats} * {@description.open} * Adds a new task to the priority queue. * {@description.close} */ void add(TimerTask task) { // Grow backing store if necessary if (size + 1 == queue.length) queue = Arrays.copyOf(queue, 2*queue.length); queue[++size] = task; fixUp(size); } /** {@collect.stats} * {@description.open} * Return the "head task" of the priority queue. (The head task is an * task with the lowest nextExecutionTime.) * {@description.close} */ TimerTask getMin() { return queue[1]; } /** {@collect.stats} * {@description.open} * Return the ith task in the priority queue, where i ranges from 1 (the * head task, which is returned by getMin) to the number of tasks on the * queue, inclusive. * {@description.close} */ TimerTask get(int i) { return queue[i]; } /** {@collect.stats} * {@description.open} * Remove the head task from the priority queue. * {@description.close} */ void removeMin() { queue[1] = queue[size]; queue[size--] = null; // Drop extra reference to prevent memory leak fixDown(1); } /** {@collect.stats} * {@description.open} * Removes the ith element from queue without regard for maintaining * the heap invariant. Recall that queue is one-based, so * 1 <= i <= size. * {@description.close} */ void quickRemove(int i) { assert i <= size; queue[i] = queue[size]; queue[size--] = null; // Drop extra ref to prevent memory leak } /** {@collect.stats} * {@description.open} * Sets the nextExecutionTime associated with the head task to the * specified value, and adjusts priority queue accordingly. * {@description.close} */ void rescheduleMin(long newTime) { queue[1].nextExecutionTime = newTime; fixDown(1); } /** {@collect.stats} * {@description.open} * Returns true if the priority queue contains no elements. * {@description.close} */ boolean isEmpty() { return size==0; } /** {@collect.stats} * {@description.open} * Removes all elements from the priority queue. * {@description.close} */ void clear() { // Null out task references to prevent memory leak for (int i=1; i<=size; i++) queue[i] = null; size = 0; } /** {@collect.stats} * {@description.open} * Establishes the heap invariant (described above) assuming the heap * satisfies the invariant except possibly for the leaf-node indexed by k * (which may have a nextExecutionTime less than its parent's). * * This method functions by "promoting" queue[k] up the hierarchy * (by swapping it with its parent) repeatedly until queue[k]'s * nextExecutionTime is greater than or equal to that of its parent. * {@description.close} */ private void fixUp(int k) { while (k > 1) { int j = k >> 1; if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime) break; TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; k = j; } } /** {@collect.stats} * {@description.open} * Establishes the heap invariant (described above) in the subtree * rooted at k, which is assumed to satisfy the heap invariant except * possibly for node k itself (which may have a nextExecutionTime greater * than its children's). * * This method functions by "demoting" queue[k] down the hierarchy * (by swapping it with its smaller child) repeatedly until queue[k]'s * nextExecutionTime is less than or equal to those of its children. * {@description.close} */ private void fixDown(int k) { int j; while ((j = k << 1) <= size && j > 0) { if (j < size && queue[j].nextExecutionTime > queue[j+1].nextExecutionTime) j++; // j indexes smallest kid if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime) break; TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; k = j; } } /** {@collect.stats} * {@description.open} * Establishes the heap invariant (described above) in the entire tree, * assuming nothing about the order of the elements prior to the call. * {@description.close} */ void heapify() { for (int i = size/2; i >= 1; i--) fixDown(i); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Josh Bloch of Google Inc. and released to the public domain, * as explained at http://creativecommons.org/licenses/publicdomain. */ package java.util; import java.io.*; /** {@collect.stats} * {@description.open} * Resizable-array implementation of the {@link Deque} interface. Array * deques have no capacity restrictions; they grow as necessary to support * usage. * {@description.close} * {@description.open synchronization} * They are not thread-safe; in the absence of external * synchronization, they do not support concurrent access by multiple threads. * {@description.close} * {@property.open Property:java.util.ArrayDeque_NonNull} * Null elements are prohibited. * {@property.close} * {@description.open} * This class is likely to be faster than * {@link Stack} when used as a stack, and faster than {@link LinkedList} * when used as a queue. * {@description.close} * * {@description.open} * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time. * Exceptions include {@link #remove(Object) remove}, {@link * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence * removeLastOccurrence}, {@link #contains contains}, {@link #iterator * iterator.remove()}, and the bulk operations, all of which run in linear * time. * {@description.close} * * {@property.open runtime formal:java.util.ArrayDeque_UnsafeIterator} * <p>The iterators returned by this class's <tt>iterator</tt> method are * <i>fail-fast</i>: If the deque is modified at any time after the iterator * is created, in any way except through the iterator's own <tt>remove</tt> * method, the iterator will generally throw a {@link * ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the * future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * {@property.close} * * {@description.open} * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch and Doug Lea * @since 1.6 * @param <E> the type of elements held in this collection */ public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable { /** {@collect.stats} * {@description.open} * The array in which the elements of the deque are stored. * The capacity of the deque is the length of this array, which is * always a power of two. The array is never allowed to become * full, except transiently within an addX method where it is * resized (see doubleCapacity) immediately upon becoming full, * thus avoiding head and tail wrapping around to equal each * other. We also guarantee that all array cells not holding * deque elements are always null. * {@description.close} */ private transient E[] elements; /** {@collect.stats} * {@description.open} * The index of the element at the head of the deque (which is the * element that would be removed by remove() or pop()); or an * arbitrary number equal to tail if the deque is empty. * {@description.close} */ private transient int head; /** {@collect.stats} * {@description.open} * The index at which the next element would be added to the tail * of the deque (via addLast(E), add(E), or push(E)). * {@description.close} */ private transient int tail; /** {@collect.stats} * {@description.open} * The minimum capacity that we'll use for a newly created deque. * Must be a power of 2. * {@description.close} */ private static final int MIN_INITIAL_CAPACITY = 8; // ****** Array allocation and resizing utilities ****** /** {@collect.stats} * {@description.open} * Allocate empty array to hold the given number of elements. * {@description.close} * * @param numElements the number of elements to hold */ private void allocateElements(int numElements) { int initialCapacity = MIN_INITIAL_CAPACITY; // Find the best power of two to hold elements. // Tests "<=" because arrays aren't kept full. if (numElements >= initialCapacity) { initialCapacity = numElements; initialCapacity |= (initialCapacity >>> 1); initialCapacity |= (initialCapacity >>> 2); initialCapacity |= (initialCapacity >>> 4); initialCapacity |= (initialCapacity >>> 8); initialCapacity |= (initialCapacity >>> 16); initialCapacity++; if (initialCapacity < 0) // Too many elements, must back off initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements } elements = (E[]) new Object[initialCapacity]; } /** {@collect.stats} * {@description.open} * Double the capacity of this deque. Call only when full, i.e., * when head and tail have wrapped around to become equal. * {@description.close} */ private void doubleCapacity() { assert head == tail; int p = head; int n = elements.length; int r = n - p; // number of elements to the right of p int newCapacity = n << 1; if (newCapacity < 0) throw new IllegalStateException("Sorry, deque too big"); Object[] a = new Object[newCapacity]; System.arraycopy(elements, p, a, 0, r); System.arraycopy(elements, 0, a, r, p); elements = (E[])a; head = 0; tail = n; } /** {@collect.stats} * {@description.open} * Copies the elements from our element array into the specified array, * in order (from first to last element in the deque). It is assumed * that the array is large enough to hold all elements in the deque. * {@description.close} * * @return its argument */ private <T> T[] copyElements(T[] a) { if (head < tail) { System.arraycopy(elements, head, a, 0, size()); } else if (head > tail) { int headPortionLen = elements.length - head; System.arraycopy(elements, head, a, 0, headPortionLen); System.arraycopy(elements, 0, a, headPortionLen, tail); } return a; } /** {@collect.stats} * {@description.open} * Constructs an empty array deque with an initial capacity * sufficient to hold 16 elements. * {@description.close} */ public ArrayDeque() { elements = (E[]) new Object[16]; } /** {@collect.stats} * {@description.open} * Constructs an empty array deque with an initial capacity * sufficient to hold the specified number of elements. * {@description.close} * * @param numElements lower bound on initial capacity of the deque */ public ArrayDeque(int numElements) { allocateElements(numElements); } /** {@collect.stats} * {@description.open} * Constructs a deque containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. (The first element returned by the collection's * iterator becomes the first element, or <i>front</i> of the * deque.) * {@description.close} * * @param c the collection whose elements are to be placed into the deque * @throws NullPointerException if the specified collection is null */ public ArrayDeque(Collection<? extends E> c) { allocateElements(c.size()); addAll(c); } // The main insertion and extraction methods are addFirst, // addLast, pollFirst, pollLast. The other methods are defined in // terms of these. /** {@collect.stats} * {@description.open} * Inserts the specified element at the front of this deque. * {@description.close} * {@property.open formal:java.util.ArrayDeque_NonNull} * Inserting <tt>null</tt> is not allowed. * {@property.close} * * @param e the element to add * @throws NullPointerException if the specified element is null */ public void addFirst(E e) { if (e == null) throw new NullPointerException(); elements[head = (head - 1) & (elements.length - 1)] = e; if (head == tail) doubleCapacity(); } /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this deque. * * <p>This method is equivalent to {@link #add}. * {@description.close} * {@property.open formal:java.util.ArrayDeque_NonNull} * Inserting <tt>null</tt> is not allowed. * {@property.close} * * @param e the element to add * @throws NullPointerException if the specified element is null */ public void addLast(E e) { if (e == null) throw new NullPointerException(); elements[tail] = e; if ( (tail = (tail + 1) & (elements.length - 1)) == head) doubleCapacity(); } /** {@collect.stats} * {@description.open} * Inserts the specified element at the front of this deque. * {@description.close} * {@property.open formal:java.util.ArrayDeque_NonNull} * Inserting <tt>null</tt> is not allowed. * {@property.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Deque#offerFirst}) * @throws NullPointerException if the specified element is null */ public boolean offerFirst(E e) { addFirst(e); return true; } /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this deque. * {@description.close} * {@property.open formal:java.util.ArrayDeque_NonNull} * Inserting <tt>null</tt> is not allowed. * {@property.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Deque#offerLast}) * @throws NullPointerException if the specified element is null */ public boolean offerLast(E e) { addLast(e); return true; } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E removeFirst() { E x = pollFirst(); if (x == null) throw new NoSuchElementException(); return x; } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E removeLast() { E x = pollLast(); if (x == null) throw new NoSuchElementException(); return x; } public E pollFirst() { int h = head; E result = elements[h]; // Element is null if deque empty if (result == null) return null; elements[h] = null; // Must null out slot head = (h + 1) & (elements.length - 1); return result; } public E pollLast() { int t = (tail - 1) & (elements.length - 1); E result = elements[t]; if (result == null) return null; elements[t] = null; tail = t; return result; } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E getFirst() { E x = elements[head]; if (x == null) throw new NoSuchElementException(); return x; } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E getLast() { E x = elements[(tail - 1) & (elements.length - 1)]; if (x == null) throw new NoSuchElementException(); return x; } public E peekFirst() { return elements[head]; // elements[head] is null if deque empty } public E peekLast() { return elements[(tail - 1) & (elements.length - 1)]; } /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element in this * deque (when traversing the deque from head to tail). * If the deque does not contain the element, it is unchanged. * More formally, removes the first element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * {@description.close} * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if the deque contained the specified element */ public boolean removeFirstOccurrence(Object o) { if (o == null) return false; int mask = elements.length - 1; int i = head; E x; while ( (x = elements[i]) != null) { if (o.equals(x)) { delete(i); return true; } i = (i + 1) & mask; } return false; } /** {@collect.stats} * {@description.open} * Removes the last occurrence of the specified element in this * deque (when traversing the deque from head to tail). * If the deque does not contain the element, it is unchanged. * More formally, removes the last element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * {@description.close} * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if the deque contained the specified element */ public boolean removeLastOccurrence(Object o) { if (o == null) return false; int mask = elements.length - 1; int i = (tail - 1) & mask; E x; while ( (x = elements[i]) != null) { if (o.equals(x)) { delete(i); return true; } i = (i - 1) & mask; } return false; } // *** Queue methods *** /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this deque. * * <p>This method is equivalent to {@link #addLast}. * {@description.close} * {@property.open formal:java.util.ArrayDeque_NonNull} * Inserting <tt>null</tt> is not allowed. * {@property.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws NullPointerException if the specified element is null */ public boolean add(E e) { addLast(e); return true; } /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this deque. * * <p>This method is equivalent to {@link #offerLast}. * {@description.close} * {@property.open formal:java.util.ArrayDeque_NonNull} * Inserting <tt>null</tt> is not allowed. * {@property.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Queue#offer}) * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { return offerLast(e); } /** {@collect.stats} * {@description.open} * Retrieves and removes the head of the queue represented by this deque. * * This method differs from {@link #poll poll} only in that it throws an * exception if this deque is empty. * * <p>This method is equivalent to {@link #removeFirst}. * {@description.close} * * @return the head of the queue represented by this deque * @throws NoSuchElementException {@inheritDoc} */ public E remove() { return removeFirst(); } /** {@collect.stats} * {@description.open} * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque), or returns * <tt>null</tt> if this deque is empty. * * <p>This method is equivalent to {@link #pollFirst}. * {@description.close} * * @return the head of the queue represented by this deque, or * <tt>null</tt> if this deque is empty */ public E poll() { return pollFirst(); } /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head of the queue represented by * this deque. This method differs from {@link #peek peek} only in * that it throws an exception if this deque is empty. * * <p>This method is equivalent to {@link #getFirst}. * {@description.close} * * @return the head of the queue represented by this deque * @throws NoSuchElementException {@inheritDoc} */ public E element() { return getFirst(); } /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head of the queue represented by * this deque, or returns <tt>null</tt> if this deque is empty. * * <p>This method is equivalent to {@link #peekFirst}. * {@description.close} * * @return the head of the queue represented by this deque, or * <tt>null</tt> if this deque is empty */ public E peek() { return peekFirst(); } // *** Stack methods *** /** {@collect.stats} * {@description.open} * Pushes an element onto the stack represented by this deque. In other * words, inserts the element at the front of this deque. * * <p>This method is equivalent to {@link #addFirst}. * {@description.close} * {@property.open formal:java.util.ArrayDeque_NonNull} * Inserting <tt>null</tt> is not allowed. * {@property.close} * * @param e the element to push * @throws NullPointerException if the specified element is null */ public void push(E e) { addFirst(e); } /** {@collect.stats} * {@description.open} * Pops an element from the stack represented by this deque. In other * words, removes and returns the first element of this deque. * * <p>This method is equivalent to {@link #removeFirst()}. * {@description.close} * * @return the element at the front of this deque (which is the top * of the stack represented by this deque) * @throws NoSuchElementException {@inheritDoc} */ public E pop() { return removeFirst(); } private void checkInvariants() { assert elements[tail] == null; assert head == tail ? elements[head] == null : (elements[head] != null && elements[(tail - 1) & (elements.length - 1)] != null); assert elements[(head - 1) & (elements.length - 1)] == null; } /** {@collect.stats} * {@description.open} * Removes the element at the specified position in the elements array, * adjusting head and tail as necessary. This can result in motion of * elements backwards or forwards in the array. * * <p>This method is called delete rather than remove to emphasize * that its semantics differ from those of {@link List#remove(int)}. * {@description.close} * * @return true if elements moved backwards */ private boolean delete(int i) { checkInvariants(); final E[] elements = this.elements; final int mask = elements.length - 1; final int h = head; final int t = tail; final int front = (i - h) & mask; final int back = (t - i) & mask; // Invariant: head <= i < tail mod circularity if (front >= ((t - h) & mask)) throw new ConcurrentModificationException(); // Optimize for least element motion if (front < back) { if (h <= i) { System.arraycopy(elements, h, elements, h + 1, front); } else { // Wrap around System.arraycopy(elements, 0, elements, 1, i); elements[0] = elements[mask]; System.arraycopy(elements, h, elements, h + 1, mask - h); } elements[h] = null; head = (h + 1) & mask; return false; } else { if (i < t) { // Copy the null tail as well System.arraycopy(elements, i + 1, elements, i, back); tail = t - 1; } else { // Wrap around System.arraycopy(elements, i + 1, elements, i, mask - i); elements[mask] = elements[0]; System.arraycopy(elements, 1, elements, 0, t); tail = (t - 1) & mask; } return true; } } // *** Collection Methods *** /** {@collect.stats} * {@description.open} * Returns the number of elements in this deque. * {@description.close} * * @return the number of elements in this deque */ public int size() { return (tail - head) & (elements.length - 1); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this deque contains no elements. * {@description.close} * * @return <tt>true</tt> if this deque contains no elements */ public boolean isEmpty() { return head == tail; } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this deque. The elements * will be ordered from first (head) to last (tail). This is the same * order that elements would be dequeued (via successive calls to * {@link #remove} or popped (via successive calls to {@link #pop}). * {@description.close} * * @return an iterator over the elements in this deque */ public Iterator<E> iterator() { return new DeqIterator(); } public Iterator<E> descendingIterator() { return new DescendingIterator(); } private class DeqIterator implements Iterator<E> { /** {@collect.stats} * {@description.open} * Index of element to be returned by subsequent call to next. * {@description.close} */ private int cursor = head; /** {@collect.stats} * {@description.open} * Tail recorded at construction (also in remove), to stop * iterator and also to check for comodification. * {@description.close} */ private int fence = tail; /** {@collect.stats} * {@description.open} * Index of element returned by most recent call to next. * Reset to -1 if element is deleted by a call to remove. * {@description.close} */ private int lastRet = -1; public boolean hasNext() { return cursor != fence; } public E next() { if (cursor == fence) throw new NoSuchElementException(); E result = elements[cursor]; // This check doesn't catch all possible comodifications, // but does catch the ones that corrupt traversal if (tail != fence || result == null) throw new ConcurrentModificationException(); lastRet = cursor; cursor = (cursor + 1) & (elements.length - 1); return result; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); if (delete(lastRet)) { // if left-shifted, undo increment in next() cursor = (cursor - 1) & (elements.length - 1); fence = tail; } lastRet = -1; } } private class DescendingIterator implements Iterator<E> { /* * This class is nearly a mirror-image of DeqIterator, using * tail instead of head for initial cursor, and head instead of * tail for fence. */ private int cursor = tail; private int fence = head; private int lastRet = -1; public boolean hasNext() { return cursor != fence; } public E next() { if (cursor == fence) throw new NoSuchElementException(); cursor = (cursor - 1) & (elements.length - 1); E result = elements[cursor]; if (head != fence || result == null) throw new ConcurrentModificationException(); lastRet = cursor; return result; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); if (!delete(lastRet)) { cursor = (cursor + 1) & (elements.length - 1); fence = head; } lastRet = -1; } } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this deque contains the specified element. * More formally, returns <tt>true</tt> if and only if this deque contains * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>. * {@description.close} * * @param o object to be checked for containment in this deque * @return <tt>true</tt> if this deque contains the specified element */ public boolean contains(Object o) { if (o == null) return false; int mask = elements.length - 1; int i = head; E x; while ( (x = elements[i]) != null) { if (o.equals(x)) return true; i = (i + 1) & mask; } return false; } /** {@collect.stats} * {@description.open} * Removes a single instance of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * <p>This method is equivalent to {@link #removeFirstOccurrence}. * {@description.close} * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if this deque contained the specified element */ public boolean remove(Object o) { return removeFirstOccurrence(o); } /** {@collect.stats} * {@description.open} * Removes all of the elements from this deque. * The deque will be empty after this call returns. * {@description.close} */ public void clear() { int h = head; int t = tail; if (h != t) { // clear all cells head = tail = 0; int i = h; int mask = elements.length - 1; do { elements[i] = null; i = (i + 1) & mask; } while (i != t); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this deque * in proper sequence (from first to last element). * * <p>The returned array will be "safe" in that no references to it are * maintained by this deque. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this deque */ public Object[] toArray() { return copyElements(new Object[size()]); } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this deque in * proper sequence (from first to last element); the runtime type of the * returned array is that of the specified array. If the deque fits in * the specified array, it is returned therein. Otherwise, a new array * is allocated with the runtime type of the specified array and the * size of this deque. * * <p>If this deque fits in the specified array with room to spare * (i.e., the array has more elements than this deque), the element in * the array immediately following the end of the deque is set to * <tt>null</tt>. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a deque known to contain only strings. * The following code can be used to dump the deque into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of the deque are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this deque * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this deque * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { int size = size(); if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size); copyElements(a); if (a.length > size) a[size] = null; return a; } // *** Object methods *** /** {@collect.stats} * {@description.open} * Returns a copy of this deque. * {@description.close} * * @return a copy of this deque */ public ArrayDeque<E> clone() { try { ArrayDeque<E> result = (ArrayDeque<E>) super.clone(); result.elements = Arrays.copyOf(elements, elements.length); return result; } catch (CloneNotSupportedException e) { throw new AssertionError(); } } /** {@collect.stats} * {@description.open} * Appease the serialization gods. * {@description.close} */ private static final long serialVersionUID = 2340985798034038923L; /** {@collect.stats} * {@description.open} * Serialize this deque. * {@description.close} * * @serialData The current size (<tt>int</tt>) of the deque, * followed by all of its elements (each an object reference) in * first-to-last order. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); // Write out size s.writeInt(size()); // Write out elements in order. int mask = elements.length - 1; for (int i = head; i != tail; i = (i + 1) & mask) s.writeObject(elements[i]); } /** {@collect.stats} * {@description.open} * Deserialize this deque. * {@description.close} */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); // Read in size and allocate array int size = s.readInt(); allocateElements(size); head = 0; tail = size; // Read in all elements in the proper order. for (int i = 0; i < size; i++) elements[i] = (E)s.readObject(); } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.*; /** {@collect.stats} * {@description.open} * <p>Hash table and linked list implementation of the <tt>Map</tt> interface, * with predictable iteration order. This implementation differs from * <tt>HashMap</tt> in that it maintains a doubly-linked list running through * all of its entries. This linked list defines the iteration ordering, * which is normally the order in which keys were inserted into the map * (<i>insertion-order</i>). Note that insertion order is not affected * if a key is <i>re-inserted</i> into the map. (A key <tt>k</tt> is * reinserted into a map <tt>m</tt> if <tt>m.put(k, v)</tt> is invoked when * <tt>m.containsKey(k)</tt> would return <tt>true</tt> immediately prior to * the invocation.) * * <p>This implementation spares its clients from the unspecified, generally * chaotic ordering provided by {@link HashMap} (and {@link Hashtable}), * without incurring the increased cost associated with {@link TreeMap}. It * can be used to produce a copy of a map that has the same order as the * original, regardless of the original map's implementation: * <pre> * void foo(Map m) { * Map copy = new LinkedHashMap(m); * ... * } * </pre> * This technique is particularly useful if a module takes a map on input, * copies it, and later returns results whose order is determined by that of * the copy. (Clients generally appreciate having things returned in the same * order they were presented.) * * <p>A special {@link #LinkedHashMap(int,float,boolean) constructor} is * provided to create a linked hash map whose order of iteration is the order * in which its entries were last accessed, from least-recently accessed to * most-recently (<i>access-order</i>). This kind of map is well-suited to * building LRU caches. Invoking the <tt>put</tt> or <tt>get</tt> method * results in an access to the corresponding entry (assuming it exists after * the invocation completes). The <tt>putAll</tt> method generates one entry * access for each mapping in the specified map, in the order that key-value * mappings are provided by the specified map's entry set iterator. <i>No * other methods generate entry accesses.</i> In particular, operations on * collection-views do <i>not</i> affect the order of iteration of the backing * map. * * <p>The {@link #removeEldestEntry(Map.Entry)} method may be overridden to * impose a policy for removing stale mappings automatically when new mappings * are added to the map. * * <p>This class provides all of the optional <tt>Map</tt> operations, and * permits null elements. Like <tt>HashMap</tt>, it provides constant-time * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and * <tt>remove</tt>), assuming the hash function disperses elements * properly among the buckets. Performance is likely to be just slightly * below that of <tt>HashMap</tt>, due to the added expense of maintaining the * linked list, with one exception: Iteration over the collection-views * of a <tt>LinkedHashMap</tt> requires time proportional to the <i>size</i> * of the map, regardless of its capacity. Iteration over a <tt>HashMap</tt> * is likely to be more expensive, requiring time proportional to its * <i>capacity</i>. * * <p>A linked hash map has two parameters that affect its performance: * <i>initial capacity</i> and <i>load factor</i>. They are defined precisely * as for <tt>HashMap</tt>. Note, however, that the penalty for choosing an * excessively high value for initial capacity is less severe for this class * than for <tt>HashMap</tt>, as iteration times for this class are unaffected * by capacity. * {@description.close} * * {@property.open formal:java.util.Collections_SynchronizedMap} * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access a linked hash map concurrently, and at least * one of the threads modifies the map structurally, it <em>must</em> be * synchronized externally. This is typically accomplished by * synchronizing on some object that naturally encapsulates the map. * * If no such object exists, the map should be "wrapped" using the * {@link Collections#synchronizedMap Collections.synchronizedMap} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the map:<pre> * Map m = Collections.synchronizedMap(new LinkedHashMap(...));</pre> * * A structural modification is any operation that adds or deletes one or more * mappings or, in the case of access-ordered linked hash maps, affects * iteration order. In insertion-ordered linked hash maps, merely changing * the value associated with a key that is already contained in the map is not * a structural modification. <strong>In access-ordered linked hash maps, * merely querying the map with <tt>get</tt> is a structural * modification.</strong>) * {@property.close} * * {@property.open formal:java.util.Map_UnsafeIterator} * <p>The iterators returned by the <tt>iterator</tt> method of the collections * returned by all of this class's collection view methods are * <em>fail-fast</em>: if the map is structurally modified at any time after * the iterator is created, in any way except through the iterator's own * <tt>remove</tt> method, the iterator will throw a {@link * ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * {@property.close} * * {@description.open} * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Josh Bloch * @see Object#hashCode() * @see Collection * @see Map * @see HashMap * @see TreeMap * @see Hashtable * @since 1.4 */ public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> { private static final long serialVersionUID = 3801124242820219131L; /** {@collect.stats} * {@description.open} * The head of the doubly linked list. * {@description.close} */ private transient Entry<K,V> header; /** {@collect.stats} * {@description.open} * The iteration ordering method for this linked hash map: <tt>true</tt> * for access-order, <tt>false</tt> for insertion-order. * {@description.close} * * @serial */ private final boolean accessOrder; /** {@collect.stats} * {@description.open} * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance * with the specified initial capacity and load factor. * {@description.close} * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive */ public LinkedHashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); accessOrder = false; } /** {@collect.stats} * {@description.open} * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance * with the specified initial capacity and a default load factor (0.75). * {@description.close} * * @param initialCapacity the initial capacity * @throws IllegalArgumentException if the initial capacity is negative */ public LinkedHashMap(int initialCapacity) { super(initialCapacity); accessOrder = false; } /** {@collect.stats} * {@description.open} * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance * with the default initial capacity (16) and load factor (0.75). * {@description.close} */ public LinkedHashMap() { super(); accessOrder = false; } /** {@collect.stats} * {@description.open} * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with * the same mappings as the specified map. The <tt>LinkedHashMap</tt> * instance is created with a default load factor (0.75) and an initial * capacity sufficient to hold the mappings in the specified map. * {@description.close} * * @param m the map whose mappings are to be placed in this map * @throws NullPointerException if the specified map is null */ public LinkedHashMap(Map<? extends K, ? extends V> m) { super(m); accessOrder = false; } /** {@collect.stats} * {@description.open} * Constructs an empty <tt>LinkedHashMap</tt> instance with the * specified initial capacity, load factor and ordering mode. * {@description.close} * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @param accessOrder the ordering mode - <tt>true</tt> for * access-order, <tt>false</tt> for insertion-order * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive */ public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { super(initialCapacity, loadFactor); this.accessOrder = accessOrder; } /** {@collect.stats} * {@description.open} * Called by superclass constructors and pseudoconstructors (clone, * readObject) before any entries are inserted into the map. Initializes * the chain. * {@description.close} */ void init() { header = new Entry<K,V>(-1, null, null, null); header.before = header.after = header; } /** {@collect.stats} * {@description.open} * Transfers all entries to new table array. This method is called * by superclass resize. It is overridden for performance, as it is * faster to iterate using our linked list. * {@description.close} */ void transfer(HashMap.Entry[] newTable) { int newCapacity = newTable.length; for (Entry<K,V> e = header.after; e != header; e = e.after) { int index = indexFor(e.hash, newCapacity); e.next = newTable[index]; newTable[index] = e; } } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map maps one or more keys to the * specified value. * {@description.close} * * @param value value whose presence in this map is to be tested * @return <tt>true</tt> if this map maps one or more keys to the * specified value */ public boolean containsValue(Object value) { // Overridden to take advantage of faster iterator if (value==null) { for (Entry e = header.after; e != header; e = e.after) if (e.value==null) return true; } else { for (Entry e = header.after; e != header; e = e.after) if (value.equals(e.value)) return true; } return false; } /** {@collect.stats} * {@description.open} * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * {@description.close} */ public V get(Object key) { Entry<K,V> e = (Entry<K,V>)getEntry(key); if (e == null) return null; e.recordAccess(this); return e.value; } /** {@collect.stats} * {@description.open} * Removes all of the mappings from this map. * The map will be empty after this call returns. * {@description.close} */ public void clear() { super.clear(); header.before = header.after = header; } /** {@collect.stats} * {@description.open} * LinkedHashMap entry. * {@description.close} */ private static class Entry<K,V> extends HashMap.Entry<K,V> { // These fields comprise the doubly linked list used for iteration. Entry<K,V> before, after; Entry(int hash, K key, V value, HashMap.Entry<K,V> next) { super(hash, key, value, next); } /** {@collect.stats} * {@description.open} * Removes this entry from the linked list. * {@description.close} */ private void remove() { before.after = after; after.before = before; } /** {@collect.stats} * {@description.open} * Inserts this entry before the specified existing entry in the list. * {@description.close} */ private void addBefore(Entry<K,V> existingEntry) { after = existingEntry; before = existingEntry.before; before.after = this; after.before = this; } /** {@collect.stats} * {@description.open} * This method is invoked by the superclass whenever the value * of a pre-existing entry is read by Map.get or modified by Map.set. * If the enclosing Map is access-ordered, it moves the entry * to the end of the list; otherwise, it does nothing. * {@description.close} */ void recordAccess(HashMap<K,V> m) { LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m; if (lm.accessOrder) { lm.modCount++; remove(); addBefore(lm.header); } } void recordRemoval(HashMap<K,V> m) { remove(); } } private abstract class LinkedHashIterator<T> implements Iterator<T> { Entry<K,V> nextEntry = header.after; Entry<K,V> lastReturned = null; /** {@collect.stats} * {@description.open} * The modCount value that the iterator believes that the backing * List should have. If this expectation is violated, the iterator * has detected concurrent modification. * {@description.close} */ int expectedModCount = modCount; public boolean hasNext() { return nextEntry != header; } public void remove() { if (lastReturned == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); LinkedHashMap.this.remove(lastReturned.key); lastReturned = null; expectedModCount = modCount; } Entry<K,V> nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (nextEntry == header) throw new NoSuchElementException(); Entry<K,V> e = lastReturned = nextEntry; nextEntry = e.after; return e; } } private class KeyIterator extends LinkedHashIterator<K> { public K next() { return nextEntry().getKey(); } } private class ValueIterator extends LinkedHashIterator<V> { public V next() { return nextEntry().value; } } private class EntryIterator extends LinkedHashIterator<Map.Entry<K,V>> { public Map.Entry<K,V> next() { return nextEntry(); } } // These Overrides alter the behavior of superclass view iterator() methods Iterator<K> newKeyIterator() { return new KeyIterator(); } Iterator<V> newValueIterator() { return new ValueIterator(); } Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); } /** {@collect.stats} * {@description.open} * This override alters behavior of superclass put method. It causes newly * allocated entry to get inserted at the end of the linked list and * removes the eldest entry if appropriate. * {@description.close} */ void addEntry(int hash, K key, V value, int bucketIndex) { createEntry(hash, key, value, bucketIndex); // Remove eldest entry if instructed, else grow capacity if appropriate Entry<K,V> eldest = header.after; if (removeEldestEntry(eldest)) { removeEntryForKey(eldest.key); } else { if (size >= threshold) resize(2 * table.length); } } /** {@collect.stats} * {@description.open} * This override differs from addEntry in that it doesn't resize the * table or remove the eldest entry. * {@description.close} */ void createEntry(int hash, K key, V value, int bucketIndex) { HashMap.Entry<K,V> old = table[bucketIndex]; Entry<K,V> e = new Entry<K,V>(hash, key, value, old); table[bucketIndex] = e; e.addBefore(header); size++; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map should remove its eldest entry. * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after * inserting a new entry into the map. It provides the implementor * with the opportunity to remove the eldest entry each time a new one * is added. This is useful if the map represents a cache: it allows * the map to reduce memory consumption by deleting stale entries. * * <p>Sample use: this override will allow the map to grow up to 100 * entries and then delete the eldest entry each time a new entry is * added, maintaining a steady state of 100 entries. * <pre> * private static final int MAX_ENTRIES = 100; * * protected boolean removeEldestEntry(Map.Entry eldest) { * return size() > MAX_ENTRIES; * } * </pre> * * <p>This method typically does not modify the map in any way, * instead allowing the map to modify itself as directed by its * return value. It <i>is</i> permitted for this method to modify * the map directly, but if it does so, it <i>must</i> return * <tt>false</tt> (indicating that the map should not attempt any * further modification). The effects of returning <tt>true</tt> * after modifying the map from within this method are unspecified. * * <p>This implementation merely returns <tt>false</tt> (so that this * map acts like a normal map - the eldest element is never removed). * {@description.close} * * @param eldest The least recently inserted entry in the map, or if * this is an access-ordered map, the least recently accessed * entry. This is the entry that will be removed it this * method returns <tt>true</tt>. If the map was empty prior * to the <tt>put</tt> or <tt>putAll</tt> invocation resulting * in this invocation, this will be the entry that was just * inserted; in other words, if the map contains a single * entry, the eldest entry is also the newest. * @return <tt>true</tt> if the eldest entry should be removed * from the map; <tt>false</tt> if it should be retained. */ protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return false; } }
Java
/* * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved * * The original version of this source code and documentation * is copyrighted and owned by Taligent, Inc., a wholly-owned * subsidiary of IBM. These materials are provided under terms * of a License Agreement between Taligent and Sun. This technology * is protected by multiple US and International patents. * * This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.util; import sun.util.ResourceBundleEnumeration; /** {@collect.stats} * {@description.open} * <code>ListResourceBundle</code> is an abstract subclass of * <code>ResourceBundle</code> that manages resources for a locale * in a convenient and easy to use list. See <code>ResourceBundle</code> for * more information about resource bundles in general. * {@description.close} * * {@property.open enforced} * <P> * Subclasses must override <code>getContents</code> and provide an array, * where each item in the array is a pair of objects. * The first element of each pair is the key, which must be a * <code>String</code>, and the second element is the value associated with * that key. * {@property.close} * * {@description.open} * <p> * The following <a name="sample">example</a> shows two members of a resource * bundle family with the base name "MyResources". * "MyResources" is the default member of the bundle family, and * "MyResources_fr" is the French member. * These members are based on <code>ListResourceBundle</code> * (a related <a href="PropertyResourceBundle.html#sample">example</a> shows * how you can add a bundle to this family that's based on a properties file). * The keys in this example are of the form "s1" etc. The actual * keys are entirely up to your choice, so long as they are the same as * the keys you use in your program to retrieve the objects from the bundle. * Keys are case-sensitive. * <blockquote> * <pre> * * public class MyResources extends ListResourceBundle { * protected Object[][] getContents() { * return new Object[][] = { * // LOCALIZE THIS * {"s1", "The disk \"{1}\" contains {0}."}, // MessageFormat pattern * {"s2", "1"}, // location of {0} in pattern * {"s3", "My Disk"}, // sample disk name * {"s4", "no files"}, // first ChoiceFormat choice * {"s5", "one file"}, // second ChoiceFormat choice * {"s6", "{0,number} files"}, // third ChoiceFormat choice * {"s7", "3 Mar 96"}, // sample date * {"s8", new Dimension(1,5)} // real object, not just string * // END OF MATERIAL TO LOCALIZE * }; * } * } * * public class MyResources_fr extends ListResourceBundle { * protected Object[][] getContents() { * return new Object[][] = { * // LOCALIZE THIS * {"s1", "Le disque \"{1}\" {0}."}, // MessageFormat pattern * {"s2", "1"}, // location of {0} in pattern * {"s3", "Mon disque"}, // sample disk name * {"s4", "ne contient pas de fichiers"}, // first ChoiceFormat choice * {"s5", "contient un fichier"}, // second ChoiceFormat choice * {"s6", "contient {0,number} fichiers"}, // third ChoiceFormat choice * {"s7", "3 mars 1996"}, // sample date * {"s8", new Dimension(1,3)} // real object, not just string * // END OF MATERIAL TO LOCALIZE * }; * } * } * </pre> * </blockquote> * {@description.close} * @see ResourceBundle * @see PropertyResourceBundle * @since JDK1.1 */ public abstract class ListResourceBundle extends ResourceBundle { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ public ListResourceBundle() { } // Implements java.util.ResourceBundle.handleGetObject; inherits javadoc specification. public final Object handleGetObject(String key) { // lazily load the lookup hashtable. if (lookup == null) { loadLookup(); } if (key == null) { throw new NullPointerException(); } return lookup.get(key); // this class ignores locales } /** {@collect.stats} * {@description.open} * Returns an <code>Enumeration</code> of the keys contained in * this <code>ResourceBundle</code> and its parent bundles. * {@description.close} * * @return an <code>Enumeration</code> of the keys contained in * this <code>ResourceBundle</code> and its parent bundles. * @see #keySet() */ public Enumeration<String> getKeys() { // lazily load the lookup hashtable. if (lookup == null) { loadLookup(); } ResourceBundle parent = this.parent; return new ResourceBundleEnumeration(lookup.keySet(), (parent != null) ? parent.getKeys() : null); } /** {@collect.stats} * {@description.open} * Returns a <code>Set</code> of the keys contained * <em>only</em> in this <code>ResourceBundle</code>. * {@description.close} * * @return a <code>Set</code> of the keys contained only in this * <code>ResourceBundle</code> * @since 1.6 * @see #keySet() */ protected Set<String> handleKeySet() { if (lookup == null) { loadLookup(); } return lookup.keySet(); } /** {@collect.stats} * {@description.open} * Returns an array in which each item is a pair of objects in an * <code>Object</code> array. The first element of each pair is * the key, which must be a <code>String</code>, and the second * element is the value associated with that key. See the class * description for details. * {@description.close} * * @return an array of an <code>Object</code> array representing a * key-value pair. */ abstract protected Object[][] getContents(); // ==================privates==================== /** {@collect.stats} * {@description.open} * We lazily load the lookup hashtable. This function does the * loading. * {@description.close} */ private synchronized void loadLookup() { if (lookup != null) return; Object[][] contents = getContents(); HashMap<String,Object> temp = new HashMap<String,Object>(contents.length); for (int i = 0; i < contents.length; ++i) { // key must be non-null String, value must be non-null String key = (String) contents[i][0]; Object value = contents[i][1]; if (key == null || value == null) { throw new NullPointerException(); } temp.put(key, value); } lookup = temp; } private Map<String,Object> lookup = null; }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea and Josh Bloch with assistance from members of JCP * JSR-166 Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util; /** {@collect.stats} * {@description.open} * A {@link SortedSet} extended with navigation methods reporting * closest matches for given search targets. Methods {@code lower}, * {@code floor}, {@code ceiling}, and {@code higher} return elements * respectively less than, less than or equal, greater than or equal, * and greater than a given element, returning {@code null} if there * is no such element. A {@code NavigableSet} may be accessed and * traversed in either ascending or descending order. The {@code * descendingSet} method returns a view of the set with the senses of * all relational and directional methods inverted. The performance of * ascending operations and views is likely to be faster than that of * descending ones. This interface additionally defines methods * {@code pollFirst} and {@code pollLast} that return and remove the * lowest and highest element, if one exists, else returning {@code * null}. Methods {@code subSet}, {@code headSet}, * and {@code tailSet} differ from the like-named {@code * SortedSet} methods in accepting additional arguments describing * whether lower and upper bounds are inclusive versus exclusive. * Subsets of any {@code NavigableSet} must implement the {@code * NavigableSet} interface. * * <p> The return values of navigation methods may be ambiguous in * implementations that permit {@code null} elements. However, even * in this case the result can be disambiguated by checking * {@code contains(null)}. To avoid such issues, implementations of * this interface are encouraged to <em>not</em> permit insertion of * {@code null} elements. (Note that sorted sets of {@link * Comparable} elements intrinsically do not permit {@code null}.) * * <p>Methods * {@link #subSet(Object, Object) subSet(E, E)}, * {@link #headSet(Object) headSet(E)}, and * {@link #tailSet(Object) tailSet(E)} * are specified to return {@code SortedSet} to allow existing * implementations of {@code SortedSet} to be compatibly retrofitted to * implement {@code NavigableSet}, but extensions and implementations * of this interface are encouraged to override these methods to return * {@code NavigableSet}. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Doug Lea * @author Josh Bloch * @param <E> the type of elements maintained by this set * @since 1.6 */ public interface NavigableSet<E> extends SortedSet<E> { /** {@collect.stats} * {@description.open} * Returns the greatest element in this set strictly less than the * given element, or {@code null} if there is no such element. * {@description.close} * * @param e the value to match * @return the greatest element less than {@code e}, * or {@code null} if there is no such element * @throws ClassCastException if the specified element cannot be * compared with the elements currently in the set * @throws NullPointerException if the specified element is null * and this set does not permit null elements */ E lower(E e); /** {@collect.stats} * {@description.open} * Returns the greatest element in this set less than or equal to * the given element, or {@code null} if there is no such element. * {@description.close} * * @param e the value to match * @return the greatest element less than or equal to {@code e}, * or {@code null} if there is no such element * @throws ClassCastException if the specified element cannot be * compared with the elements currently in the set * @throws NullPointerException if the specified element is null * and this set does not permit null elements */ E floor(E e); /** {@collect.stats} * {@description.open} * Returns the least element in this set greater than or equal to * the given element, or {@code null} if there is no such element. * {@description.close} * * @param e the value to match * @return the least element greater than or equal to {@code e}, * or {@code null} if there is no such element * @throws ClassCastException if the specified element cannot be * compared with the elements currently in the set * @throws NullPointerException if the specified element is null * and this set does not permit null elements */ E ceiling(E e); /** {@collect.stats} * {@description.open} * Returns the least element in this set strictly greater than the * given element, or {@code null} if there is no such element. * {@description.close} * * @param e the value to match * @return the least element greater than {@code e}, * or {@code null} if there is no such element * @throws ClassCastException if the specified element cannot be * compared with the elements currently in the set * @throws NullPointerException if the specified element is null * and this set does not permit null elements */ E higher(E e); /** {@collect.stats} * {@description.open} * Retrieves and removes the first (lowest) element, * or returns {@code null} if this set is empty. * {@description.close} * * @return the first element, or {@code null} if this set is empty */ E pollFirst(); /** {@collect.stats} * {@description.open} * Retrieves and removes the last (highest) element, * or returns {@code null} if this set is empty. * {@description.close} * * @return the last element, or {@code null} if this set is empty */ E pollLast(); /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this set, in ascending order. * {@description.close} * * @return an iterator over the elements in this set, in ascending order */ Iterator<E> iterator(); /** {@collect.stats} * {@description.open} * Returns a reverse order view of the elements contained in this set. * The descending set is backed by this set, so changes to the set are * reflected in the descending set, and vice-versa. * {@description.close} * {@property.open formal:java.util.NavigableSet_Modification} * If either set is * modified while an iteration over either set is in progress (except * through the iterator's own {@code remove} operation), the results of * the iteration are undefined. * {@property.close} * * {@description.open} * <p>The returned set has an ordering equivalent to * <tt>{@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator())</tt>. * The expression {@code s.descendingSet().descendingSet()} returns a * view of {@code s} essentially equivalent to {@code s}. * {@description.close} * * @return a reverse order view of this set */ NavigableSet<E> descendingSet(); /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this set, in descending order. * Equivalent in effect to {@code descendingSet().iterator()}. * {@description.close} * * @return an iterator over the elements in this set, in descending order */ Iterator<E> descendingIterator(); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this set whose elements range from * {@code fromElement} to {@code toElement}. If {@code fromElement} and * {@code toElement} are equal, the returned set is empty unless {@code * fromExclusive} and {@code toExclusive} are both true. The returned set * is backed by this set, so changes in the returned set are reflected in * this set, and vice-versa. The returned set supports all optional set * operations that this set supports. * * <p>The returned set will throw an {@code IllegalArgumentException} * on an attempt to insert an element outside its range. * {@description.close} * * @param fromElement low endpoint of the returned set * @param fromInclusive {@code true} if the low endpoint * is to be included in the returned view * @param toElement high endpoint of the returned set * @param toInclusive {@code true} if the high endpoint * is to be included in the returned view * @return a view of the portion of this set whose elements range from * {@code fromElement}, inclusive, to {@code toElement}, exclusive * @throws ClassCastException if {@code fromElement} and * {@code toElement} cannot be compared to one another using this * set's comparator (or, if the set has no comparator, using * natural ordering). Implementations may, but are not required * to, throw this exception if {@code fromElement} or * {@code toElement} cannot be compared to elements currently in * the set. * @throws NullPointerException if {@code fromElement} or * {@code toElement} is null and this set does * not permit null elements * @throws IllegalArgumentException if {@code fromElement} is * greater than {@code toElement}; or if this set itself * has a restricted range, and {@code fromElement} or * {@code toElement} lies outside the bounds of the range. */ NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this set whose elements are less than * (or equal to, if {@code inclusive} is true) {@code toElement}. The * returned set is backed by this set, so changes in the returned set are * reflected in this set, and vice-versa. The returned set supports all * optional set operations that this set supports. * * <p>The returned set will throw an {@code IllegalArgumentException} * on an attempt to insert an element outside its range. * {@description.close} * * @param toElement high endpoint of the returned set * @param inclusive {@code true} if the high endpoint * is to be included in the returned view * @return a view of the portion of this set whose elements are less than * (or equal to, if {@code inclusive} is true) {@code toElement} * @throws ClassCastException if {@code toElement} is not compatible * with this set's comparator (or, if the set has no comparator, * if {@code toElement} does not implement {@link Comparable}). * Implementations may, but are not required to, throw this * exception if {@code toElement} cannot be compared to elements * currently in the set. * @throws NullPointerException if {@code toElement} is null and * this set does not permit null elements * @throws IllegalArgumentException if this set itself has a * restricted range, and {@code toElement} lies outside the * bounds of the range */ NavigableSet<E> headSet(E toElement, boolean inclusive); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this set whose elements are greater * than (or equal to, if {@code inclusive} is true) {@code fromElement}. * The returned set is backed by this set, so changes in the returned set * are reflected in this set, and vice-versa. The returned set supports * all optional set operations that this set supports. * * <p>The returned set will throw an {@code IllegalArgumentException} * on an attempt to insert an element outside its range. * {@description.close} * * @param fromElement low endpoint of the returned set * @param inclusive {@code true} if the low endpoint * is to be included in the returned view * @return a view of the portion of this set whose elements are greater * than or equal to {@code fromElement} * @throws ClassCastException if {@code fromElement} is not compatible * with this set's comparator (or, if the set has no comparator, * if {@code fromElement} does not implement {@link Comparable}). * Implementations may, but are not required to, throw this * exception if {@code fromElement} cannot be compared to elements * currently in the set. * @throws NullPointerException if {@code fromElement} is null * and this set does not permit null elements * @throws IllegalArgumentException if this set itself has a * restricted range, and {@code fromElement} lies outside the * bounds of the range */ NavigableSet<E> tailSet(E fromElement, boolean inclusive); /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>Equivalent to {@code subSet(fromElement, true, toElement, false)}. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ SortedSet<E> subSet(E fromElement, E toElement); /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>Equivalent to {@code headSet(toElement, false)}. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} na */ SortedSet<E> headSet(E toElement); /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>Equivalent to {@code tailSet(fromElement, true)}. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ SortedSet<E> tailSet(E fromElement); }
Java
/* * Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.lang.ref.WeakReference; import java.lang.ref.ReferenceQueue; /** {@collect.stats} * {@description.open} * A hashtable-based <tt>Map</tt> implementation with <em>weak keys</em>. * An entry in a <tt>WeakHashMap</tt> will automatically be removed when * its key is no longer in ordinary use. More precisely, the presence of a * mapping for a given key will not prevent the key from being discarded by the * garbage collector, that is, made finalizable, finalized, and then reclaimed. * When a key has been discarded its entry is effectively removed from the map, * so this class behaves somewhat differently from other <tt>Map</tt> * implementations. * * <p> Both null values and the null key are supported. This class has * performance characteristics similar to those of the <tt>HashMap</tt> * class, and has the same efficiency parameters of <em>initial capacity</em> * and <em>load factor</em>. * {@description.close} * * {@property.open formal:java.util.Collections_SynchronizedMap} * <p> Like most collection classes, this class is not synchronized. * A synchronized <tt>WeakHashMap</tt> may be constructed using the * {@link Collections#synchronizedMap Collections.synchronizedMap} * method. * {@property.close} * * {@description.open} * <p> This class is intended primarily for use with key objects whose * <tt>equals</tt> methods test for object identity using the * <tt>==</tt> operator. Once such a key is discarded it can never be * recreated, so it is impossible to do a lookup of that key in a * <tt>WeakHashMap</tt> at some later time and be surprised that its entry * has been removed. This class will work perfectly well with key objects * whose <tt>equals</tt> methods are not based upon object identity, such * as <tt>String</tt> instances. With such recreatable key objects, * however, the automatic removal of <tt>WeakHashMap</tt> entries whose * keys have been discarded may prove to be confusing. * * <p> The behavior of the <tt>WeakHashMap</tt> class depends in part upon * the actions of the garbage collector, so several familiar (though not * required) <tt>Map</tt> invariants do not hold for this class. Because * the garbage collector may discard keys at any time, a * <tt>WeakHashMap</tt> may behave as though an unknown thread is silently * removing entries. In particular, even if you synchronize on a * <tt>WeakHashMap</tt> instance and invoke none of its mutator methods, it * is possible for the <tt>size</tt> method to return smaller values over * time, for the <tt>isEmpty</tt> method to return <tt>false</tt> and * then <tt>true</tt>, for the <tt>containsKey</tt> method to return * <tt>true</tt> and later <tt>false</tt> for a given key, for the * <tt>get</tt> method to return a value for a given key but later return * <tt>null</tt>, for the <tt>put</tt> method to return * <tt>null</tt> and the <tt>remove</tt> method to return * <tt>false</tt> for a key that previously appeared to be in the map, and * for successive examinations of the key set, the value collection, and * the entry set to yield successively smaller numbers of elements. * * <p> Each key object in a <tt>WeakHashMap</tt> is stored indirectly as * the referent of a weak reference. Therefore a key will automatically be * removed only after the weak references to it, both inside and outside of the * map, have been cleared by the garbage collector. * {@description.close} * * {@property.open uncheckable} * <p> <strong>Implementation note:</strong> The value objects in a * <tt>WeakHashMap</tt> are held by ordinary strong references. Thus care * should be taken to ensure that value objects do not strongly refer to their * own keys, either directly or indirectly, since that will prevent the keys * from being discarded. Note that a value object may refer indirectly to its * key via the <tt>WeakHashMap</tt> itself; that is, a value object may * strongly refer to some other key object whose associated value object, in * turn, strongly refers to the key of the first value object. One way * to deal with this is to wrap values themselves within * <tt>WeakReferences</tt> before * inserting, as in: <tt>m.put(key, new WeakReference(value))</tt>, * and then unwrapping upon each <tt>get</tt>. * {@property.close} * * {@property.open formal:java.util.Map_UnsafeIterator} * <p>The iterators returned by the <tt>iterator</tt> method of the collections * returned by all of this class's "collection view methods" are * <i>fail-fast</i>: if the map is structurally modified at any time after the * iterator is created, in any way except through the iterator's own * <tt>remove</tt> method, the iterator will throw a {@link * ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * {@property.close} * * {@description.open} * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Doug Lea * @author Josh Bloch * @author Mark Reinhold * @since 1.2 * @see java.util.HashMap * @see java.lang.ref.WeakReference */ public class WeakHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V> { /** {@collect.stats} * {@description.open} * The default initial capacity -- MUST be a power of two. * {@description.close} */ private static final int DEFAULT_INITIAL_CAPACITY = 16; /** {@collect.stats} * {@description.open} * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. * {@description.close} */ private static final int MAXIMUM_CAPACITY = 1 << 30; /** {@collect.stats} * {@description.open} * The load factor used when none specified in constructor. * {@description.close} */ private static final float DEFAULT_LOAD_FACTOR = 0.75f; /** {@collect.stats} * {@description.open} * The table, resized as necessary. Length MUST Always be a power of two. * {@description.close} */ Entry<K,V>[] table; /** {@collect.stats} * {@description.open} * The number of key-value mappings contained in this weak hash map. * {@description.close} */ private int size; /** {@collect.stats} * {@description.open} * The next size value at which to resize (capacity * load factor). * {@description.close} */ private int threshold; /** {@collect.stats} * {@description.open} * The load factor for the hash table. * {@description.close} */ private final float loadFactor; /** {@collect.stats} * {@description.open} * Reference queue for cleared WeakEntries * {@description.close} */ private final ReferenceQueue<Object> queue = new ReferenceQueue<Object>(); /** {@collect.stats} * {@description.open} * The number of times this WeakHashMap has been structurally modified. * Structural modifications are those that change the number of * mappings in the map or otherwise modify its internal structure * (e.g., rehash). This field is used to make iterators on * Collection-views of the map fail-fast. * {@description.close} * * @see ConcurrentModificationException */ volatile int modCount; @SuppressWarnings("unchecked") private Entry<K,V>[] newTable(int n) { return (Entry<K,V>[]) new Entry[n]; } /** {@collect.stats} * {@description.open} * Constructs a new, empty <tt>WeakHashMap</tt> with the given initial * capacity and the given load factor. * {@description.close} * * @param initialCapacity The initial capacity of the <tt>WeakHashMap</tt> * @param loadFactor The load factor of the <tt>WeakHashMap</tt> * @throws IllegalArgumentException if the initial capacity is negative, * or if the load factor is nonpositive. */ public WeakHashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Initial Capacity: "+ initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal Load factor: "+ loadFactor); int capacity = 1; while (capacity < initialCapacity) capacity <<= 1; table = newTable(capacity); this.loadFactor = loadFactor; threshold = (int)(capacity * loadFactor); } /** {@collect.stats} * {@description.open} * Constructs a new, empty <tt>WeakHashMap</tt> with the given initial * capacity and the default load factor (0.75). * {@description.close} * * @param initialCapacity The initial capacity of the <tt>WeakHashMap</tt> * @throws IllegalArgumentException if the initial capacity is negative */ public WeakHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** {@collect.stats} * {@description.open} * Constructs a new, empty <tt>WeakHashMap</tt> with the default initial * capacity (16) and load factor (0.75). * {@description.close} */ public WeakHashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; threshold = DEFAULT_INITIAL_CAPACITY; table = newTable(DEFAULT_INITIAL_CAPACITY); } /** {@collect.stats} * {@description.open} * Constructs a new <tt>WeakHashMap</tt> with the same mappings as the * specified map. The <tt>WeakHashMap</tt> is created with the default * load factor (0.75) and an initial capacity sufficient to hold the * mappings in the specified map. * {@description.close} * * @param m the map whose mappings are to be placed in this map * @throws NullPointerException if the specified map is null * @since 1.3 */ public WeakHashMap(Map<? extends K, ? extends V> m) { this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, 16), DEFAULT_LOAD_FACTOR); putAll(m); } // internal utilities /** {@collect.stats} * {@description.open} * Value representing null keys inside tables. * {@description.close} */ private static final Object NULL_KEY = new Object(); /** {@collect.stats} * {@description.open} * Use NULL_KEY for key if it is null. * {@description.close} */ private static Object maskNull(Object key) { return (key == null) ? NULL_KEY : key; } /** {@collect.stats} * {@description.open} * Returns internal representation of null key back to caller as null. * {@description.close} */ static Object unmaskNull(Object key) { return (key == NULL_KEY) ? null : key; } /** {@collect.stats} * {@description.open} * Checks for equality of non-null reference x and possibly-null y. By * default uses Object.equals. * {@description.close} */ private static boolean eq(Object x, Object y) { return x == y || x.equals(y); } /** {@collect.stats} * {@description.open} * Returns index for hash code h. * {@description.close} */ private static int indexFor(int h, int length) { return h & (length-1); } /** {@collect.stats} * {@description.open} * Expunges stale entries from the table. * {@description.close} */ private void expungeStaleEntries() { for (Object x; (x = queue.poll()) != null; ) { synchronized (queue) { @SuppressWarnings("unchecked") Entry<K,V> e = (Entry<K,V>) x; int i = indexFor(e.hash, table.length); Entry<K,V> prev = table[i]; Entry<K,V> p = prev; while (p != null) { Entry<K,V> next = p.next; if (p == e) { if (prev == e) table[i] = next; else prev.next = next; // Must not null out e.next; // stale entries may be in use by a HashIterator e.value = null; // Help GC size--; break; } prev = p; p = next; } } } } /** {@collect.stats} * {@description.open} * Returns the table after first expunging stale entries. * {@description.close} */ private Entry<K,V>[] getTable() { expungeStaleEntries(); return table; } /** {@collect.stats} * {@description.open} * Returns the number of key-value mappings in this map. * This result is a snapshot, and may not reflect unprocessed * entries that will be removed before next attempted access * because they are no longer referenced. * {@description.close} */ public int size() { if (size == 0) return 0; expungeStaleEntries(); return size; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map contains no key-value mappings. * This result is a snapshot, and may not reflect unprocessed * entries that will be removed before next attempted access * because they are no longer referenced. * {@description.close} */ public boolean isEmpty() { return size() == 0; } /** {@collect.stats} * {@description.open} * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * {@description.close} * * @see #put(Object, Object) */ public V get(Object key) { Object k = maskNull(key); int h = HashMap.hash(k.hashCode()); Entry<K,V>[] tab = getTable(); int index = indexFor(h, tab.length); Entry<K,V> e = tab[index]; while (e != null) { if (e.hash == h && eq(k, e.get())) return e.value; e = e.next; } return null; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map contains a mapping for the * specified key. * {@description.close} * * @param key The key whose presence in this map is to be tested * @return <tt>true</tt> if there is a mapping for <tt>key</tt>; * <tt>false</tt> otherwise */ public boolean containsKey(Object key) { return getEntry(key) != null; } /** {@collect.stats} * {@description.open} * Returns the entry associated with the specified key in this map. * Returns null if the map contains no mapping for this key. * {@description.close} */ Entry<K,V> getEntry(Object key) { Object k = maskNull(key); int h = HashMap.hash(k.hashCode()); Entry<K,V>[] tab = getTable(); int index = indexFor(h, tab.length); Entry<K,V> e = tab[index]; while (e != null && !(e.hash == h && eq(k, e.get()))) e = e.next; return e; } /** {@collect.stats} * {@description.open} * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for this key, the old * value is replaced. * {@description.close} * * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) */ public V put(K key, V value) { Object k = maskNull(key); int h = HashMap.hash(k.hashCode()); Entry<K,V>[] tab = getTable(); int i = indexFor(h, tab.length); for (Entry<K,V> e = tab[i]; e != null; e = e.next) { if (h == e.hash && eq(k, e.get())) { V oldValue = e.value; if (value != oldValue) e.value = value; return oldValue; } } modCount++; Entry<K,V> e = tab[i]; tab[i] = new Entry<K,V>(k, value, queue, h, e); if (++size >= threshold) resize(tab.length * 2); return null; } /** {@collect.stats} * {@description.open} * Rehashes the contents of this map into a new array with a * larger capacity. This method is called automatically when the * number of keys in this map reaches its threshold. * * If current capacity is MAXIMUM_CAPACITY, this method does not * resize the map, but sets threshold to Integer.MAX_VALUE. * This has the effect of preventing future calls. * {@description.close} * * @param newCapacity the new capacity, MUST be a power of two; * must be greater than current capacity unless current * capacity is MAXIMUM_CAPACITY (in which case value * is irrelevant). */ void resize(int newCapacity) { Entry<K,V>[] oldTable = getTable(); int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return; } Entry<K,V>[] newTable = newTable(newCapacity); transfer(oldTable, newTable); table = newTable; /* * If ignoring null elements and processing ref queue caused massive * shrinkage, then restore old table. This should be rare, but avoids * unbounded expansion of garbage-filled tables. */ if (size >= threshold / 2) { threshold = (int)(newCapacity * loadFactor); } else { expungeStaleEntries(); transfer(newTable, oldTable); table = oldTable; } } /** {@collect.stats} * {@description.open} * Transfers all entries from src to dest tables * {@description.close} */ private void transfer(Entry<K,V>[] src, Entry<K,V>[] dest) { for (int j = 0; j < src.length; ++j) { Entry<K,V> e = src[j]; src[j] = null; while (e != null) { Entry<K,V> next = e.next; Object key = e.get(); if (key == null) { e.next = null; // Help GC e.value = null; // " " size--; } else { int i = indexFor(e.hash, dest.length); e.next = dest[i]; dest[i] = e; } e = next; } } } /** {@collect.stats} * {@description.open} * Copies all of the mappings from the specified map to this map. * These mappings will replace any mappings that this map had for any * of the keys currently in the specified map. * {@description.close} * * @param m mappings to be stored in this map. * @throws NullPointerException if the specified map is null. */ public void putAll(Map<? extends K, ? extends V> m) { int numKeysToBeAdded = m.size(); if (numKeysToBeAdded == 0) return; /* * Expand the map if the map if the number of mappings to be added * is greater than or equal to threshold. This is conservative; the * obvious condition is (m.size() + size) >= threshold, but this * condition could result in a map with twice the appropriate capacity, * if the keys to be added overlap with the keys already in this map. * By using the conservative calculation, we subject ourself * to at most one extra resize. */ if (numKeysToBeAdded > threshold) { int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1); if (targetCapacity > MAXIMUM_CAPACITY) targetCapacity = MAXIMUM_CAPACITY; int newCapacity = table.length; while (newCapacity < targetCapacity) newCapacity <<= 1; if (newCapacity > table.length) resize(newCapacity); } for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue()); } /** {@collect.stats} * {@description.open} * Removes the mapping for a key from this weak hash map if it is present. * More formally, if this map contains a mapping from key <tt>k</tt> to * value <tt>v</tt> such that <code>(key==null ? k==null : * key.equals(k))</code>, that mapping is removed. (The map can contain * at most one such mapping.) * * <p>Returns the value to which this map previously associated the key, * or <tt>null</tt> if the map contained no mapping for the key. A * return value of <tt>null</tt> does not <i>necessarily</i> indicate * that the map contained no mapping for the key; it's also possible * that the map explicitly mapped the key to <tt>null</tt>. * * <p>The map will not contain a mapping for the specified key once the * call returns. * {@description.close} * * @param key key whose mapping is to be removed from the map * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt> */ public V remove(Object key) { Object k = maskNull(key); int h = HashMap.hash(k.hashCode()); Entry<K,V>[] tab = getTable(); int i = indexFor(h, tab.length); Entry<K,V> prev = tab[i]; Entry<K,V> e = prev; while (e != null) { Entry<K,V> next = e.next; if (h == e.hash && eq(k, e.get())) { modCount++; size--; if (prev == e) tab[i] = next; else prev.next = next; return e.value; } prev = e; e = next; } return null; } /** {@collect.stats} * {@description.open} * Special version of remove needed by Entry set * {@description.close} */ boolean removeMapping(Object o) { if (!(o instanceof Map.Entry)) return false; Entry<K,V>[] tab = getTable(); Map.Entry<?,?> entry = (Map.Entry<?,?>)o; Object k = maskNull(entry.getKey()); int h = HashMap.hash(k.hashCode()); int i = indexFor(h, tab.length); Entry<K,V> prev = tab[i]; Entry<K,V> e = prev; while (e != null) { Entry<K,V> next = e.next; if (h == e.hash && e.equals(entry)) { modCount++; size--; if (prev == e) tab[i] = next; else prev.next = next; return true; } prev = e; e = next; } return false; } /** {@collect.stats} * {@description.open} * Removes all of the mappings from this map. * The map will be empty after this call returns. * {@description.close} */ public void clear() { // clear out ref queue. We don't need to expunge entries // since table is getting cleared. while (queue.poll() != null) ; modCount++; Arrays.fill(table, null); size = 0; // Allocation of array may have caused GC, which may have caused // additional entries to go stale. Removing these entries from the // reference queue will make them eligible for reclamation. while (queue.poll() != null) ; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map maps one or more keys to the * specified value. * {@description.close} * * @param value value whose presence in this map is to be tested * @return <tt>true</tt> if this map maps one or more keys to the * specified value */ public boolean containsValue(Object value) { if (value==null) return containsNullValue(); Entry<K,V>[] tab = getTable(); for (int i = tab.length; i-- > 0;) for (Entry<K,V> e = tab[i]; e != null; e = e.next) if (value.equals(e.value)) return true; return false; } /** {@collect.stats} * {@description.open} * Special-case code for containsValue with null argument * {@description.close} */ private boolean containsNullValue() { Entry<K,V>[] tab = getTable(); for (int i = tab.length; i-- > 0;) for (Entry<K,V> e = tab[i]; e != null; e = e.next) if (e.value==null) return true; return false; } /** {@collect.stats} * {@description.open} * The entries in this hash table extend WeakReference, using its main ref * field as the key. * {@description.close} */ private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> { V value; final int hash; Entry<K,V> next; /** {@collect.stats} * {@description.open} * Creates new entry. * {@description.close} */ Entry(Object key, V value, ReferenceQueue<Object> queue, int hash, Entry<K,V> next) { super(key, queue); this.value = value; this.hash = hash; this.next = next; } @SuppressWarnings("unchecked") public K getKey() { return (K) WeakHashMap.unmaskNull(get()); } public V getValue() { return value; } public V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; K k1 = getKey(); Object k2 = e.getKey(); if (k1 == k2 || (k1 != null && k1.equals(k2))) { V v1 = getValue(); Object v2 = e.getValue(); if (v1 == v2 || (v1 != null && v1.equals(v2))) return true; } return false; } public int hashCode() { K k = getKey(); V v = getValue(); return ((k==null ? 0 : k.hashCode()) ^ (v==null ? 0 : v.hashCode())); } public String toString() { return getKey() + "=" + getValue(); } } private abstract class HashIterator<T> implements Iterator<T> { private int index; private Entry<K,V> entry = null; private Entry<K,V> lastReturned = null; private int expectedModCount = modCount; /** {@collect.stats} * {@description.open} * Strong reference needed to avoid disappearance of key * between hasNext and next * {@description.close} */ private Object nextKey = null; /** {@collect.stats} * {@description.open} * Strong reference needed to avoid disappearance of key * between nextEntry() and any use of the entry * {@description.close} */ private Object currentKey = null; HashIterator() { index = isEmpty() ? 0 : table.length; } public boolean hasNext() { Entry<K,V>[] t = table; while (nextKey == null) { Entry<K,V> e = entry; int i = index; while (e == null && i > 0) e = t[--i]; entry = e; index = i; if (e == null) { currentKey = null; return false; } nextKey = e.get(); // hold on to key in strong ref if (nextKey == null) entry = entry.next; } return true; } /** {@collect.stats} * {@description.open} * The common parts of next() across different types of iterators * {@description.close} */ protected Entry<K,V> nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (nextKey == null && !hasNext()) throw new NoSuchElementException(); lastReturned = entry; entry = entry.next; currentKey = nextKey; nextKey = null; return lastReturned; } public void remove() { if (lastReturned == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); WeakHashMap.this.remove(currentKey); expectedModCount = modCount; lastReturned = null; currentKey = null; } } private class ValueIterator extends HashIterator<V> { public V next() { return nextEntry().value; } } private class KeyIterator extends HashIterator<K> { public K next() { return nextEntry().getKey(); } } private class EntryIterator extends HashIterator<Map.Entry<K,V>> { public Map.Entry<K,V> next() { return nextEntry(); } } // Views private transient Set<Map.Entry<K,V>> entrySet = null; /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the keys contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. * {@property.close} */ public Set<K> keySet() { Set<K> ks = keySet; return (ks != null ? ks : (keySet = new KeySet())); } private class KeySet extends AbstractSet<K> { public Iterator<K> iterator() { return new KeyIterator(); } public int size() { return WeakHashMap.this.size(); } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { if (containsKey(o)) { WeakHashMap.this.remove(o); return true; } else return false; } public void clear() { WeakHashMap.this.clear(); } } /** {@collect.stats} * {@description.open} * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is * modified while an iteration over the collection is in progress * (except through the iterator's own <tt>remove</tt> operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Collection.remove</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not * support the <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} */ public Collection<V> values() { Collection<V> vs = values; return (vs != null) ? vs : (values = new Values()); } private class Values extends AbstractCollection<V> { public Iterator<V> iterator() { return new ValueIterator(); } public int size() { return WeakHashMap.this.size(); } public boolean contains(Object o) { return containsValue(o); } public void clear() { WeakHashMap.this.clear(); } } /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the mappings contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation, or through the * <tt>setValue</tt> operation on a map entry returned by the * iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and * <tt>clear</tt> operations. It does not support the * <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} */ public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es = entrySet; return es != null ? es : (entrySet = new EntrySet()); } private class EntrySet extends AbstractSet<Map.Entry<K,V>> { public Iterator<Map.Entry<K,V>> iterator() { return new EntryIterator(); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; Entry<K,V> candidate = getEntry(e.getKey()); return candidate != null && candidate.equals(e); } public boolean remove(Object o) { return removeMapping(o); } public int size() { return WeakHashMap.this.size(); } public void clear() { WeakHashMap.this.clear(); } private List<Map.Entry<K,V>> deepCopy() { List<Map.Entry<K,V>> list = new ArrayList<Map.Entry<K,V>>(size()); for (Map.Entry<K,V> e : this) list.add(new AbstractMap.SimpleEntry<K,V>(e)); return list; } public Object[] toArray() { return deepCopy().toArray(); } public <T> T[] toArray(T[] a) { return deepCopy().toArray(a); } } }
Java
/* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.spi; import java.util.Currency; import java.util.Locale; /** {@collect.stats} * {@description.open} * An abstract class for service providers that * provide localized currency symbols and display names for the * {@link java.util.Currency Currency} class. * Note that currency symbols are considered names when determining * behaviors described in the * {@link java.util.spi.LocaleServiceProvider LocaleServiceProvider} * specification. * {@description.close} * * @since 1.6 */ public abstract class CurrencyNameProvider extends LocaleServiceProvider { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ protected CurrencyNameProvider() { } /** {@collect.stats} * {@description.open} * Gets the symbol of the given currency code for the specified locale. * For example, for "USD" (US Dollar), the symbol is "$" if the specified * locale is the US, while for other locales it may be "US$". If no * symbol can be determined, null should be returned. * {@description.close} * * @param currencyCode the ISO 4217 currency code, which * consists of three upper-case letters between 'A' (U+0041) and * 'Z' (U+005A) * @param locale the desired locale * @return the symbol of the given currency code for the specified locale, or null if * the symbol is not available for the locale * @exception NullPointerException if <code>currencyCode</code> or * <code>locale</code> is null * @exception IllegalArgumentException if <code>currencyCode</code> is not in * the form of three upper-case letters, or <code>locale</code> isn't * one of the locales returned from * {@link java.util.spi.LocaleServiceProvider#getAvailableLocales() * getAvailableLocales()}. * @see java.util.Currency#getSymbol(java.util.Locale) */ public abstract String getSymbol(String currencyCode, Locale locale); /** {@collect.stats} * {@description.open} * Returns a name for the currency that is appropriate for display to the * user. The default implementation returns null. * {@description.close} * * @param currencyCode the ISO 4217 currency code, which * consists of three upper-case letters between 'A' (U+0041) and * 'Z' (U+005A) * @param locale the desired locale * @return the name for the currency that is appropriate for display to the * user, or null if the name is not available for the locale * @exception IllegalArgumentException if <code>currencyCode</code> is not in * the form of three upper-case letters, or <code>locale</code> isn't * one of the locales returned from * {@link java.util.spi.LocaleServiceProvider#getAvailableLocales() * getAvailableLocales()}. * @exception NullPointerException if <code>currencyCode</code> or * <code>locale</code> is <code>null</code> * @since 1.7 */ private String getDisplayName(String currencyCode, Locale locale) { if (currencyCode == null || locale == null) { throw new NullPointerException(); } return null; } }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.spi; import java.util.Locale; /** {@collect.stats} * {@description.open} * <p> * This is the super class of all the locale sensitive service provider * interfaces (SPIs). * <p> * Locale sensitive service provider interfaces are interfaces that * correspond to locale sensitive classes in the <code>java.text</code> * and <code>java.util</code> packages. The interfaces enable the * construction of locale sensitive objects and the retrieval of * localized names for these packages. Locale sensitive factory methods * and methods for name retrieval in the <code>java.text</code> and * <code>java.util</code> packages use implementations of the provider * interfaces to offer support for locales beyond the set of locales * supported by the Java runtime environment itself. * <p> * <h4>Packaging of Locale Sensitive Service Provider Implementations</h4> * Implementations of these locale sensitive services are packaged using the * <a href="../../../../technotes/guides/extensions/index.html">Java Extension Mechanism</a> * as installed extensions. A provider identifies itself with a * provider-configuration file in the resource directory META-INF/services, * using the fully qualified provider interface class name as the file name. * The file should contain a list of fully-qualified concrete provider class names, * one per line. A line is terminated by any one of a line feed ('\n'), a carriage * return ('\r'), or a carriage return followed immediately by a line feed. Space * and tab characters surrounding each name, as well as blank lines, are ignored. * The comment character is '#' ('\u0023'); on each line all characters following * the first comment character are ignored. The file must be encoded in UTF-8. * <p> * If a particular concrete provider class is named in more than one configuration * file, or is named in the same configuration file more than once, then the * duplicates will be ignored. The configuration file naming a particular provider * need not be in the same jar file or other distribution unit as the provider itself. * The provider must be accessible from the same class loader that was initially * queried to locate the configuration file; this is not necessarily the class loader * that loaded the file. * <p> * For example, an implementation of the * {@link java.text.spi.DateFormatProvider DateFormatProvider} class should * take the form of a jar file which contains the file: * <pre> * META-INF/services/java.text.spi.DateFormatProvider * </pre> * And the file <code>java.text.spi.DateFormatProvider</code> should have * a line such as: * <pre> * <code>com.foo.DateFormatProviderImpl</code> * </pre> * which is the fully qualified class name of the class implementing * <code>DateFormatProvider</code>. * <h4>Invocation of Locale Sensitive Services</h4> * <p> * Locale sensitive factory methods and methods for name retrieval in the * <code>java.text</code> and <code>java.util</code> packages invoke * service provider methods when needed to support the requested locale. * The methods first check whether the Java runtime environment itself * supports the requested locale, and use its support if available. * Otherwise, they call the <code>getAvailableLocales()</code> methods of * installed providers for the appropriate interface to find one that * supports the requested locale. If such a provider is found, its other * methods are called to obtain the requested object or name. If neither * the Java runtime environment itself nor an installed provider supports * the requested locale, a fallback locale is constructed by replacing the * first of the variant, country, or language strings of the locale that's * not an empty string with an empty string, and the lookup process is * restarted. In the case that the variant contains one or more '_'s, the * fallback locale is constructed by replacing the variant with a new variant * which eliminates the last '_' and the part following it. Even if a * fallback occurs, methods that return requested objects or name are * invoked with the original locale before the fallback.The Java runtime * environment must support the root locale for all locale sensitive services * in order to guarantee that this process terminates. * <p> * Providers of names (but not providers of other objects) are allowed to * return null for some name requests even for locales that they claim to * support by including them in their return value for * <code>getAvailableLocales</code>. Similarly, the Java runtime * environment itself may not have all names for all locales that it * supports. This is because the sets of objects for which names are * requested can be large and vary over time, so that it's not always * feasible to cover them completely. If the Java runtime environment or a * provider returns null instead of a name, the lookup will proceed as * described above as if the locale was not supported. * {@description.close} * * @since 1.6 */ public abstract class LocaleServiceProvider { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ protected LocaleServiceProvider() { } /** {@collect.stats} * {@description.open} * Returns an array of all locales for which this locale service provider * can provide localized objects or names. * {@description.close} * * @return An array of all locales for which this locale service provider * can provide localized objects or names. */ public abstract Locale[] getAvailableLocales(); }
Java
/* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.spi; import java.util.Locale; /** {@collect.stats} * {@description.open} * An abstract class for service providers that * provide localized time zone names for the * {@link java.util.TimeZone TimeZone} class. * The localized time zone names available from the implementations of * this class are also the source for the * {@link java.text.DateFormatSymbols#getZoneStrings() * DateFormatSymbols.getZoneStrings()} method. * {@description.close} * * @since 1.6 */ public abstract class TimeZoneNameProvider extends LocaleServiceProvider { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ protected TimeZoneNameProvider() { } /** {@collect.stats} * {@description.open} * Returns a name for the given time zone ID that's suitable for * presentation to the user in the specified locale. The given time * zone ID is "GMT" or one of the names defined using "Zone" entries * in the "tz database", a public domain time zone database at * <a href="ftp://elsie.nci.nih.gov/pub/">ftp://elsie.nci.nih.gov/pub/</a>. * The data of this database is contained in a file whose name starts with * "tzdata", and the specification of the data format is part of the zic.8 * man page, which is contained in a file whose name starts with "tzcode". * <p> * If <code>daylight</code> is true, the method should return a name * appropriate for daylight saving time even if the specified time zone * has not observed daylight saving time in the past. * {@description.close} * * @param ID a time zone ID string * @param daylight if true, return the daylight saving name. * @param style either {@link java.util.TimeZone#LONG TimeZone.LONG} or * {@link java.util.TimeZone#SHORT TimeZone.SHORT} * @param locale the desired locale * @return the human-readable name of the given time zone in the * given locale, or null if it's not available. * @exception IllegalArgumentException if <code>style</code> is invalid, * or <code>locale</code> isn't one of the locales returned from * {@link java.util.spi.LocaleServiceProvider#getAvailableLocales() * getAvailableLocales()}. * @exception NullPointerException if <code>ID</code> or <code>locale</code> * is null * @see java.util.TimeZone#getDisplayName(boolean, int, java.util.Locale) */ public abstract String getDisplayName(String ID, boolean daylight, int style, Locale locale); }
Java
/* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.spi; import java.util.Locale; /** {@collect.stats} * {@description.open} * An abstract class for service providers that * provide localized names for the * {@link java.util.Locale Locale} class. * {@description.close} * * @since 1.6 */ public abstract class LocaleNameProvider extends LocaleServiceProvider { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ protected LocaleNameProvider() { } /** {@collect.stats} * {@description.open} * Returns a localized name for the given ISO 639 language code and the * given locale that is appropriate for display to the user. * For example, if <code>languageCode</code> is "fr" and <code>locale</code> * is en_US, getDisplayLanguage() will return "French"; if <code>languageCode</code> * is "en" and <code>locale</code> is fr_FR, getDisplayLanguage() will return "anglais". * If the name returned cannot be localized according to <code>locale</code>, * (say, the provider does not have a Japanese name for Croatian), * this method returns null. * {@description.close} * @param languageCode the ISO 639 language code string in the form of two * lower-case letters between 'a' (U+0061) and 'z' (U+007A) * @param locale the desired locale * @return the name of the given language code for the specified locale, or null if it's not * available. * @exception NullPointerException if <code>languageCode</code> or <code>locale</code> is null * @exception IllegalArgumentException if <code>languageCode</code> is not in the form of * two lower-case letters, or <code>locale</code> isn't * one of the locales returned from * {@link java.util.spi.LocaleServiceProvider#getAvailableLocales() * getAvailableLocales()}. * @see java.util.Locale#getDisplayLanguage(java.util.Locale) */ public abstract String getDisplayLanguage(String languageCode, Locale locale); /** {@collect.stats} * {@description.open} * Returns a localized name for the given ISO 3166 country code and the * given locale that is appropriate for display to the user. * For example, if <code>countryCode</code> is "FR" and <code>locale</code> * is en_US, getDisplayCountry() will return "France"; if <code>countryCode</code> * is "US" and <code>locale</code> is fr_FR, getDisplayCountry() will return "Etats-Unis". * If the name returned cannot be localized according to <code>locale</code>, * (say, the provider does not have a Japanese name for Croatia), * this method returns null. * {@description.close} * @param countryCode the ISO 3166 country code string in the form of two * upper-case letters between 'A' (U+0041) and 'Z' (U+005A) * @param locale the desired locale * @return the name of the given country code for the specified locale, or null if it's not * available. * @exception NullPointerException if <code>countryCode</code> or <code>locale</code> is null * @exception IllegalArgumentException if <code>countryCode</code> is not in the form of * two upper-case letters, or <code>locale</code> isn't * one of the locales returned from * {@link java.util.spi.LocaleServiceProvider#getAvailableLocales() * getAvailableLocales()}. * @see java.util.Locale#getDisplayCountry(java.util.Locale) */ public abstract String getDisplayCountry(String countryCode, Locale locale); /** {@collect.stats} * {@description.open} * Returns a localized name for the given variant code and the given locale that * is appropriate for display to the user. * If the name returned cannot be localized according to <code>locale</code>, * this method returns null. * {@description.close} * @param variant the variant string * @param locale the desired locale * @return the name of the given variant string for the specified locale, or null if it's not * available. * @exception NullPointerException if <code>variant</code> or <code>locale</code> is null * @exception IllegalArgumentException if <code>locale</code> isn't * one of the locales returned from * {@link java.util.spi.LocaleServiceProvider#getAvailableLocales() * getAvailableLocales()}. * @see java.util.Locale#getDisplayVariant(java.util.Locale) */ public abstract String getDisplayVariant(String variant, Locale locale); }
Java
/* * Copyright (c) 1994, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.lang.*; /** {@collect.stats} * {@description.open} * The string tokenizer class allows an application to break a * string into tokens. The tokenization method is much simpler than * the one used by the <code>StreamTokenizer</code> class. The * <code>StringTokenizer</code> methods do not distinguish among * identifiers, numbers, and quoted strings, nor do they recognize * and skip comments. * <p> * The set of delimiters (the characters that separate tokens) may * be specified either at creation time or on a per-token basis. * <p> * An instance of <code>StringTokenizer</code> behaves in one of two * ways, depending on whether it was created with the * <code>returnDelims</code> flag having the value <code>true</code> * or <code>false</code>: * <ul> * <li>If the flag is <code>false</code>, delimiter characters serve to * separate tokens. A token is a maximal sequence of consecutive * characters that are not delimiters. * <li>If the flag is <code>true</code>, delimiter characters are themselves * considered to be tokens. A token is thus either one delimiter * character, or a maximal sequence of consecutive characters that are * not delimiters. * </ul><p> * A <tt>StringTokenizer</tt> object internally maintains a current * position within the string to be tokenized. Some operations advance this * current position past the characters processed.<p> * A token is returned by taking a substring of the string that was used to * create the <tt>StringTokenizer</tt> object. * <p> * The following is one example of the use of the tokenizer. The code: * <blockquote><pre> * StringTokenizer st = new StringTokenizer("this is a test"); * while (st.hasMoreTokens()) { * System.out.println(st.nextToken()); * } * </pre></blockquote> * <p> * prints the following output: * <blockquote><pre> * this * is * a * test * </pre></blockquote> * * <p> * <tt>StringTokenizer</tt> is a legacy class that is retained for * compatibility reasons although its use is discouraged in new code. It is * recommended that anyone seeking this functionality use the <tt>split</tt> * method of <tt>String</tt> or the java.util.regex package instead. * <p> * The following example illustrates how the <tt>String.split</tt> * method can be used to break up a string into its basic tokens: * <blockquote><pre> * String[] result = "this is a test".split("\\s"); * for (int x=0; x&lt;result.length; x++) * System.out.println(result[x]); * </pre></blockquote> * <p> * prints the following output: * <blockquote><pre> * this * is * a * test * </pre></blockquote> * {@description.close} * * @author unascribed * @see java.io.StreamTokenizer * @since JDK1.0 */ public class StringTokenizer implements Enumeration<Object> { private int currentPosition; private int newPosition; private int maxPosition; private String str; private String delimiters; private boolean retDelims; private boolean delimsChanged; /** {@collect.stats} * {@description.open} * maxDelimCodePoint stores the value of the delimiter character with the * highest value. It is used to optimize the detection of delimiter * characters. * * It is unlikely to provide any optimization benefit in the * hasSurrogates case because most string characters will be * smaller than the limit, but we keep it so that the two code * paths remain similar. * {@description.close} */ private int maxDelimCodePoint; /** {@collect.stats} * {@description.open} * If delimiters include any surrogates (including surrogate * pairs), hasSurrogates is true and the tokenizer uses the * different code path. This is because String.indexOf(int) * doesn't handle unpaired surrogates as a single character. * {@description.close} */ private boolean hasSurrogates = false; /** {@collect.stats} * {@description.open} * When hasSurrogates is true, delimiters are converted to code * points and isDelimiter(int) is used to determine if the given * codepoint is a delimiter. * {@description.close} */ private int[] delimiterCodePoints; /** {@collect.stats} * {@description.open} * Set maxDelimCodePoint to the highest char in the delimiter set. * {@description.close} */ private void setMaxDelimCodePoint() { if (delimiters == null) { maxDelimCodePoint = 0; return; } int m = 0; int c; int count = 0; for (int i = 0; i < delimiters.length(); i += Character.charCount(c)) { c = delimiters.charAt(i); if (c >= Character.MIN_HIGH_SURROGATE && c <= Character.MAX_LOW_SURROGATE) { c = delimiters.codePointAt(i); hasSurrogates = true; } if (m < c) m = c; count++; } maxDelimCodePoint = m; if (hasSurrogates) { delimiterCodePoints = new int[count]; for (int i = 0, j = 0; i < count; i++, j += Character.charCount(c)) { c = delimiters.codePointAt(j); delimiterCodePoints[i] = c; } } } /** {@collect.stats} * {@description.open} * Constructs a string tokenizer for the specified string. All * characters in the <code>delim</code> argument are the delimiters * for separating tokens. * <p> * If the <code>returnDelims</code> flag is <code>true</code>, then * the delimiter characters are also returned as tokens. Each * delimiter is returned as a string of length one. If the flag is * <code>false</code>, the delimiter characters are skipped and only * serve as separators between tokens. * <p> * Note that if <tt>delim</tt> is <tt>null</tt>, this constructor does * not throw an exception. However, trying to invoke other methods on the * resulting <tt>StringTokenizer</tt> may result in a * <tt>NullPointerException</tt>. * {@description.close} * * @param str a string to be parsed. * @param delim the delimiters. * @param returnDelims flag indicating whether to return the delimiters * as tokens. * @exception NullPointerException if str is <CODE>null</CODE> */ public StringTokenizer(String str, String delim, boolean returnDelims) { currentPosition = 0; newPosition = -1; delimsChanged = false; this.str = str; maxPosition = str.length(); delimiters = delim; retDelims = returnDelims; setMaxDelimCodePoint(); } /** {@collect.stats} * {@description.open} * Constructs a string tokenizer for the specified string. The * characters in the <code>delim</code> argument are the delimiters * for separating tokens. Delimiter characters themselves will not * be treated as tokens. * <p> * Note that if <tt>delim</tt> is <tt>null</tt>, this constructor does * not throw an exception. However, trying to invoke other methods on the * resulting <tt>StringTokenizer</tt> may result in a * <tt>NullPointerException</tt>. * {@description.close} * * @param str a string to be parsed. * @param delim the delimiters. * @exception NullPointerException if str is <CODE>null</CODE> */ public StringTokenizer(String str, String delim) { this(str, delim, false); } /** {@collect.stats} * {@description.open} * Constructs a string tokenizer for the specified string. The * tokenizer uses the default delimiter set, which is * <code>"&nbsp;&#92;t&#92;n&#92;r&#92;f"</code>: the space character, * the tab character, the newline character, the carriage-return character, * and the form-feed character. Delimiter characters themselves will * not be treated as tokens. * {@description.close} * * @param str a string to be parsed. * @exception NullPointerException if str is <CODE>null</CODE> */ public StringTokenizer(String str) { this(str, " \t\n\r\f", false); } /** {@collect.stats} * {@description.open} * Skips delimiters starting from the specified position. If retDelims * is false, returns the index of the first non-delimiter character at or * after startPos. If retDelims is true, startPos is returned. * {@description.close} */ private int skipDelimiters(int startPos) { if (delimiters == null) throw new NullPointerException(); int position = startPos; while (!retDelims && position < maxPosition) { if (!hasSurrogates) { char c = str.charAt(position); if ((c > maxDelimCodePoint) || (delimiters.indexOf(c) < 0)) break; position++; } else { int c = str.codePointAt(position); if ((c > maxDelimCodePoint) || !isDelimiter(c)) { break; } position += Character.charCount(c); } } return position; } /** {@collect.stats} * {@description.open} * Skips ahead from startPos and returns the index of the next delimiter * character encountered, or maxPosition if no such delimiter is found. * {@description.close} */ private int scanToken(int startPos) { int position = startPos; while (position < maxPosition) { if (!hasSurrogates) { char c = str.charAt(position); if ((c <= maxDelimCodePoint) && (delimiters.indexOf(c) >= 0)) break; position++; } else { int c = str.codePointAt(position); if ((c <= maxDelimCodePoint) && isDelimiter(c)) break; position += Character.charCount(c); } } if (retDelims && (startPos == position)) { if (!hasSurrogates) { char c = str.charAt(position); if ((c <= maxDelimCodePoint) && (delimiters.indexOf(c) >= 0)) position++; } else { int c = str.codePointAt(position); if ((c <= maxDelimCodePoint) && isDelimiter(c)) position += Character.charCount(c); } } return position; } private boolean isDelimiter(int codePoint) { for (int i = 0; i < delimiterCodePoints.length; i++) { if (delimiterCodePoints[i] == codePoint) { return true; } } return false; } /** {@collect.stats} * {@description.open} * Tests if there are more tokens available from this tokenizer's string. * If this method returns <tt>true</tt>, then a subsequent call to * <tt>nextToken</tt> with no argument will successfully return a token. * {@description.close} * * @return <code>true</code> if and only if there is at least one token * in the string after the current position; <code>false</code> * otherwise. */ public boolean hasMoreTokens() { /* * Temporarily store this position and use it in the following * nextToken() method only if the delimiters haven't been changed in * that nextToken() invocation. */ newPosition = skipDelimiters(currentPosition); return (newPosition < maxPosition); } /** {@collect.stats} * {@description.open} * Returns the next token from this string tokenizer. * {@description.close} * * @return the next token from this string tokenizer. * @exception NoSuchElementException if there are no more tokens in this * tokenizer's string. */ public String nextToken() { /* * If next position already computed in hasMoreElements() and * delimiters have changed between the computation and this invocation, * then use the computed value. */ currentPosition = (newPosition >= 0 && !delimsChanged) ? newPosition : skipDelimiters(currentPosition); /* Reset these anyway */ delimsChanged = false; newPosition = -1; if (currentPosition >= maxPosition) throw new NoSuchElementException(); int start = currentPosition; currentPosition = scanToken(currentPosition); return str.substring(start, currentPosition); } /** {@collect.stats} * {@description.open} * Returns the next token in this string tokenizer's string. First, * the set of characters considered to be delimiters by this * <tt>StringTokenizer</tt> object is changed to be the characters in * the string <tt>delim</tt>. Then the next token in the string * after the current position is returned. The current position is * advanced beyond the recognized token. The new delimiter set * remains the default after this call. * {@description.close} * {@property.open formal:java.util.StringTokenizer_HasMoreElements} * {@new.open} * In general, it is recommended to call hasNext() and check the return * value before calling this method. * {@new.close} * {@property.close} * * @param delim the new delimiters. * @return the next token, after switching to the new delimiter set. * @exception NoSuchElementException if there are no more tokens in this * tokenizer's string. * @exception NullPointerException if delim is <CODE>null</CODE> */ public String nextToken(String delim) { delimiters = delim; /* delimiter string specified, so set the appropriate flag. */ delimsChanged = true; setMaxDelimCodePoint(); return nextToken(); } /** {@collect.stats} * {@description.open} * Returns the same value as the <code>hasMoreTokens</code> * method. It exists so that this class can implement the * <code>Enumeration</code> interface. * {@description.close} * * @return <code>true</code> if there are more tokens; * <code>false</code> otherwise. * @see java.util.Enumeration * @see java.util.StringTokenizer#hasMoreTokens() */ public boolean hasMoreElements() { return hasMoreTokens(); } /** {@collect.stats} * {@description.open} * Returns the same value as the <code>nextToken</code> method, * except that its declared return value is <code>Object</code> rather than * <code>String</code>. It exists so that this class can implement the * <code>Enumeration</code> interface. * {@description.close} * {@property.open formal:java.util.StringTokenizer_HasMoreElements} * {@new.open} * In general, it is recommended to call hasNext() and check the return * value before calling this method. * {@new.close} * {@property.close} * * @return the next token in the string. * @exception NoSuchElementException if there are no more tokens in this * tokenizer's string. * @see java.util.Enumeration * @see java.util.StringTokenizer#nextToken() */ public Object nextElement() { return nextToken(); } /** {@collect.stats} * {@description.open} * Calculates the number of times that this tokenizer's * <code>nextToken</code> method can be called before it generates an * exception. The current position is not advanced. * {@description.close} * * @return the number of tokens remaining in the string using the current * delimiter set. * @see java.util.StringTokenizer#nextToken() */ public int countTokens() { int count = 0; int currpos = currentPosition; while (currpos < maxPosition) { currpos = skipDelimiters(currpos); if (currpos >= maxPosition) break; currpos = scanToken(currpos); count++; } return count; } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * This class implements the <tt>Set</tt> interface, backed by a hash table * (actually a <tt>HashMap</tt> instance). It makes no guarantees as to the * iteration order of the set; in particular, it does not guarantee that the * order will remain constant over time. This class permits the <tt>null</tt> * element. * * <p>This class offers constant time performance for the basic operations * (<tt>add</tt>, <tt>remove</tt>, <tt>contains</tt> and <tt>size</tt>), * assuming the hash function disperses the elements properly among the * buckets. Iterating over this set requires time proportional to the sum of * the <tt>HashSet</tt> instance's size (the number of elements) plus the * "capacity" of the backing <tt>HashMap</tt> instance (the number of * buckets). Thus, it's very important not to set the initial capacity too * high (or the load factor too low) if iteration performance is important. * {@description.close} * * {@description.open synchronization} * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access a hash set concurrently, and at least one of * the threads modifies the set, it <i>must</i> be synchronized externally. * This is typically accomplished by synchronizing on some object that * naturally encapsulates the set. * * If no such object exists, the set should be "wrapped" using the * {@link Collections#synchronizedSet Collections.synchronizedSet} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the set:<pre> * Set s = Collections.synchronizedSet(new HashSet(...));</pre> * {@description.close} * * {@property.open formal:java.util.Collection_UnsafeIterator} * <p>The iterators returned by this class's <tt>iterator</tt> method are * <i>fail-fast</i>: if the set is modified at any time after the iterator is * created, in any way except through the iterator's own <tt>remove</tt> * method, the Iterator throws a {@link ConcurrentModificationException}. * Thus, in the face of concurrent modification, the iterator fails quickly * and cleanly, rather than risking arbitrary, non-deterministic behavior at * an undetermined time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * {@property.close} * * {@description.open} * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <E> the type of elements maintained by this set * * @author Josh Bloch * @author Neal Gafter * @see Collection * @see Set * @see TreeSet * @see HashMap * @since 1.2 */ public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable { static final long serialVersionUID = -5024744406713321676L; private transient HashMap<E,Object> map; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); /** {@collect.stats} * {@description.open} * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has * default initial capacity (16) and load factor (0.75). * {@description.close} */ public HashSet() { map = new HashMap<E,Object>(); } /** {@collect.stats} * {@description.open} * Constructs a new set containing the elements in the specified * collection. The <tt>HashMap</tt> is created with default load factor * (0.75) and an initial capacity sufficient to contain the elements in * the specified collection. * {@description.close} * * @param c the collection whose elements are to be placed into this set * @throws NullPointerException if the specified collection is null */ public HashSet(Collection<? extends E> c) { map = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16)); addAll(c); } /** {@collect.stats} * {@description.open} * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has * the specified initial capacity and the specified load factor. * {@description.close} * * @param initialCapacity the initial capacity of the hash map * @param loadFactor the load factor of the hash map * @throws IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive */ public HashSet(int initialCapacity, float loadFactor) { map = new HashMap<E,Object>(initialCapacity, loadFactor); } /** {@collect.stats} * {@description.open} * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has * the specified initial capacity and default load factor (0.75). * {@description.close} * * @param initialCapacity the initial capacity of the hash table * @throws IllegalArgumentException if the initial capacity is less * than zero */ public HashSet(int initialCapacity) { map = new HashMap<E,Object>(initialCapacity); } /** {@collect.stats} * {@description.open} * Constructs a new, empty linked hash set. (This package private * constructor is only used by LinkedHashSet.) The backing * HashMap instance is a LinkedHashMap with the specified initial * capacity and the specified load factor. * {@description.close} * * @param initialCapacity the initial capacity of the hash map * @param loadFactor the load factor of the hash map * @param dummy ignored (distinguishes this * constructor from other int, float constructor.) * @throws IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive */ HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor); } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this set. The elements * are returned in no particular order. * {@description.close} * * @return an Iterator over the elements in this set * @see ConcurrentModificationException */ public Iterator<E> iterator() { return map.keySet().iterator(); } /** {@collect.stats} * {@description.open} * Returns the number of elements in this set (its cardinality). * {@description.close} * * @return the number of elements in this set (its cardinality) */ public int size() { return map.size(); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains no elements. * {@description.close} * * @return <tt>true</tt> if this set contains no elements */ public boolean isEmpty() { return map.isEmpty(); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains the specified element. * More formally, returns <tt>true</tt> if and only if this set * contains an element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * {@description.close} * * @param o element whose presence in this set is to be tested * @return <tt>true</tt> if this set contains the specified element */ public boolean contains(Object o) { return map.containsKey(o); } /** {@collect.stats} * {@description.open} * Adds the specified element to this set if it is not already present. * More formally, adds the specified element <tt>e</tt> to this set if * this set contains no element <tt>e2</tt> such that * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt>. * {@description.close} * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element */ public boolean add(E e) { return map.put(e, PRESENT)==null; } /** {@collect.stats} * {@description.open} * Removes the specified element from this set if it is present. * More formally, removes an element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, * if this set contains such an element. Returns <tt>true</tt> if * this set contained the element (or equivalently, if this set * changed as a result of the call). (This set will not contain the * element once the call returns.) * {@description.close} * * @param o object to be removed from this set, if present * @return <tt>true</tt> if the set contained the specified element */ public boolean remove(Object o) { return map.remove(o)==PRESENT; } /** {@collect.stats} * {@description.open} * Removes all of the elements from this set. * The set will be empty after this call returns. * {@description.close} */ public void clear() { map.clear(); } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this <tt>HashSet</tt> instance: the elements * themselves are not cloned. * {@description.close} * * @return a shallow copy of this set */ public Object clone() { try { HashSet<E> newSet = (HashSet<E>) super.clone(); newSet.map = (HashMap<E, Object>) map.clone(); return newSet; } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** {@collect.stats} * {@description.open} * Save the state of this <tt>HashSet</tt> instance to a stream (that is, * serialize it). * {@description.close} * * @serialData The capacity of the backing <tt>HashMap</tt> instance * (int), and its load factor (float) are emitted, followed by * the size of the set (the number of elements it contains) * (int), followed by all of its elements (each an Object) in * no particular order. */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden serialization magic s.defaultWriteObject(); // Write out HashMap capacity and load factor s.writeInt(map.capacity()); s.writeFloat(map.loadFactor()); // Write out size s.writeInt(map.size()); // Write out all elements in the proper order. for (Iterator i=map.keySet().iterator(); i.hasNext(); ) s.writeObject(i.next()); } /** {@collect.stats} * {@description.open} * Reconstitute the <tt>HashSet</tt> instance from a stream (that is, * deserialize it). * {@description.close} */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in any hidden serialization magic s.defaultReadObject(); // Read in HashMap capacity and load factor and create backing HashMap int capacity = s.readInt(); float loadFactor = s.readFloat(); map = (((HashSet)this) instanceof LinkedHashSet ? new LinkedHashMap<E,Object>(capacity, loadFactor) : new HashMap<E,Object>(capacity, loadFactor)); // Read in size int size = s.readInt(); // Read in all elements in the proper order. for (int i=0; i<size; i++) { E e = (E) s.readObject(); map.put(e, PRESENT); } } }
Java
/* * Copyright (c) 1995, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.LongBuffer; /** {@collect.stats} * {@description.open} * This class implements a vector of bits that grows as needed. Each * component of the bit set has a {@code boolean} value. The * bits of a {@code BitSet} are indexed by nonnegative integers. * Individual indexed bits can be examined, set, or cleared. One * {@code BitSet} may be used to modify the contents of another * {@code BitSet} through logical AND, logical inclusive OR, and * logical exclusive OR operations. * * <p>By default, all bits in the set initially have the value * {@code false}. * * <p>Every bit set has a current size, which is the number of bits * of space currently in use by the bit set. Note that the size is * related to the implementation of a bit set, so it may change with * implementation. The length of a bit set relates to logical length * of a bit set and is defined independently of implementation. * * <p>Unless otherwise noted, passing a null parameter to any of the * methods in a {@code BitSet} will result in a * {@code NullPointerException}. * {@description.close} * * {@property.open synchronized} * <p>A {@code BitSet} is not safe for multithreaded use without * external synchronization. * {@property.close} * * @author Arthur van Hoff * @author Michael McCloskey * @author Martin Buchholz * @since JDK1.0 */ public class BitSet implements Cloneable, java.io.Serializable { /* * BitSets are packed into arrays of "words." Currently a word is * a long, which consists of 64 bits, requiring 6 address bits. * The choice of word size is determined purely by performance concerns. */ private final static int ADDRESS_BITS_PER_WORD = 6; private final static int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD; private final static int BIT_INDEX_MASK = BITS_PER_WORD - 1; /* Used to shift left or right for a partial word mask */ private static final long WORD_MASK = 0xffffffffffffffffL; /** {@collect.stats} * @serialField bits long[] * * The bits in this BitSet. The ith bit is stored in bits[i/64] at * bit position i % 64 (where bit position 0 refers to the least * significant bit and 63 refers to the most significant bit). */ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("bits", long[].class), }; /** {@collect.stats} * {@description.open} * The internal field corresponding to the serialField "bits". * {@description.close} */ private long[] words; /** {@collect.stats} * {@description.open} * The number of words in the logical size of this BitSet. * {@description.close} */ private transient int wordsInUse = 0; /** {@collect.stats} * {@description.open} * Whether the size of "words" is user-specified. If so, we assume * the user knows what he's doing and try harder to preserve it. * {@description.close} */ private transient boolean sizeIsSticky = false; /* use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = 7997698588986878753L; /** {@collect.stats} * {@description.open} * Given a bit index, return word index containing it. * {@description.close} */ private static int wordIndex(int bitIndex) { return bitIndex >> ADDRESS_BITS_PER_WORD; } /** {@collect.stats} * {@description.open} * Every public method must preserve these invariants. * {@description.close} */ private void checkInvariants() { assert(wordsInUse == 0 || words[wordsInUse - 1] != 0); assert(wordsInUse >= 0 && wordsInUse <= words.length); assert(wordsInUse == words.length || words[wordsInUse] == 0); } /** {@collect.stats} * {@description.open} * Sets the field wordsInUse to the logical size in words of the bit set. * WARNING:This method assumes that the number of words actually in use is * less than or equal to the current value of wordsInUse! * {@description.close} */ private void recalculateWordsInUse() { // Traverse the bitset until a used word is found int i; for (i = wordsInUse-1; i >= 0; i--) if (words[i] != 0) break; wordsInUse = i+1; // The new logical size } /** {@collect.stats} * {@description.open} * Creates a new bit set. All bits are initially {@code false}. * {@description.close} */ public BitSet() { initWords(BITS_PER_WORD); sizeIsSticky = false; } /** {@collect.stats} * {@description.open} * Creates a bit set whose initial size is large enough to explicitly * represent bits with indices in the range {@code 0} through * {@code nbits-1}. All bits are initially {@code false}. * {@description.close} * * @param nbits the initial size of the bit set * @throws NegativeArraySizeException if the specified initial size * is negative */ public BitSet(int nbits) { // nbits can't be negative; size 0 is OK if (nbits < 0) throw new NegativeArraySizeException("nbits < 0: " + nbits); initWords(nbits); sizeIsSticky = true; } private void initWords(int nbits) { words = new long[wordIndex(nbits-1) + 1]; } /** {@collect.stats} * {@description.open} * Creates a bit set using words as the internal representation. * The last word (if there is one) must be non-zero. * {@description.close} */ private BitSet(long[] words) { this.words = words; this.wordsInUse = words.length; checkInvariants(); } /** {@collect.stats} * {@description.open} * Ensures that the BitSet can hold enough words. * {@description.close} * @param wordsRequired the minimum acceptable number of words. */ private void ensureCapacity(int wordsRequired) { if (words.length < wordsRequired) { // Allocate larger of doubled size or required size int request = Math.max(2 * words.length, wordsRequired); words = Arrays.copyOf(words, request); sizeIsSticky = false; } } /** {@collect.stats} * {@description.open} * Ensures that the BitSet can accommodate a given wordIndex, * temporarily violating the invariants. * {@description.close} * {@property.open internal} * The caller must * restore the invariants before returning to the user, * possibly using recalculateWordsInUse(). * {@property.close} * @param wordIndex the index to be accommodated. */ private void expandTo(int wordIndex) { int wordsRequired = wordIndex+1; if (wordsInUse < wordsRequired) { ensureCapacity(wordsRequired); wordsInUse = wordsRequired; } } /** {@collect.stats} * {@description.open} * Checks that fromIndex ... toIndex is a valid range of bit indices. * {@description.close} */ private static void checkRange(int fromIndex, int toIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); if (toIndex < 0) throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex); if (fromIndex > toIndex) throw new IndexOutOfBoundsException("fromIndex: " + fromIndex + " > toIndex: " + toIndex); } /** {@collect.stats} * {@description.open} * Sets the bit at the specified index to the complement of its * current value. * {@description.close} * * @param bitIndex the index of the bit to flip * @throws IndexOutOfBoundsException if the specified index is negative * @since 1.4 */ public void flip(int bitIndex) { if (bitIndex < 0) throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex); int wordIndex = wordIndex(bitIndex); expandTo(wordIndex); words[wordIndex] ^= (1L << bitIndex); recalculateWordsInUse(); checkInvariants(); } /** {@collect.stats} * {@description.open} * Sets each bit from the specified {@code fromIndex} (inclusive) to the * specified {@code toIndex} (exclusive) to the complement of its current * value. * {@description.close} * * @param fromIndex index of the first bit to flip * @param toIndex index after the last bit to flip * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, * or {@code toIndex} is negative, or {@code fromIndex} is * larger than {@code toIndex} * @since 1.4 */ public void flip(int fromIndex, int toIndex) { checkRange(fromIndex, toIndex); if (fromIndex == toIndex) return; int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); expandTo(endWordIndex); long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // Case 1: One word words[startWordIndex] ^= (firstWordMask & lastWordMask); } else { // Case 2: Multiple words // Handle first word words[startWordIndex] ^= firstWordMask; // Handle intermediate words, if any for (int i = startWordIndex+1; i < endWordIndex; i++) words[i] ^= WORD_MASK; // Handle last word words[endWordIndex] ^= lastWordMask; } recalculateWordsInUse(); checkInvariants(); } /** {@collect.stats} * {@description.open} * Sets the bit at the specified index to {@code true}. * {@description.close} * * @param bitIndex a bit index * @throws IndexOutOfBoundsException if the specified index is negative * @since JDK1.0 */ public void set(int bitIndex) { if (bitIndex < 0) throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex); int wordIndex = wordIndex(bitIndex); expandTo(wordIndex); words[wordIndex] |= (1L << bitIndex); // Restores invariants checkInvariants(); } /** {@collect.stats} * {@description.open} * Sets the bit at the specified index to the specified value. * {@description.close} * * @param bitIndex a bit index * @param value a boolean value to set * @throws IndexOutOfBoundsException if the specified index is negative * @since 1.4 */ public void set(int bitIndex, boolean value) { if (value) set(bitIndex); else clear(bitIndex); } /** {@collect.stats} * {@description.open} * Sets the bits from the specified {@code fromIndex} (inclusive) to the * specified {@code toIndex} (exclusive) to {@code true}. * {@description.close} * * @param fromIndex index of the first bit to be set * @param toIndex index after the last bit to be set * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, * or {@code toIndex} is negative, or {@code fromIndex} is * larger than {@code toIndex} * @since 1.4 */ public void set(int fromIndex, int toIndex) { checkRange(fromIndex, toIndex); if (fromIndex == toIndex) return; // Increase capacity if necessary int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); expandTo(endWordIndex); long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // Case 1: One word words[startWordIndex] |= (firstWordMask & lastWordMask); } else { // Case 2: Multiple words // Handle first word words[startWordIndex] |= firstWordMask; // Handle intermediate words, if any for (int i = startWordIndex+1; i < endWordIndex; i++) words[i] = WORD_MASK; // Handle last word (restores invariants) words[endWordIndex] |= lastWordMask; } checkInvariants(); } /** {@collect.stats} * {@description.open} * Sets the bits from the specified {@code fromIndex} (inclusive) to the * specified {@code toIndex} (exclusive) to the specified value. * {@description.close} * * @param fromIndex index of the first bit to be set * @param toIndex index after the last bit to be set * @param value value to set the selected bits to * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, * or {@code toIndex} is negative, or {@code fromIndex} is * larger than {@code toIndex} * @since 1.4 */ public void set(int fromIndex, int toIndex, boolean value) { if (value) set(fromIndex, toIndex); else clear(fromIndex, toIndex); } /** {@collect.stats} * {@description.open} * Sets the bit specified by the index to {@code false}. * {@description.close} * * @param bitIndex the index of the bit to be cleared * @throws IndexOutOfBoundsException if the specified index is negative * @since JDK1.0 */ public void clear(int bitIndex) { if (bitIndex < 0) throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex); int wordIndex = wordIndex(bitIndex); if (wordIndex >= wordsInUse) return; words[wordIndex] &= ~(1L << bitIndex); recalculateWordsInUse(); checkInvariants(); } /** {@collect.stats} * {@description.open} * Sets the bits from the specified {@code fromIndex} (inclusive) to the * specified {@code toIndex} (exclusive) to {@code false}. * {@description.close} * * @param fromIndex index of the first bit to be cleared * @param toIndex index after the last bit to be cleared * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, * or {@code toIndex} is negative, or {@code fromIndex} is * larger than {@code toIndex} * @since 1.4 */ public void clear(int fromIndex, int toIndex) { checkRange(fromIndex, toIndex); if (fromIndex == toIndex) return; int startWordIndex = wordIndex(fromIndex); if (startWordIndex >= wordsInUse) return; int endWordIndex = wordIndex(toIndex - 1); if (endWordIndex >= wordsInUse) { toIndex = length(); endWordIndex = wordsInUse - 1; } long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // Case 1: One word words[startWordIndex] &= ~(firstWordMask & lastWordMask); } else { // Case 2: Multiple words // Handle first word words[startWordIndex] &= ~firstWordMask; // Handle intermediate words, if any for (int i = startWordIndex+1; i < endWordIndex; i++) words[i] = 0; // Handle last word words[endWordIndex] &= ~lastWordMask; } recalculateWordsInUse(); checkInvariants(); } /** {@collect.stats} * {@description.open} * Sets all of the bits in this BitSet to {@code false}. * {@description.close} * * @since 1.4 */ public void clear() { while (wordsInUse > 0) words[--wordsInUse] = 0; } /** {@collect.stats} * {@description.open} * Returns the value of the bit with the specified index. The value * is {@code true} if the bit with the index {@code bitIndex} * is currently set in this {@code BitSet}; otherwise, the result * is {@code false}. * {@description.close} * * @param bitIndex the bit index * @return the value of the bit with the specified index * @throws IndexOutOfBoundsException if the specified index is negative */ public boolean get(int bitIndex) { if (bitIndex < 0) throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex); checkInvariants(); int wordIndex = wordIndex(bitIndex); return (wordIndex < wordsInUse) && ((words[wordIndex] & (1L << bitIndex)) != 0); } /** {@collect.stats} * {@description.open} * Returns a new {@code BitSet} composed of bits from this {@code BitSet} * from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive). * {@description.close} * * @param fromIndex index of the first bit to include * @param toIndex index after the last bit to include * @return a new {@code BitSet} from a range of this {@code BitSet} * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, * or {@code toIndex} is negative, or {@code fromIndex} is * larger than {@code toIndex} * @since 1.4 */ public BitSet get(int fromIndex, int toIndex) { checkRange(fromIndex, toIndex); checkInvariants(); int len = length(); // If no set bits in range return empty bitset if (len <= fromIndex || fromIndex == toIndex) return new BitSet(0); // An optimization if (toIndex > len) toIndex = len; BitSet result = new BitSet(toIndex - fromIndex); int targetWords = wordIndex(toIndex - fromIndex - 1) + 1; int sourceIndex = wordIndex(fromIndex); boolean wordAligned = ((fromIndex & BIT_INDEX_MASK) == 0); // Process all words but the last word for (int i = 0; i < targetWords - 1; i++, sourceIndex++) result.words[i] = wordAligned ? words[sourceIndex] : (words[sourceIndex] >>> fromIndex) | (words[sourceIndex+1] << -fromIndex); // Process the last word long lastWordMask = WORD_MASK >>> -toIndex; result.words[targetWords - 1] = ((toIndex-1) & BIT_INDEX_MASK) < (fromIndex & BIT_INDEX_MASK) ? /* straddles source words */ ((words[sourceIndex] >>> fromIndex) | (words[sourceIndex+1] & lastWordMask) << -fromIndex) : ((words[sourceIndex] & lastWordMask) >>> fromIndex); // Set wordsInUse correctly result.wordsInUse = targetWords; result.recalculateWordsInUse(); result.checkInvariants(); return result; } /** {@collect.stats} * {@description.open} * Returns the index of the first bit that is set to {@code true} * that occurs on or after the specified starting index. If no such * bit exists then {@code -1} is returned. * * <p>To iterate over the {@code true} bits in a {@code BitSet}, * use the following loop: * * <pre> {@code * for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { * // operate on index i here * }}</pre> * {@description.close} * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next set bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is negative * @since 1.4 */ public int nextSetBit(int fromIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); checkInvariants(); int u = wordIndex(fromIndex); if (u >= wordsInUse) return -1; long word = words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); if (++u == wordsInUse) return -1; word = words[u]; } } /** {@collect.stats} * {@description.open} * Returns the index of the first bit that is set to {@code false} * that occurs on or after the specified starting index. * {@description.close} * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next clear bit * @throws IndexOutOfBoundsException if the specified index is negative * @since 1.4 */ public int nextClearBit(int fromIndex) { // Neither spec nor implementation handle bitsets of maximal length. // See 4816253. if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); checkInvariants(); int u = wordIndex(fromIndex); if (u >= wordsInUse) return fromIndex; long word = ~words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); if (++u == wordsInUse) return wordsInUse * BITS_PER_WORD; word = ~words[u]; } } /** {@collect.stats} * {@description.open} * Returns the "logical size" of this {@code BitSet}: the index of * the highest set bit in the {@code BitSet} plus one. Returns zero * if the {@code BitSet} contains no set bits. * {@description.close} * * @return the logical size of this {@code BitSet} * @since 1.2 */ public int length() { if (wordsInUse == 0) return 0; return BITS_PER_WORD * (wordsInUse - 1) + (BITS_PER_WORD - Long.numberOfLeadingZeros(words[wordsInUse - 1])); } /** {@collect.stats} * {@description.open} * Returns true if this {@code BitSet} contains no bits that are set * to {@code true}. * {@description.close} * * @return boolean indicating whether this {@code BitSet} is empty * @since 1.4 */ public boolean isEmpty() { return wordsInUse == 0; } /** {@collect.stats} * {@description.open} * Returns true if the specified {@code BitSet} has any bits set to * {@code true} that are also set to {@code true} in this {@code BitSet}. * {@description.close} * * @param set {@code BitSet} to intersect with * @return boolean indicating whether this {@code BitSet} intersects * the specified {@code BitSet} * @since 1.4 */ public boolean intersects(BitSet set) { for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--) if ((words[i] & set.words[i]) != 0) return true; return false; } /** {@collect.stats} * {@description.open} * Returns the number of bits set to {@code true} in this {@code BitSet}. * {@description.close} * * @return the number of bits set to {@code true} in this {@code BitSet} * @since 1.4 */ public int cardinality() { int sum = 0; for (int i = 0; i < wordsInUse; i++) sum += Long.bitCount(words[i]); return sum; } /** {@collect.stats} * {@description.open} * Performs a logical <b>AND</b> of this target bit set with the * argument bit set. This bit set is modified so that each bit in it * has the value {@code true} if and only if it both initially * had the value {@code true} and the corresponding bit in the * bit set argument also had the value {@code true}. * {@description.close} * * @param set a bit set */ public void and(BitSet set) { if (this == set) return; while (wordsInUse > set.wordsInUse) words[--wordsInUse] = 0; // Perform logical AND on words in common for (int i = 0; i < wordsInUse; i++) words[i] &= set.words[i]; recalculateWordsInUse(); checkInvariants(); } /** {@collect.stats} * {@description.open} * Performs a logical <b>OR</b> of this bit set with the bit set * argument. This bit set is modified so that a bit in it has the * value {@code true} if and only if it either already had the * value {@code true} or the corresponding bit in the bit set * argument has the value {@code true}. * {@description.close} * * @param set a bit set */ public void or(BitSet set) { if (this == set) return; int wordsInCommon = Math.min(wordsInUse, set.wordsInUse); if (wordsInUse < set.wordsInUse) { ensureCapacity(set.wordsInUse); wordsInUse = set.wordsInUse; } // Perform logical OR on words in common for (int i = 0; i < wordsInCommon; i++) words[i] |= set.words[i]; // Copy any remaining words if (wordsInCommon < set.wordsInUse) System.arraycopy(set.words, wordsInCommon, words, wordsInCommon, wordsInUse - wordsInCommon); // recalculateWordsInUse() is unnecessary checkInvariants(); } /** {@collect.stats} * {@description.open} * Performs a logical <b>XOR</b> of this bit set with the bit set * argument. This bit set is modified so that a bit in it has the * value {@code true} if and only if one of the following * statements holds: * <ul> * <li>The bit initially has the value {@code true}, and the * corresponding bit in the argument has the value {@code false}. * <li>The bit initially has the value {@code false}, and the * corresponding bit in the argument has the value {@code true}. * </ul> * {@description.close} * * @param set a bit set */ public void xor(BitSet set) { int wordsInCommon = Math.min(wordsInUse, set.wordsInUse); if (wordsInUse < set.wordsInUse) { ensureCapacity(set.wordsInUse); wordsInUse = set.wordsInUse; } // Perform logical XOR on words in common for (int i = 0; i < wordsInCommon; i++) words[i] ^= set.words[i]; // Copy any remaining words if (wordsInCommon < set.wordsInUse) System.arraycopy(set.words, wordsInCommon, words, wordsInCommon, set.wordsInUse - wordsInCommon); recalculateWordsInUse(); checkInvariants(); } /** {@collect.stats} * {@description.open} * Clears all of the bits in this {@code BitSet} whose corresponding * bit is set in the specified {@code BitSet}. * {@description.close} * * @param set the {@code BitSet} with which to mask this * {@code BitSet} * @since 1.2 */ public void andNot(BitSet set) { // Perform logical (a & !b) on words in common for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--) words[i] &= ~set.words[i]; recalculateWordsInUse(); checkInvariants(); } /** {@collect.stats} * {@description.open} * Returns a hash code value for this bit set. The hash code * depends only on which bits have been set within this * <code>BitSet</code>. The algorithm used to compute it may * be described as follows.<p> * Suppose the bits in the <code>BitSet</code> were to be stored * in an array of <code>long</code> integers called, say, * <code>words</code>, in such a manner that bit <code>k</code> is * set in the <code>BitSet</code> (for nonnegative values of * <code>k</code>) if and only if the expression * <pre>((k&gt;&gt;6) &lt; words.length) && ((words[k&gt;&gt;6] & (1L &lt;&lt; (bit & 0x3F))) != 0)</pre> * is true. Then the following definition of the <code>hashCode</code> * method would be a correct implementation of the actual algorithm: * <pre> * public int hashCode() { * long h = 1234; * for (int i = words.length; --i &gt;= 0; ) { * h ^= words[i] * (i + 1); * } * return (int)((h &gt;&gt; 32) ^ h); * }</pre> * Note that the hash code values change if the set of bits is altered. * <p>Overrides the <code>hashCode</code> method of <code>Object</code>. * {@description.close} * * @return a hash code value for this bit set. */ public int hashCode() { long h = 1234; for (int i = wordsInUse; --i >= 0; ) h ^= words[i] * (i + 1); return (int)((h >> 32) ^ h); } /** {@collect.stats} * {@description.open} * Returns the number of bits of space actually in use by this * {@code BitSet} to represent bit values. * The maximum element in the set is the size - 1st element. * {@description.close} * * @return the number of bits currently in this bit set */ public int size() { return words.length * BITS_PER_WORD; } /** {@collect.stats} * {@description.open} * Compares this object against the specified object. * The result is {@code true} if and only if the argument is * not {@code null} and is a {@code Bitset} object that has * exactly the same set of bits set to {@code true} as this bit * set. That is, for every nonnegative {@code int} index {@code k}, * <pre>((BitSet)obj).get(k) == this.get(k)</pre> * must be true. The current sizes of the two bit sets are not compared. * {@description.close} * * @param obj the object to compare with * @return {@code true} if the objects are the same; * {@code false} otherwise * @see #size() */ public boolean equals(Object obj) { if (!(obj instanceof BitSet)) return false; if (this == obj) return true; BitSet set = (BitSet) obj; checkInvariants(); set.checkInvariants(); if (wordsInUse != set.wordsInUse) return false; // Check words in use by both BitSets for (int i = 0; i < wordsInUse; i++) if (words[i] != set.words[i]) return false; return true; } /** {@collect.stats} * {@description.open} * Cloning this {@code BitSet} produces a new {@code BitSet} * that is equal to it. * The clone of the bit set is another bit set that has exactly the * same bits set to {@code true} as this bit set. * {@description.close} * * @return a clone of this bit set * @see #size() */ public Object clone() { if (! sizeIsSticky) trimToSize(); try { BitSet result = (BitSet) super.clone(); result.words = words.clone(); result.checkInvariants(); return result; } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** {@collect.stats} * {@description.open} * Attempts to reduce internal storage used for the bits in this bit set. * Calling this method may, but is not required to, affect the value * returned by a subsequent call to the {@link #size()} method. * {@description.close} */ private void trimToSize() { if (wordsInUse != words.length) { words = Arrays.copyOf(words, wordsInUse); checkInvariants(); } } /** {@collect.stats} * {@description.open} * Save the state of the {@code BitSet} instance to a stream (i.e., * serialize it). * {@description.close} */ private void writeObject(ObjectOutputStream s) throws IOException { checkInvariants(); if (! sizeIsSticky) trimToSize(); ObjectOutputStream.PutField fields = s.putFields(); fields.put("bits", words); s.writeFields(); } /** {@collect.stats} * {@description.open} * Reconstitute the {@code BitSet} instance from a stream (i.e., * deserialize it). * {@description.close} */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields = s.readFields(); words = (long[]) fields.get("bits", null); // Assume maximum length then find real length // because recalculateWordsInUse assumes maintenance // or reduction in logical size wordsInUse = words.length; recalculateWordsInUse(); sizeIsSticky = (words.length > 0 && words[words.length-1] == 0L); // heuristic checkInvariants(); } /** {@collect.stats} * {@description.open} * Returns a string representation of this bit set. For every index * for which this {@code BitSet} contains a bit in the set * state, the decimal representation of that index is included in * the result. Such indices are listed in order from lowest to * highest, separated by ",&nbsp;" (a comma and a space) and * surrounded by braces, resulting in the usual mathematical * notation for a set of integers. * * <p>Example: * <pre> * BitSet drPepper = new BitSet();</pre> * Now {@code drPepper.toString()} returns "{@code {}}".<p> * <pre> * drPepper.set(2);</pre> * Now {@code drPepper.toString()} returns "{@code {2}}".<p> * <pre> * drPepper.set(4); * drPepper.set(10);</pre> * Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}". * {@description.close} * * @return a string representation of this bit set */ public String toString() { checkInvariants(); int numBits = (wordsInUse > 128) ? cardinality() : wordsInUse * BITS_PER_WORD; StringBuilder b = new StringBuilder(6*numBits + 2); b.append('{'); int i = nextSetBit(0); if (i != -1) { b.append(i); for (i = nextSetBit(i+1); i >= 0; i = nextSetBit(i+1)) { int endOfRun = nextClearBit(i); do { b.append(", ").append(i); } while (++i < endOfRun); } } b.append('}'); return b.toString(); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util; /** {@collect.stats} * {@description.open} * This class provides skeletal implementations of some {@link Queue} * operations. * The implementations in this class are appropriate when * the base implementation does <em>not</em> allow <tt>null</tt> * elements. Methods {@link #add add}, {@link #remove remove}, and * {@link #element element} are based on {@link #offer offer}, {@link * #poll poll}, and {@link #peek peek}, respectively, but throw * exceptions instead of indicating failure via <tt>false</tt> or * <tt>null</tt> returns. * {@description.close} * * {@property.open static enforced} * <p> A <tt>Queue</tt> implementation that extends this class must * minimally define a method {@link Queue#offer} which does not permit * insertion of <tt>null</tt> elements, along with methods {@link * Queue#peek}, {@link Queue#poll}, {@link Collection#size}, and a * {@link Collection#iterator} supporting {@link * Iterator#remove}. Typically, additional methods will be overridden * as well. If these requirements cannot be met, consider instead * subclassing {@link AbstractCollection}. * {@property.close} * * {@description.open} * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */ public abstract class AbstractQueue<E> extends AbstractCollection<E> implements Queue<E> { /** {@collect.stats} * {@description.open} * Constructor for use by subclasses. * {@description.close} */ protected AbstractQueue() { } /** {@collect.stats} * {@description.open} * Inserts the specified element into this queue if it is possible to do so * immediately without violating capacity restrictions, returning * <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt> * if no space is currently available. * * <p>This implementation returns <tt>true</tt> if <tt>offer</tt> succeeds, * else throws an <tt>IllegalStateException</tt>. * {@description.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws ClassCastException if the class of the specified element * prevents it from being added to this queue * @throws NullPointerException if the specified element is null and * this queue does not permit null elements * @throws IllegalArgumentException if some property of this element * prevents it from being added to this queue */ public boolean add(E e) { if (offer(e)) return true; else throw new IllegalStateException("Queue full"); } /** {@collect.stats} * {@description.open} * Retrieves and removes the head of this queue. This method differs * from {@link #poll poll} only in that it throws an exception if this * queue is empty. * * <p>This implementation returns the result of <tt>poll</tt> * unless the queue is empty. * {@description.close} * * @return the head of this queue * @throws NoSuchElementException if this queue is empty */ public E remove() { E x = poll(); if (x != null) return x; else throw new NoSuchElementException(); } /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head of this queue. This method * differs from {@link #peek peek} only in that it throws an exception if * this queue is empty. * * <p>This implementation returns the result of <tt>peek</tt> * unless the queue is empty. * {@description.close} * * @return the head of this queue * @throws NoSuchElementException if this queue is empty */ public E element() { E x = peek(); if (x != null) return x; else throw new NoSuchElementException(); } /** {@collect.stats} * {@description.open} * Removes all of the elements from this queue. * The queue will be empty after this call returns. * * <p>This implementation repeatedly invokes {@link #poll poll} until it * returns <tt>null</tt>. * {@description.close} */ public void clear() { while (poll() != null) ; } /** {@collect.stats} * {@description.open} * Adds all of the elements in the specified collection to this * queue. Attempts to addAll of a queue to itself result in * <tt>IllegalArgumentException</tt>. * {@description.close} * {@property.open runtime formal:java.util.Collection_UnsynchronizedAddAll} * Further, the behavior of * this operation is undefined if the specified collection is * modified while the operation is in progress. * {@property.close} * * {@description.open} * <p>This implementation iterates over the specified collection, * and adds each element returned by the iterator to this * queue, in turn. A runtime exception encountered while * trying to add an element (including, in particular, a * <tt>null</tt> element) may result in only some of the elements * having been successfully added when the associated exception is * thrown. * {@description.close} * * @param c collection containing elements to be added to this queue * @return <tt>true</tt> if this queue changed as a result of the call * @throws ClassCastException if the class of an element of the specified * collection prevents it from being added to this queue * @throws NullPointerException if the specified collection contains a * null element and this queue does not permit null elements, * or if the specified collection is null * @throws IllegalArgumentException if some property of an element of the * specified collection prevents it from being added to this * queue, or if the specified collection is this queue * @throws IllegalStateException if not all the elements can be added at * this time due to insertion restrictions * @see #add(Object) */ public boolean addAll(Collection<? extends E> c) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); boolean modified = false; Iterator<? extends E> e = c.iterator(); while (e.hasNext()) { if (add(e.next())) modified = true; } return modified; } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved * * The original version of this source code and documentation * is copyrighted and owned by Taligent, Inc., a wholly-owned * subsidiary of IBM. These materials are provided under terms * of a License Agreement between Taligent and Sun. This technology * is protected by multiple US and International patents. * * This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. */ package java.util; import java.io.InputStream; import java.io.Reader; import java.io.IOException; import sun.util.ResourceBundleEnumeration; /** {@collect.stats} * {@description.open} * <code>PropertyResourceBundle</code> is a concrete subclass of * <code>ResourceBundle</code> that manages resources for a locale * using a set of static strings from a property file. See * {@link ResourceBundle ResourceBundle} for more information about resource * bundles. * * <p> * Unlike other types of resource bundle, you don't subclass * <code>PropertyResourceBundle</code>. Instead, you supply properties * files containing the resource data. <code>ResourceBundle.getBundle</code> * will automatically look for the appropriate properties file and create a * <code>PropertyResourceBundle</code> that refers to it. See * {@link ResourceBundle#getBundle(java.lang.String, java.util.Locale, java.lang.ClassLoader) ResourceBundle.getBundle} * for a complete description of the search and instantiation strategy. * * <p> * The following <a name="sample">example</a> shows a member of a resource * bundle family with the base name "MyResources". * The text defines the bundle "MyResources_de", * the German member of the bundle family. * This member is based on <code>PropertyResourceBundle</code>, and the text * therefore is the content of the file "MyResources_de.properties" * (a related <a href="ListResourceBundle.html#sample">example</a> shows * how you can add bundles to this family that are implemented as subclasses * of <code>ListResourceBundle</code>). * The keys in this example are of the form "s1" etc. The actual * keys are entirely up to your choice, so long as they are the same as * the keys you use in your program to retrieve the objects from the bundle. * Keys are case-sensitive. * <blockquote> * <pre> * # MessageFormat pattern * s1=Die Platte \"{1}\" enth&auml;lt {0}. * * # location of {0} in pattern * s2=1 * * # sample disk name * s3=Meine Platte * * # first ChoiceFormat choice * s4=keine Dateien * * # second ChoiceFormat choice * s5=eine Datei * * # third ChoiceFormat choice * s6={0,number} Dateien * * # sample date * s7=3. M&auml;rz 1996 * </pre> * </blockquote> * {@description.close} * * {@property.open uncheckable} * <p> * <strong>Note:</strong> PropertyResourceBundle can be constructed either * from an InputStream or a Reader, which represents a property file. * Constructing a PropertyResourceBundle instance from an InputStream requires * that the input stream be encoded in ISO-8859-1. In that case, characters * that cannot be represented in ISO-8859-1 encoding must be represented by * <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.3">Unicode Escapes</a>, * whereas the other constructor which takes a Reader does not have that limitation. * {@property.close} * * @see ResourceBundle * @see ListResourceBundle * @see Properties * @since JDK1.1 */ public class PropertyResourceBundle extends ResourceBundle { /** {@collect.stats} * {@description.open} * Creates a property resource bundle from an {@link java.io.InputStream * InputStream}. * {@description.close} * {@property.open uncheckable} * The property file read with this constructor * must be encoded in ISO-8859-1. * {@property.close} * * @param stream an InputStream that represents a property file * to read from. * @throws IOException if an I/O error occurs * @throws NullPointerException if <code>stream</code> is null */ public PropertyResourceBundle (InputStream stream) throws IOException { Properties properties = new Properties(); properties.load(stream); lookup = new HashMap(properties); } /** {@collect.stats} * {@description.open} * Creates a property resource bundle from a {@link java.io.Reader * Reader}. Unlike the constructor * {@link #PropertyResourceBundle(java.io.InputStream) PropertyResourceBundle(InputStream)}, * there is no limitation as to the encoding of the input property file. * {@description.close} * * @param reader a Reader that represents a property file to * read from. * @throws IOException if an I/O error occurs * @throws NullPointerException if <code>reader</code> is null * @since 1.6 */ public PropertyResourceBundle (Reader reader) throws IOException { Properties properties = new Properties(); properties.load(reader); lookup = new HashMap(properties); } // Implements java.util.ResourceBundle.handleGetObject; inherits javadoc specification. public Object handleGetObject(String key) { if (key == null) { throw new NullPointerException(); } return lookup.get(key); } /** {@collect.stats} * {@description.open} * Returns an <code>Enumeration</code> of the keys contained in * this <code>ResourceBundle</code> and its parent bundles. * {@description.close} * * @return an <code>Enumeration</code> of the keys contained in * this <code>ResourceBundle</code> and its parent bundles. * @see #keySet() */ public Enumeration<String> getKeys() { ResourceBundle parent = this.parent; return new ResourceBundleEnumeration(lookup.keySet(), (parent != null) ? parent.getKeys() : null); } /** {@collect.stats} * {@description.open} * Returns a <code>Set</code> of the keys contained * <em>only</em> in this <code>ResourceBundle</code>. * {@description.close} * * @return a <code>Set</code> of the keys contained only in this * <code>ResourceBundle</code> * @since 1.6 * @see #keySet() */ protected Set<String> handleKeySet() { return lookup.keySet(); } // ==================privates==================== private Map<String,Object> lookup; }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * An object that maps keys to values. A map cannot contain duplicate keys; * each key can map to at most one value. * * <p>This interface takes the place of the <tt>Dictionary</tt> class, which * was a totally abstract class rather than an interface. * * <p>The <tt>Map</tt> interface provides three <i>collection views</i>, which * allow a map's contents to be viewed as a set of keys, collection of values, * or set of key-value mappings. The <i>order</i> of a map is defined as * the order in which the iterators on the map's collection views return their * elements. Some map implementations, like the <tt>TreeMap</tt> class, make * specific guarantees as to their order; others, like the <tt>HashMap</tt> * class, do not. * {@description.close} * * {@property.open formal:java.util.Map_ItselfAsKey} * <p>Note: great care must be exercised if mutable objects are used as map * keys. The behavior of a map is not specified if the value of an object is * changed in a manner that affects <tt>equals</tt> comparisons while the * object is a key in the map. A special case of this prohibition is that it * is not permissible for a map to contain itself as a key. * {@property.close} * {@property.open formal:java.util.Map_ItselfAsValue} * While it is * permissible for a map to contain itself as a value, extreme caution is * advised: the <tt>equals</tt> and <tt>hashCode</tt> methods are no longer * well defined on such a map. * {@property.close} * * {@property.open formal:java.util.Map_StandardConstructors} * <p>All general-purpose map implementation classes should provide two * "standard" constructors: a void (no arguments) constructor which creates an * empty map, and a constructor with a single argument of type <tt>Map</tt>, * which creates a new map with the same key-value mappings as its argument. * In effect, the latter constructor allows the user to copy any map, * producing an equivalent map of the desired class. There is no way to * enforce this recommendation (as interfaces cannot contain constructors) but * all of the general-purpose map implementations in the JDK comply. * {@property.close} * * {@description.open} * <p>The "destructive" methods contained in this interface, that is, the * methods that modify the map on which they operate, are specified to throw * <tt>UnsupportedOperationException</tt> if this map does not support the * operation. If this is the case, these methods may, but are not required * to, throw an <tt>UnsupportedOperationException</tt> if the invocation would * have no effect on the map. For example, invoking the {@link #putAll(Map)} * method on an unmodifiable map may, but is not required to, throw the * exception if the map whose mappings are to be "superimposed" is empty. * * <p>Some map implementations have restrictions on the keys and values they * may contain. For example, some implementations prohibit null keys and * values, and some have restrictions on the types of their keys. Attempting * to insert an ineligible key or value throws an unchecked exception, * typically <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. * Attempting to query the presence of an ineligible key or value may throw an * exception, or it may simply return false; some implementations will exhibit * the former behavior and some will exhibit the latter. More generally, * attempting an operation on an ineligible key or value whose completion * would not result in the insertion of an ineligible element into the map may * throw an exception or it may succeed, at the option of the implementation. * Such exceptions are marked as "optional" in the specification for this * interface. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * <p>Many methods in Collections Framework interfaces are defined * in terms of the {@link Object#equals(Object) equals} method. For * example, the specification for the {@link #containsKey(Object) * containsKey(Object key)} method says: "returns <tt>true</tt> if and * only if this map contains a mapping for a key <tt>k</tt> such that * <tt>(key==null ? k==null : key.equals(k))</tt>." This specification should * <i>not</i> be construed to imply that invoking <tt>Map.containsKey</tt> * with a non-null argument <tt>key</tt> will cause <tt>key.equals(k)</tt> to * be invoked for any key <tt>k</tt>. Implementations are free to * implement optimizations whereby the <tt>equals</tt> invocation is avoided, * for example, by first comparing the hash codes of the two keys. (The * {@link Object#hashCode()} specification guarantees that two objects with * unequal hash codes cannot be equal.) More generally, implementations of * the various Collections Framework interfaces are free to take advantage of * the specified behavior of underlying {@link Object} methods wherever the * implementor deems it appropriate. * {@description.close} * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Josh Bloch * @see HashMap * @see TreeMap * @see Hashtable * @see SortedMap * @see Collection * @see Set * @since 1.2 */ public interface Map<K,V> { // Query Operations /** {@collect.stats} * {@description.open} * Returns the number of key-value mappings in this map. If the * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns * <tt>Integer.MAX_VALUE</tt>. * {@description.close} * * @return the number of key-value mappings in this map */ int size(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map contains no key-value mappings. * {@description.close} * * @return <tt>true</tt> if this map contains no key-value mappings */ boolean isEmpty(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map contains a mapping for the specified * key. More formally, returns <tt>true</tt> if and only if * this map contains a mapping for a key <tt>k</tt> such that * <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be * at most one such mapping.) * {@description.close} * * @param key key whose presence in this map is to be tested * @return <tt>true</tt> if this map contains a mapping for the specified * key * @throws ClassCastException if the key is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified key is null and this map * does not permit null keys (optional) */ boolean containsKey(Object key); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map maps one or more keys to the * specified value. More formally, returns <tt>true</tt> if and only if * this map contains at least one mapping to a value <tt>v</tt> such that * <tt>(value==null ? v==null : value.equals(v))</tt>. This operation * will probably require time linear in the map size for most * implementations of the <tt>Map</tt> interface. * {@description.close} * * @param value value whose presence in this map is to be tested * @return <tt>true</tt> if this map maps one or more keys to the * specified value * @throws ClassCastException if the value is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified value is null and this * map does not permit null values (optional) */ boolean containsValue(Object value); /** {@collect.stats} * {@description.open} * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * * <p>If this map permits null values, then a return value of * {@code null} does not <i>necessarily</i> indicate that the map * contains no mapping for the key; it's also possible that the map * explicitly maps the key to {@code null}. The {@link #containsKey * containsKey} operation may be used to distinguish these two cases. * {@description.close} * * @param key the key whose associated value is to be returned * @return the value to which the specified key is mapped, or * {@code null} if this map contains no mapping for the key * @throws ClassCastException if the key is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified key is null and this map * does not permit null keys (optional) */ V get(Object key); // Modification Operations /** {@collect.stats} * {@description.open} * Associates the specified value with the specified key in this map * (optional operation). If the map previously contained a mapping for * the key, the old value is replaced by the specified value. (A map * <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only * if {@link #containsKey(Object) m.containsKey(k)} would return * <tt>true</tt>.) * {@description.close} * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>, * if the implementation supports <tt>null</tt> values.) * @throws UnsupportedOperationException if the <tt>put</tt> operation * is not supported by this map * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map * @throws NullPointerException if the specified key or value is null * and this map does not permit null keys or values * @throws IllegalArgumentException if some property of the specified key * or value prevents it from being stored in this map */ V put(K key, V value); /** {@collect.stats} * {@description.open} * Removes the mapping for a key from this map if it is present * (optional operation). More formally, if this map contains a mapping * from key <tt>k</tt> to value <tt>v</tt> such that * <code>(key==null ? k==null : key.equals(k))</code>, that mapping * is removed. (The map can contain at most one such mapping.) * * <p>Returns the value to which this map previously associated the key, * or <tt>null</tt> if the map contained no mapping for the key. * * <p>If this map permits null values, then a return value of * <tt>null</tt> does not <i>necessarily</i> indicate that the map * contained no mapping for the key; it's also possible that the map * explicitly mapped the key to <tt>null</tt>. * * <p>The map will not contain a mapping for the specified key once the * call returns. * {@description.close} * * @param key key whose mapping is to be removed from the map * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * @throws UnsupportedOperationException if the <tt>remove</tt> operation * is not supported by this map * @throws ClassCastException if the key is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified key is null and this * map does not permit null keys (optional) */ V remove(Object key); // Bulk Operations /** {@collect.stats} * {@description.open} * Copies all of the mappings from the specified map to this map * (optional operation). The effect of this call is equivalent to that * of calling {@link #put(Object,Object) put(k, v)} on this map once * for each mapping from key <tt>k</tt> to value <tt>v</tt> in the * specified map. * {@description.close} * {@property.open formal:java.util.Map_UnsynchronizedAddAll} * The behavior of this operation is undefined if the * specified map is modified while the operation is in progress. * {@property.close} * * @param m mappings to be stored in this map * @throws UnsupportedOperationException if the <tt>putAll</tt> operation * is not supported by this map * @throws ClassCastException if the class of a key or value in the * specified map prevents it from being stored in this map * @throws NullPointerException if the specified map is null, or if * this map does not permit null keys or values, and the * specified map contains null keys or values * @throws IllegalArgumentException if some property of a key or value in * the specified map prevents it from being stored in this map */ void putAll(Map<? extends K, ? extends V> m); /** {@collect.stats} * {@description.open} * Removes all of the mappings from this map (optional operation). * The map will be empty after this call returns. * {@description.close} * * @throws UnsupportedOperationException if the <tt>clear</tt> operation * is not supported by this map */ void clear(); // Views /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the keys contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. * {@property.close} * * @return a set view of the keys contained in this map */ Set<K> keySet(); /** {@collect.stats} * {@description.open} * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is * modified while an iteration over the collection is in progress * (except through the iterator's own <tt>remove</tt> operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Collection.remove</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not * support the <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} * * @return a collection view of the values contained in this map */ Collection<V> values(); /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the mappings contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation, or through the * <tt>setValue</tt> operation on a map entry returned by the * iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and * <tt>clear</tt> operations. It does not support the * <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} * * @return a set view of the mappings contained in this map */ Set<Map.Entry<K, V>> entrySet(); /** {@collect.stats} * {@description.open} * A map entry (key-value pair). The <tt>Map.entrySet</tt> method returns * a collection-view of the map, whose elements are of this class. The * <i>only</i> way to obtain a reference to a map entry is from the * iterator of this collection-view. These <tt>Map.Entry</tt> objects are * valid <i>only</i> for the duration of the iteration; more formally, * the behavior of a map entry is undefined if the backing map has been * modified after the entry was returned by the iterator, except through * the <tt>setValue</tt> operation on the map entry. * {@description.close} * * @see Map#entrySet() * @since 1.2 */ interface Entry<K,V> { /** {@collect.stats} * {@description.open} * Returns the key corresponding to this entry. * {@description.close} * * @return the key corresponding to this entry * @throws IllegalStateException implementations may, but are not * required to, throw this exception if the entry has been * removed from the backing map. */ K getKey(); /** {@collect.stats} * {@description.open} * Returns the value corresponding to this entry. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator} * If the mapping * has been removed from the backing map (by the iterator's * <tt>remove</tt> operation), the results of this call are undefined. * {@property.close} * * @return the value corresponding to this entry * @throws IllegalStateException implementations may, but are not * required to, throw this exception if the entry has been * removed from the backing map. */ V getValue(); /** {@collect.stats} * {@description.open} * Replaces the value corresponding to this entry with the specified * value (optional operation). (Writes through to the map.) * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator} * The * behavior of this call is undefined if the mapping has already been * removed from the map (by the iterator's <tt>remove</tt> operation). * {@property.close} * * @param value new value to be stored in this entry * @return old value corresponding to the entry * @throws UnsupportedOperationException if the <tt>put</tt> operation * is not supported by the backing map * @throws ClassCastException if the class of the specified value * prevents it from being stored in the backing map * @throws NullPointerException if the backing map does not permit * null values, and the specified value is null * @throws IllegalArgumentException if some property of this value * prevents it from being stored in the backing map * @throws IllegalStateException implementations may, but are not * required to, throw this exception if the entry has been * removed from the backing map. */ V setValue(V value); /** {@collect.stats} * {@description.open} * Compares the specified object with this entry for equality. * Returns <tt>true</tt> if the given object is also a map entry and * the two entries represent the same mapping. More formally, two * entries <tt>e1</tt> and <tt>e2</tt> represent the same mapping * if<pre> * (e1.getKey()==null ? * e2.getKey()==null : e1.getKey().equals(e2.getKey())) &amp;&amp; * (e1.getValue()==null ? * e2.getValue()==null : e1.getValue().equals(e2.getValue())) * </pre> * This ensures that the <tt>equals</tt> method works properly across * different implementations of the <tt>Map.Entry</tt> interface. * {@description.close} * * @param o object to be compared for equality with this map entry * @return <tt>true</tt> if the specified object is equal to this map * entry */ boolean equals(Object o); /** {@collect.stats} * {@description.open} * Returns the hash code value for this map entry. The hash code * of a map entry <tt>e</tt> is defined to be: <pre> * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ * (e.getValue()==null ? 0 : e.getValue().hashCode()) * </pre> * This ensures that <tt>e1.equals(e2)</tt> implies that * <tt>e1.hashCode()==e2.hashCode()</tt> for any two Entries * <tt>e1</tt> and <tt>e2</tt>, as required by the general * contract of <tt>Object.hashCode</tt>. * {@description.close} * * @return the hash code value for this map entry * @see Object#hashCode() * @see Object#equals(Object) * @see #equals(Object) */ int hashCode(); } // Comparison and hashing /** {@collect.stats} * {@description.open} * Compares the specified object with this map for equality. Returns * <tt>true</tt> if the given object is also a map and the two maps * represent the same mappings. More formally, two maps <tt>m1</tt> and * <tt>m2</tt> represent the same mappings if * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the * <tt>equals</tt> method works properly across different implementations * of the <tt>Map</tt> interface. * {@description.close} * * @param o object to be compared for equality with this map * @return <tt>true</tt> if the specified object is equal to this map */ boolean equals(Object o); /** {@collect.stats} * {@description.open} * Returns the hash code value for this map. The hash code of a map is * defined to be the sum of the hash codes of each entry in the map's * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt> * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of * {@link Object#hashCode}. * {@description.close} * * @return the hash code value for this map * @see Map.Entry#hashCode() * @see Object#equals(Object) * @see #equals(Object) */ int hashCode(); }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when there is a format specifier which does not * have a corresponding argument or if an argument index refers to an argument * that does not exist. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any * method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @since 1.5 */ public class MissingFormatArgumentException extends IllegalFormatException { private static final long serialVersionUID = 19190115L; private String s; /** {@collect.stats} * {@description.open} * Constructs an instance of this class with the unmatched format * specifier. * {@description.close} * * @param s * Format specifier which does not have a corresponding argument */ public MissingFormatArgumentException(String s) { if (s == null) throw new NullPointerException(); this.s = s; } /** {@collect.stats} * {@description.open} * Returns the unmatched format specifier. * {@description.close} * * @return The unmatched format specifier */ public String getFormatSpecifier() { return s; } public String getMessage() { return "Format specifier '" + s + "'"; } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * An iterator over a collection. {@code Iterator} takes the place of * {@link Enumeration} in the Java Collections Framework. Iterators * differ from enumerations in two ways: * * <ul> * <li> Iterators allow the caller to remove elements from the * underlying collection during the iteration with well-defined * semantics. * <li> Method names have been improved. * </ul> * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @see Collection * @see ListIterator * @see Iterable * @since 1.2 */ public interface Iterator<E> { /** {@collect.stats} * {@description.open} * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * {@description.close} * * @return {@code true} if the iteration has more elements */ boolean hasNext(); /** {@collect.stats} * {@description.open} * Returns the next element in the iteration. * {@description.close} * {@property.open formal:java.util.Iterator_HasNext} * {@new.open} * In general, it is recommended to call hasNext() and check the return * value before calling this method. * {@new.close} * {@property.close} * * @return the next element in the iteration * @throws NoSuchElementException if the iteration has no more elements */ E next(); /** {@collect.stats} * {@description.open} * Removes from the underlying collection the last element returned * by this iterator (optional operation). * {@description.close} * {@property.open formal:java.util.Iterator_RemoveOnce} * This method can be called * only once per call to {@link #next}. * {@new.open} * If the {@link #next} method has not yet been called, this method cannot be called. * {@new.close} * {@property.close} * {@property.open formal:java.util.Collection_UnsafeIterator formal:java.util.Map_UnsafeIterator} * The behavior of an iterator * is unspecified if the underlying collection is modified while the * iteration is in progress in any way other than by calling this * method. * {@property.close} * * @throws UnsupportedOperationException if the {@code remove} * operation is not supported by this iterator * * @throws IllegalStateException if the {@code next} method has not * yet been called, or the {@code remove} method has already * been called after the last call to the {@code next} * method */ void remove(); }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved * * The original version of this source code and documentation is copyrighted * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These * materials are provided under terms of a License Agreement between Taligent * and Sun. This technology is protected by multiple US and International * patents. This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.util; import java.io.IOException; import java.io.ObjectInputStream; import sun.util.calendar.BaseCalendar; import sun.util.calendar.CalendarDate; import sun.util.calendar.CalendarSystem; import sun.util.calendar.CalendarUtils; import sun.util.calendar.Era; import sun.util.calendar.Gregorian; import sun.util.calendar.JulianCalendar; import sun.util.calendar.ZoneInfo; /** {@collect.stats} * {@description.open} * <code>GregorianCalendar</code> is a concrete subclass of * <code>Calendar</code> and provides the standard calendar system * used by most of the world. * * <p> <code>GregorianCalendar</code> is a hybrid calendar that * supports both the Julian and Gregorian calendar systems with the * support of a single discontinuity, which corresponds by default to * the Gregorian date when the Gregorian calendar was instituted * (October 15, 1582 in some countries, later in others). The cutover * date may be changed by the caller by calling {@link * #setGregorianChange(Date) setGregorianChange()}. * * <p> * Historically, in those countries which adopted the Gregorian calendar first, * October 4, 1582 (Julian) was thus followed by October 15, 1582 (Gregorian). This calendar models * this correctly. Before the Gregorian cutover, <code>GregorianCalendar</code> * implements the Julian calendar. The only difference between the Gregorian * and the Julian calendar is the leap year rule. The Julian calendar specifies * leap years every four years, whereas the Gregorian calendar omits century * years which are not divisible by 400. * * <p> * <code>GregorianCalendar</code> implements <em>proleptic</em> Gregorian and * Julian calendars. That is, dates are computed by extrapolating the current * rules indefinitely far backward and forward in time. As a result, * <code>GregorianCalendar</code> may be used for all years to generate * meaningful and consistent results. However, dates obtained using * <code>GregorianCalendar</code> are historically accurate only from March 1, 4 * AD onward, when modern Julian calendar rules were adopted. Before this date, * leap year rules were applied irregularly, and before 45 BC the Julian * calendar did not even exist. * * <p> * Prior to the institution of the Gregorian calendar, New Year's Day was * March 25. To avoid confusion, this calendar always uses January 1. A manual * adjustment may be made if desired for dates that are prior to the Gregorian * changeover and which fall between January 1 and March 24. * * <p>Values calculated for the <code>WEEK_OF_YEAR</code> field range from 1 to * 53. Week 1 for a year is the earliest seven day period starting on * <code>getFirstDayOfWeek()</code> that contains at least * <code>getMinimalDaysInFirstWeek()</code> days from that year. It thus * depends on the values of <code>getMinimalDaysInFirstWeek()</code>, * <code>getFirstDayOfWeek()</code>, and the day of the week of January 1. * Weeks between week 1 of one year and week 1 of the following year are * numbered sequentially from 2 to 52 or 53 (as needed). * <p>For example, January 1, 1998 was a Thursday. If * <code>getFirstDayOfWeek()</code> is <code>MONDAY</code> and * <code>getMinimalDaysInFirstWeek()</code> is 4 (these are the values * reflecting ISO 8601 and many national standards), then week 1 of 1998 starts * on December 29, 1997, and ends on January 4, 1998. If, however, * <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>, then week 1 of 1998 * starts on January 4, 1998, and ends on January 10, 1998; the first three days * of 1998 then are part of week 53 of 1997. * * <p>Values calculated for the <code>WEEK_OF_MONTH</code> field range from 0 * to 6. Week 1 of a month (the days with <code>WEEK_OF_MONTH = * 1</code>) is the earliest set of at least * <code>getMinimalDaysInFirstWeek()</code> contiguous days in that month, * ending on the day before <code>getFirstDayOfWeek()</code>. Unlike * week 1 of a year, week 1 of a month may be shorter than 7 days, need * not start on <code>getFirstDayOfWeek()</code>, and will not include days of * the previous month. Days of a month before week 1 have a * <code>WEEK_OF_MONTH</code> of 0. * * <p>For example, if <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code> * and <code>getMinimalDaysInFirstWeek()</code> is 4, then the first week of * January 1998 is Sunday, January 4 through Saturday, January 10. These days * have a <code>WEEK_OF_MONTH</code> of 1. Thursday, January 1 through * Saturday, January 3 have a <code>WEEK_OF_MONTH</code> of 0. If * <code>getMinimalDaysInFirstWeek()</code> is changed to 3, then January 1 * through January 3 have a <code>WEEK_OF_MONTH</code> of 1. * * <p>The <code>clear</code> methods set calendar field(s) * undefined. <code>GregorianCalendar</code> uses the following * default value for each calendar field if its value is undefined. * * <table cellpadding="0" cellspacing="3" border="0" * summary="GregorianCalendar default field values" * style="text-align: left; width: 66%;"> * <tbody> * <tr> * <th style="vertical-align: top; background-color: rgb(204, 204, 255); * text-align: center;">Field<br> * </th> * <th style="vertical-align: top; background-color: rgb(204, 204, 255); * text-align: center;">Default Value<br> * </th> * </tr> * <tr> * <td style="vertical-align: middle;"> * <code>ERA<br></code> * </td> * <td style="vertical-align: middle;"> * <code>AD<br></code> * </td> * </tr> * <tr> * <td style="vertical-align: middle; background-color: rgb(238, 238, 255);"> * <code>YEAR<br></code> * </td> * <td style="vertical-align: middle; background-color: rgb(238, 238, 255);"> * <code>1970<br></code> * </td> * </tr> * <tr> * <td style="vertical-align: middle;"> * <code>MONTH<br></code> * </td> * <td style="vertical-align: middle;"> * <code>JANUARY<br></code> * </td> * </tr> * <tr> * <td style="vertical-align: top; background-color: rgb(238, 238, 255);"> * <code>DAY_OF_MONTH<br></code> * </td> * <td style="vertical-align: top; background-color: rgb(238, 238, 255);"> * <code>1<br></code> * </td> * </tr> * <tr> * <td style="vertical-align: middle;"> * <code>DAY_OF_WEEK<br></code> * </td> * <td style="vertical-align: middle;"> * <code>the first day of week<br></code> * </td> * </tr> * <tr> * <td style="vertical-align: top; background-color: rgb(238, 238, 255);"> * <code>WEEK_OF_MONTH<br></code> * </td> * <td style="vertical-align: top; background-color: rgb(238, 238, 255);"> * <code>0<br></code> * </td> * </tr> * <tr> * <td style="vertical-align: top;"> * <code>DAY_OF_WEEK_IN_MONTH<br></code> * </td> * <td style="vertical-align: top;"> * <code>1<br></code> * </td> * </tr> * <tr> * <td style="vertical-align: middle; background-color: rgb(238, 238, 255);"> * <code>AM_PM<br></code> * </td> * <td style="vertical-align: middle; background-color: rgb(238, 238, 255);"> * <code>AM<br></code> * </td> * </tr> * <tr> * <td style="vertical-align: middle;"> * <code>HOUR, HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND<br></code> * </td> * <td style="vertical-align: middle;"> * <code>0<br></code> * </td> * </tr> * </tbody> * </table> * <br>Default values are not applicable for the fields not listed above. * * <p> * <strong>Example:</strong> * <blockquote> * <pre> * // get the supported ids for GMT-08:00 (Pacific Standard Time) * String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000); * // if no ids were returned, something is wrong. get out. * if (ids.length == 0) * System.exit(0); * * // begin output * System.out.println("Current Time"); * * // create a Pacific Standard Time time zone * SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]); * * // set up rules for daylight savings time * pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); * pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); * * // create a GregorianCalendar with the Pacific Daylight time zone * // and the current date and time * Calendar calendar = new GregorianCalendar(pdt); * Date trialTime = new Date(); * calendar.setTime(trialTime); * * // print out a bunch of interesting things * System.out.println("ERA: " + calendar.get(Calendar.ERA)); * System.out.println("YEAR: " + calendar.get(Calendar.YEAR)); * System.out.println("MONTH: " + calendar.get(Calendar.MONTH)); * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR)); * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH)); * System.out.println("DATE: " + calendar.get(Calendar.DATE)); * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH)); * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR)); * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK)); * System.out.println("DAY_OF_WEEK_IN_MONTH: " * + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM)); * System.out.println("HOUR: " + calendar.get(Calendar.HOUR)); * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY)); * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE)); * System.out.println("SECOND: " + calendar.get(Calendar.SECOND)); * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND)); * System.out.println("ZONE_OFFSET: " * + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); * System.out.println("DST_OFFSET: " * + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); * System.out.println("Current Time, with hour reset to 3"); * calendar.clear(Calendar.HOUR_OF_DAY); // so doesn't override * calendar.set(Calendar.HOUR, 3); * System.out.println("ERA: " + calendar.get(Calendar.ERA)); * System.out.println("YEAR: " + calendar.get(Calendar.YEAR)); * System.out.println("MONTH: " + calendar.get(Calendar.MONTH)); * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR)); * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH)); * System.out.println("DATE: " + calendar.get(Calendar.DATE)); * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH)); * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR)); * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK)); * System.out.println("DAY_OF_WEEK_IN_MONTH: " * + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM)); * System.out.println("HOUR: " + calendar.get(Calendar.HOUR)); * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY)); * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE)); * System.out.println("SECOND: " + calendar.get(Calendar.SECOND)); * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND)); * System.out.println("ZONE_OFFSET: " * + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); // in hours * System.out.println("DST_OFFSET: " * + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); // in hours * </pre> * </blockquote> * {@description.close} * * @see TimeZone * @author David Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu * @since JDK1.1 */ public class GregorianCalendar extends Calendar { /* * Implementation Notes * * The epoch is the number of days or milliseconds from some defined * starting point. The epoch for java.util.Date is used here; that is, * milliseconds from January 1, 1970 (Gregorian), midnight UTC. Other * epochs which are used are January 1, year 1 (Gregorian), which is day 1 * of the Gregorian calendar, and December 30, year 0 (Gregorian), which is * day 1 of the Julian calendar. * * We implement the proleptic Julian and Gregorian calendars. This means we * implement the modern definition of the calendar even though the * historical usage differs. For example, if the Gregorian change is set * to new Date(Long.MIN_VALUE), we have a pure Gregorian calendar which * labels dates preceding the invention of the Gregorian calendar in 1582 as * if the calendar existed then. * * Likewise, with the Julian calendar, we assume a consistent * 4-year leap year rule, even though the historical pattern of * leap years is irregular, being every 3 years from 45 BCE * through 9 BCE, then every 4 years from 8 CE onwards, with no * leap years in-between. Thus date computations and functions * such as isLeapYear() are not intended to be historically * accurate. */ ////////////////// // Class Variables ////////////////// /** {@collect.stats} * {@description.open} * Value of the <code>ERA</code> field indicating * the period before the common era (before Christ), also known as BCE. * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is * ..., 2 BC, 1 BC, 1 AD, 2 AD,... * {@description.close} * * @see #ERA */ public static final int BC = 0; /** {@collect.stats} * {@description.open} * Value of the {@link #ERA} field indicating * the period before the common era, the same value as {@link #BC}. * {@description.close} * * @see #CE */ static final int BCE = 0; /** {@collect.stats} * {@description.open} * Value of the <code>ERA</code> field indicating * the common era (Anno Domini), also known as CE. * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is * ..., 2 BC, 1 BC, 1 AD, 2 AD,... * {@description.close} * * @see #ERA */ public static final int AD = 1; /** {@collect.stats} * {@description.open} * Value of the {@link #ERA} field indicating * the common era, the same value as {@link #AD}. * {@description.close} * * @see #BCE */ static final int CE = 1; private static final int EPOCH_OFFSET = 719163; // Fixed date of January 1, 1970 (Gregorian) private static final int EPOCH_YEAR = 1970; static final int MONTH_LENGTH[] = {31,28,31,30,31,30,31,31,30,31,30,31}; // 0-based static final int LEAP_MONTH_LENGTH[] = {31,29,31,30,31,30,31,31,30,31,30,31}; // 0-based // Useful millisecond constants. Although ONE_DAY and ONE_WEEK can fit // into ints, they must be longs in order to prevent arithmetic overflow // when performing (bug 4173516). private static final int ONE_SECOND = 1000; private static final int ONE_MINUTE = 60*ONE_SECOND; private static final int ONE_HOUR = 60*ONE_MINUTE; private static final long ONE_DAY = 24*ONE_HOUR; private static final long ONE_WEEK = 7*ONE_DAY; /* * <pre> * Greatest Least * Field name Minimum Minimum Maximum Maximum * ---------- ------- ------- ------- ------- * ERA 0 0 1 1 * YEAR 1 1 292269054 292278994 * MONTH 0 0 11 11 * WEEK_OF_YEAR 1 1 52* 53 * WEEK_OF_MONTH 0 0 4* 6 * DAY_OF_MONTH 1 1 28* 31 * DAY_OF_YEAR 1 1 365* 366 * DAY_OF_WEEK 1 1 7 7 * DAY_OF_WEEK_IN_MONTH -1 -1 4* 6 * AM_PM 0 0 1 1 * HOUR 0 0 11 11 * HOUR_OF_DAY 0 0 23 23 * MINUTE 0 0 59 59 * SECOND 0 0 59 59 * MILLISECOND 0 0 999 999 * ZONE_OFFSET -13:00 -13:00 14:00 14:00 * DST_OFFSET 0:00 0:00 0:20 2:00 * </pre> * *: depends on the Gregorian change date */ static final int MIN_VALUES[] = { BCE, // ERA 1, // YEAR JANUARY, // MONTH 1, // WEEK_OF_YEAR 0, // WEEK_OF_MONTH 1, // DAY_OF_MONTH 1, // DAY_OF_YEAR SUNDAY, // DAY_OF_WEEK 1, // DAY_OF_WEEK_IN_MONTH AM, // AM_PM 0, // HOUR 0, // HOUR_OF_DAY 0, // MINUTE 0, // SECOND 0, // MILLISECOND -13*ONE_HOUR, // ZONE_OFFSET (UNIX compatibility) 0 // DST_OFFSET }; static final int LEAST_MAX_VALUES[] = { CE, // ERA 292269054, // YEAR DECEMBER, // MONTH 52, // WEEK_OF_YEAR 4, // WEEK_OF_MONTH 28, // DAY_OF_MONTH 365, // DAY_OF_YEAR SATURDAY, // DAY_OF_WEEK 4, // DAY_OF_WEEK_IN PM, // AM_PM 11, // HOUR 23, // HOUR_OF_DAY 59, // MINUTE 59, // SECOND 999, // MILLISECOND 14*ONE_HOUR, // ZONE_OFFSET 20*ONE_MINUTE // DST_OFFSET (historical least maximum) }; static final int MAX_VALUES[] = { CE, // ERA 292278994, // YEAR DECEMBER, // MONTH 53, // WEEK_OF_YEAR 6, // WEEK_OF_MONTH 31, // DAY_OF_MONTH 366, // DAY_OF_YEAR SATURDAY, // DAY_OF_WEEK 6, // DAY_OF_WEEK_IN PM, // AM_PM 11, // HOUR 23, // HOUR_OF_DAY 59, // MINUTE 59, // SECOND 999, // MILLISECOND 14*ONE_HOUR, // ZONE_OFFSET 2*ONE_HOUR // DST_OFFSET (double summer time) }; // Proclaim serialization compatibility with JDK 1.1 static final long serialVersionUID = -8125100834729963327L; // Reference to the sun.util.calendar.Gregorian instance (singleton). private static final Gregorian gcal = CalendarSystem.getGregorianCalendar(); // Reference to the JulianCalendar instance (singleton), set as needed. See // getJulianCalendarSystem(). private static JulianCalendar jcal; // JulianCalendar eras. See getJulianCalendarSystem(). private static Era[] jeras; // The default value of gregorianCutover. static final long DEFAULT_GREGORIAN_CUTOVER = -12219292800000L; ///////////////////// // Instance Variables ///////////////////// /** {@collect.stats} * {@description.open} * The point at which the Gregorian calendar rules are used, measured in * milliseconds from the standard epoch. Default is October 15, 1582 * (Gregorian) 00:00:00 UTC or -12219292800000L. For this value, October 4, * 1582 (Julian) is followed by October 15, 1582 (Gregorian). This * corresponds to Julian day number 2299161. * {@description.close} * @serial */ private long gregorianCutover = DEFAULT_GREGORIAN_CUTOVER; /** {@collect.stats} * {@description.open} * The fixed date of the gregorianCutover. * {@description.close} */ private transient long gregorianCutoverDate = (((DEFAULT_GREGORIAN_CUTOVER + 1)/ONE_DAY) - 1) + EPOCH_OFFSET; // == 577736 /** {@collect.stats} * {@description.open} * The normalized year of the gregorianCutover in Gregorian, with * 0 representing 1 BCE, -1 representing 2 BCE, etc. * {@description.close} */ private transient int gregorianCutoverYear = 1582; /** {@collect.stats} * {@description.open} * The normalized year of the gregorianCutover in Julian, with 0 * representing 1 BCE, -1 representing 2 BCE, etc. * {@description.close} */ private transient int gregorianCutoverYearJulian = 1582; /** {@collect.stats} * {@description.open} * gdate always has a sun.util.calendar.Gregorian.Date instance to * avoid overhead of creating it. The assumption is that most * applications will need only Gregorian calendar calculations. * {@description.close} */ private transient BaseCalendar.Date gdate; /** {@collect.stats} * {@description.open} * Reference to either gdate or a JulianCalendar.Date * instance. After calling complete(), this value is guaranteed to * be set. * {@description.close} */ private transient BaseCalendar.Date cdate; /** {@collect.stats} * {@description.open} * The CalendarSystem used to calculate the date in cdate. After * calling complete(), this value is guaranteed to be set and * consistent with the cdate value. * {@description.close} */ private transient BaseCalendar calsys; /** {@collect.stats} * {@description.open} * Temporary int[2] to get time zone offsets. zoneOffsets[0] gets * the GMT offset value and zoneOffsets[1] gets the DST saving * value. * {@description.close} */ private transient int[] zoneOffsets; /** {@collect.stats} * {@description.open} * Temporary storage for saving original fields[] values in * non-lenient mode. * {@description.close} */ private transient int[] originalFields; /////////////// // Constructors /////////////// /** {@collect.stats} * {@description.open} * Constructs a default <code>GregorianCalendar</code> using the current time * in the default time zone with the default locale. * {@description.close} */ public GregorianCalendar() { this(TimeZone.getDefaultRef(), Locale.getDefault()); setZoneShared(true); } /** {@collect.stats} * {@description.open} * Constructs a <code>GregorianCalendar</code> based on the current time * in the given time zone with the default locale. * {@description.close} * * @param zone the given time zone. */ public GregorianCalendar(TimeZone zone) { this(zone, Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Constructs a <code>GregorianCalendar</code> based on the current time * in the default time zone with the given locale. * {@description.close} * * @param aLocale the given locale. */ public GregorianCalendar(Locale aLocale) { this(TimeZone.getDefaultRef(), aLocale); setZoneShared(true); } /** {@collect.stats} * {@description.open} * Constructs a <code>GregorianCalendar</code> based on the current time * in the given time zone with the given locale. * {@description.close} * * @param zone the given time zone. * @param aLocale the given locale. */ public GregorianCalendar(TimeZone zone, Locale aLocale) { super(zone, aLocale); gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone); setTimeInMillis(System.currentTimeMillis()); } /** {@collect.stats} * {@description.open} * Constructs a <code>GregorianCalendar</code> with the given date set * in the default time zone with the default locale. * {@description.close} * * @param year the value used to set the <code>YEAR</code> calendar field in the calendar. * @param month the value used to set the <code>MONTH</code> calendar field in the calendar. * Month value is 0-based. e.g., 0 for January. * @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar. */ public GregorianCalendar(int year, int month, int dayOfMonth) { this(year, month, dayOfMonth, 0, 0, 0, 0); } /** {@collect.stats} * {@description.open} * Constructs a <code>GregorianCalendar</code> with the given date * and time set for the default time zone with the default locale. * {@description.close} * * @param year the value used to set the <code>YEAR</code> calendar field in the calendar. * @param month the value used to set the <code>MONTH</code> calendar field in the calendar. * Month value is 0-based. e.g., 0 for January. * @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar. * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field * in the calendar. * @param minute the value used to set the <code>MINUTE</code> calendar field * in the calendar. */ public GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute) { this(year, month, dayOfMonth, hourOfDay, minute, 0, 0); } /** {@collect.stats} * {@description.open} * Constructs a GregorianCalendar with the given date * and time set for the default time zone with the default locale. * {@description.close} * * @param year the value used to set the <code>YEAR</code> calendar field in the calendar. * @param month the value used to set the <code>MONTH</code> calendar field in the calendar. * Month value is 0-based. e.g., 0 for January. * @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar. * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field * in the calendar. * @param minute the value used to set the <code>MINUTE</code> calendar field * in the calendar. * @param second the value used to set the <code>SECOND</code> calendar field * in the calendar. */ public GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second) { this(year, month, dayOfMonth, hourOfDay, minute, second, 0); } /** {@collect.stats} * {@description.open} * Constructs a <code>GregorianCalendar</code> with the given date * and time set for the default time zone with the default locale. * {@description.close} * * @param year the value used to set the <code>YEAR</code> calendar field in the calendar. * @param month the value used to set the <code>MONTH</code> calendar field in the calendar. * Month value is 0-based. e.g., 0 for January. * @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar. * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field * in the calendar. * @param minute the value used to set the <code>MINUTE</code> calendar field * in the calendar. * @param second the value used to set the <code>SECOND</code> calendar field * in the calendar. * @param millis the value used to set the <code>MILLISECOND</code> calendar field */ GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second, int millis) { super(); gdate = (BaseCalendar.Date) gcal.newCalendarDate(getZone()); this.set(YEAR, year); this.set(MONTH, month); this.set(DAY_OF_MONTH, dayOfMonth); // Set AM_PM and HOUR here to set their stamp values before // setting HOUR_OF_DAY (6178071). if (hourOfDay >= 12 && hourOfDay <= 23) { // If hourOfDay is a valid PM hour, set the correct PM values // so that it won't throw an exception in case it's set to // non-lenient later. this.internalSet(AM_PM, PM); this.internalSet(HOUR, hourOfDay - 12); } else { // The default value for AM_PM is AM. // We don't care any out of range value here for leniency. this.internalSet(HOUR, hourOfDay); } // The stamp values of AM_PM and HOUR must be COMPUTED. (6440854) setFieldsComputed(HOUR_MASK|AM_PM_MASK); this.set(HOUR_OF_DAY, hourOfDay); this.set(MINUTE, minute); this.set(SECOND, second); // should be changed to set() when this constructor is made // public. this.internalSet(MILLISECOND, millis); } ///////////////// // Public methods ///////////////// /** {@collect.stats} * {@description.open} * Sets the <code>GregorianCalendar</code> change date. This is the point when the switch * from Julian dates to Gregorian dates occurred. Default is October 15, * 1582 (Gregorian). Previous to this, dates will be in the Julian calendar. * <p> * To obtain a pure Julian calendar, set the change date to * <code>Date(Long.MAX_VALUE)</code>. To obtain a pure Gregorian calendar, * set the change date to <code>Date(Long.MIN_VALUE)</code>. * {@description.close} * * @param date the given Gregorian cutover date. */ public void setGregorianChange(Date date) { long cutoverTime = date.getTime(); if (cutoverTime == gregorianCutover) { return; } // Before changing the cutover date, make sure to have the // time of this calendar. complete(); setGregorianChange(cutoverTime); } private void setGregorianChange(long cutoverTime) { gregorianCutover = cutoverTime; gregorianCutoverDate = CalendarUtils.floorDivide(cutoverTime, ONE_DAY) + EPOCH_OFFSET; // To provide the "pure" Julian calendar as advertised. // Strictly speaking, the last millisecond should be a // Gregorian date. However, the API doc specifies that setting // the cutover date to Long.MAX_VALUE will make this calendar // a pure Julian calendar. (See 4167995) if (cutoverTime == Long.MAX_VALUE) { gregorianCutoverDate++; } BaseCalendar.Date d = getGregorianCutoverDate(); // Set the cutover year (in the Gregorian year numbering) gregorianCutoverYear = d.getYear(); BaseCalendar jcal = getJulianCalendarSystem(); d = (BaseCalendar.Date) jcal.newCalendarDate(TimeZone.NO_TIMEZONE); jcal.getCalendarDateFromFixedDate(d, gregorianCutoverDate - 1); gregorianCutoverYearJulian = d.getNormalizedYear(); if (time < gregorianCutover) { // The field values are no longer valid under the new // cutover date. setUnnormalized(); } } /** {@collect.stats} * {@description.open} * Gets the Gregorian Calendar change date. This is the point when the * switch from Julian dates to Gregorian dates occurred. Default is * October 15, 1582 (Gregorian). Previous to this, dates will be in the Julian * calendar. * {@description.close} * * @return the Gregorian cutover date for this <code>GregorianCalendar</code> object. */ public final Date getGregorianChange() { return new Date(gregorianCutover); } /** {@collect.stats} * {@description.open} * Determines if the given year is a leap year. Returns <code>true</code> if * the given year is a leap year. To specify BC year numbers, * <code>1 - year number</code> must be given. For example, year BC 4 is * specified as -3. * {@description.close} * * @param year the given year. * @return <code>true</code> if the given year is a leap year; <code>false</code> otherwise. */ public boolean isLeapYear(int year) { if ((year & 3) != 0) { return false; } if (year > gregorianCutoverYear) { return (year%100 != 0) || (year%400 == 0); // Gregorian } if (year < gregorianCutoverYearJulian) { return true; // Julian } boolean gregorian; // If the given year is the Gregorian cutover year, we need to // determine which calendar system to be applied to February in the year. if (gregorianCutoverYear == gregorianCutoverYearJulian) { BaseCalendar.Date d = getCalendarDate(gregorianCutoverDate); // Gregorian gregorian = d.getMonth() < BaseCalendar.MARCH; } else { gregorian = year == gregorianCutoverYear; } return gregorian ? (year%100 != 0) || (year%400 == 0) : true; } /** {@collect.stats} * {@description.open} * Compares this <code>GregorianCalendar</code> to the specified * <code>Object</code>. The result is <code>true</code> if and * only if the argument is a <code>GregorianCalendar</code> object * that represents the same time value (millisecond offset from * the <a href="Calendar.html#Epoch">Epoch</a>) under the same * <code>Calendar</code> parameters and Gregorian change date as * this object. * {@description.close} * * @param obj the object to compare with. * @return <code>true</code> if this object is equal to <code>obj</code>; * <code>false</code> otherwise. * @see Calendar#compareTo(Calendar) */ public boolean equals(Object obj) { return obj instanceof GregorianCalendar && super.equals(obj) && gregorianCutover == ((GregorianCalendar)obj).gregorianCutover; } /** {@collect.stats} * {@description.open} * Generates the hash code for this <code>GregorianCalendar</code> object. * {@description.close} */ public int hashCode() { return super.hashCode() ^ (int)gregorianCutoverDate; } /** {@collect.stats} * {@description.open} * Adds the specified (signed) amount of time to the given calendar field, * based on the calendar's rules. * * <p><em>Add rule 1</em>. The value of <code>field</code> * after the call minus the value of <code>field</code> before the * call is <code>amount</code>, modulo any overflow that has occurred in * <code>field</code>. Overflow occurs when a field value exceeds its * range and, as a result, the next larger field is incremented or * decremented and the field value is adjusted back into its range.</p> * * <p><em>Add rule 2</em>. If a smaller field is expected to be * invariant, but it is impossible for it to be equal to its * prior value because of changes in its minimum or maximum after * <code>field</code> is changed, then its value is adjusted to be as close * as possible to its expected value. A smaller field represents a * smaller unit of time. <code>HOUR</code> is a smaller field than * <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields * that are not expected to be invariant. The calendar system * determines what fields are expected to be invariant.</p> * {@description.close} * * @param field the calendar field. * @param amount the amount of date or time to be added to the field. * @exception IllegalArgumentException if <code>field</code> is * <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or unknown, * or if any calendar fields have out-of-range values in * non-lenient mode. */ public void add(int field, int amount) { // If amount == 0, do nothing even the given field is out of // range. This is tested by JCK. if (amount == 0) { return; // Do nothing! } if (field < 0 || field >= ZONE_OFFSET) { throw new IllegalArgumentException(); } // Sync the time and calendar fields. complete(); if (field == YEAR) { int year = internalGet(YEAR); if (internalGetEra() == CE) { year += amount; if (year > 0) { set(YEAR, year); } else { // year <= 0 set(YEAR, 1 - year); // if year == 0, you get 1 BCE. set(ERA, BCE); } } else { // era == BCE year -= amount; if (year > 0) { set(YEAR, year); } else { // year <= 0 set(YEAR, 1 - year); // if year == 0, you get 1 CE set(ERA, CE); } } pinDayOfMonth(); } else if (field == MONTH) { int month = internalGet(MONTH) + amount; int year = internalGet(YEAR); int y_amount; if (month >= 0) { y_amount = month/12; } else { y_amount = (month+1)/12 - 1; } if (y_amount != 0) { if (internalGetEra() == CE) { year += y_amount; if (year > 0) { set(YEAR, year); } else { // year <= 0 set(YEAR, 1 - year); // if year == 0, you get 1 BCE set(ERA, BCE); } } else { // era == BCE year -= y_amount; if (year > 0) { set(YEAR, year); } else { // year <= 0 set(YEAR, 1 - year); // if year == 0, you get 1 CE set(ERA, CE); } } } if (month >= 0) { set(MONTH, (int) (month % 12)); } else { // month < 0 month %= 12; if (month < 0) { month += 12; } set(MONTH, JANUARY + month); } pinDayOfMonth(); } else if (field == ERA) { int era = internalGet(ERA) + amount; if (era < 0) { era = 0; } if (era > 1) { era = 1; } set(ERA, era); } else { long delta = amount; long timeOfDay = 0; switch (field) { // Handle the time fields here. Convert the given // amount to milliseconds and call setTimeInMillis. case HOUR: case HOUR_OF_DAY: delta *= 60 * 60 * 1000; // hours to minutes break; case MINUTE: delta *= 60 * 1000; // minutes to seconds break; case SECOND: delta *= 1000; // seconds to milliseconds break; case MILLISECOND: break; // Handle week, day and AM_PM fields which involves // time zone offset change adjustment. Convert the // given amount to the number of days. case WEEK_OF_YEAR: case WEEK_OF_MONTH: case DAY_OF_WEEK_IN_MONTH: delta *= 7; break; case DAY_OF_MONTH: // synonym of DATE case DAY_OF_YEAR: case DAY_OF_WEEK: break; case AM_PM: // Convert the amount to the number of days (delta) // and +12 or -12 hours (timeOfDay). delta = amount / 2; timeOfDay = 12 * (amount % 2); break; } // The time fields don't require time zone offset change // adjustment. if (field >= HOUR) { setTimeInMillis(time + delta); return; } // The rest of the fields (week, day or AM_PM fields) // require time zone offset (both GMT and DST) change // adjustment. // Translate the current time to the fixed date and time // of the day. long fd = getCurrentFixedDate(); timeOfDay += internalGet(HOUR_OF_DAY); timeOfDay *= 60; timeOfDay += internalGet(MINUTE); timeOfDay *= 60; timeOfDay += internalGet(SECOND); timeOfDay *= 1000; timeOfDay += internalGet(MILLISECOND); if (timeOfDay >= ONE_DAY) { fd++; timeOfDay -= ONE_DAY; } else if (timeOfDay < 0) { fd--; timeOfDay += ONE_DAY; } fd += delta; // fd is the expected fixed date after the calculation int zoneOffset = internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET); setTimeInMillis((fd - EPOCH_OFFSET) * ONE_DAY + timeOfDay - zoneOffset); zoneOffset -= internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET); // If the time zone offset has changed, then adjust the difference. if (zoneOffset != 0) { setTimeInMillis(time + zoneOffset); long fd2 = getCurrentFixedDate(); // If the adjustment has changed the date, then take // the previous one. if (fd2 != fd) { setTimeInMillis(time - zoneOffset); } } } } /** {@collect.stats} * {@description.open} * Adds or subtracts (up/down) a single unit of time on the given time * field without changing larger fields. * <p> * <em>Example</em>: Consider a <code>GregorianCalendar</code> * originally set to December 31, 1999. Calling {@link #roll(int,boolean) roll(Calendar.MONTH, true)} * sets the calendar to January 31, 1999. The <code>YEAR</code> field is unchanged * because it is a larger field than <code>MONTH</code>.</p> * {@description.close} * * @param up indicates if the value of the specified calendar field is to be * rolled up or rolled down. Use <code>true</code> if rolling up, <code>false</code> otherwise. * @exception IllegalArgumentException if <code>field</code> is * <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or unknown, * or if any calendar fields have out-of-range values in * non-lenient mode. * @see #add(int,int) * @see #set(int,int) */ public void roll(int field, boolean up) { roll(field, up ? +1 : -1); } /** {@collect.stats} * {@description.open} * Adds a signed amount to the specified calendar field without changing larger fields. * A negative roll amount means to subtract from field without changing * larger fields. If the specified amount is 0, this method performs nothing. * * <p>This method calls {@link #complete()} before adding the * amount so that all the calendar fields are normalized. If there * is any calendar field having an out-of-range value in non-lenient mode, then an * <code>IllegalArgumentException</code> is thrown. * * <p> * <em>Example</em>: Consider a <code>GregorianCalendar</code> * originally set to August 31, 1999. Calling <code>roll(Calendar.MONTH, * 8)</code> sets the calendar to April 30, <strong>1999</strong>. Using a * <code>GregorianCalendar</code>, the <code>DAY_OF_MONTH</code> field cannot * be 31 in the month April. <code>DAY_OF_MONTH</code> is set to the closest possible * value, 30. The <code>YEAR</code> field maintains the value of 1999 because it * is a larger field than <code>MONTH</code>. * <p> * <em>Example</em>: Consider a <code>GregorianCalendar</code> * originally set to Sunday June 6, 1999. Calling * <code>roll(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to * Tuesday June 1, 1999, whereas calling * <code>add(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to * Sunday May 30, 1999. This is because the roll rule imposes an * additional constraint: The <code>MONTH</code> must not change when the * <code>WEEK_OF_MONTH</code> is rolled. Taken together with add rule 1, * the resultant date must be between Tuesday June 1 and Saturday June * 5. According to add rule 2, the <code>DAY_OF_WEEK</code>, an invariant * when changing the <code>WEEK_OF_MONTH</code>, is set to Tuesday, the * closest possible value to Sunday (where Sunday is the first day of the * week).</p> * {@description.close} * * @param field the calendar field. * @param amount the signed amount to add to <code>field</code>. * @exception IllegalArgumentException if <code>field</code> is * <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or unknown, * or if any calendar fields have out-of-range values in * non-lenient mode. * @see #roll(int,boolean) * @see #add(int,int) * @see #set(int,int) * @since 1.2 */ public void roll(int field, int amount) { // If amount == 0, do nothing even the given field is out of // range. This is tested by JCK. if (amount == 0) { return; } if (field < 0 || field >= ZONE_OFFSET) { throw new IllegalArgumentException(); } // Sync the time and calendar fields. complete(); int min = getMinimum(field); int max = getMaximum(field); switch (field) { case AM_PM: case ERA: case YEAR: case MINUTE: case SECOND: case MILLISECOND: // These fields are handled simply, since they have fixed minima // and maxima. The field DAY_OF_MONTH is almost as simple. Other // fields are complicated, since the range within they must roll // varies depending on the date. break; case HOUR: case HOUR_OF_DAY: { int unit = max + 1; // 12 or 24 hours int h = internalGet(field); int nh = (h + amount) % unit; if (nh < 0) { nh += unit; } time += ONE_HOUR * (nh - h); // The day might have changed, which could happen if // the daylight saving time transition brings it to // the next day, although it's very unlikely. But we // have to make sure not to change the larger fields. CalendarDate d = calsys.getCalendarDate(time, getZone()); if (internalGet(DAY_OF_MONTH) != d.getDayOfMonth()) { d.setDate(internalGet(YEAR), internalGet(MONTH) + 1, internalGet(DAY_OF_MONTH)); if (field == HOUR) { assert (internalGet(AM_PM) == PM); d.addHours(+12); // restore PM } time = calsys.getTime(d); } int hourOfDay = d.getHours(); internalSet(field, hourOfDay % unit); if (field == HOUR) { internalSet(HOUR_OF_DAY, hourOfDay); } else { internalSet(AM_PM, hourOfDay / 12); internalSet(HOUR, hourOfDay % 12); } // Time zone offset and/or daylight saving might have changed. int zoneOffset = d.getZoneOffset(); int saving = d.getDaylightSaving(); internalSet(ZONE_OFFSET, zoneOffset - saving); internalSet(DST_OFFSET, saving); return; } case MONTH: // Rolling the month involves both pinning the final value to [0, 11] // and adjusting the DAY_OF_MONTH if necessary. We only adjust the // DAY_OF_MONTH if, after updating the MONTH field, it is illegal. // E.g., <jan31>.roll(MONTH, 1) -> <feb28> or <feb29>. { if (!isCutoverYear(cdate.getNormalizedYear())) { int mon = (internalGet(MONTH) + amount) % 12; if (mon < 0) { mon += 12; } set(MONTH, mon); // Keep the day of month in the range. We don't want to spill over // into the next month; e.g., we don't want jan31 + 1 mo -> feb31 -> // mar3. int monthLen = monthLength(mon); if (internalGet(DAY_OF_MONTH) > monthLen) { set(DAY_OF_MONTH, monthLen); } } else { // We need to take care of different lengths in // year and month due to the cutover. int yearLength = getActualMaximum(MONTH) + 1; int mon = (internalGet(MONTH) + amount) % yearLength; if (mon < 0) { mon += yearLength; } set(MONTH, mon); int monthLen = getActualMaximum(DAY_OF_MONTH); if (internalGet(DAY_OF_MONTH) > monthLen) { set(DAY_OF_MONTH, monthLen); } } return; } case WEEK_OF_YEAR: { int y = cdate.getNormalizedYear(); max = getActualMaximum(WEEK_OF_YEAR); set(DAY_OF_WEEK, internalGet(DAY_OF_WEEK)); int woy = internalGet(WEEK_OF_YEAR); int value = woy + amount; if (!isCutoverYear(y)) { // If the new value is in between min and max // (exclusive), then we can use the value. if (value > min && value < max) { set(WEEK_OF_YEAR, value); return; } long fd = getCurrentFixedDate(); // Make sure that the min week has the current DAY_OF_WEEK long day1 = fd - (7 * (woy - min)); if (calsys.getYearFromFixedDate(day1) != y) { min++; } // Make sure the same thing for the max week fd += 7 * (max - internalGet(WEEK_OF_YEAR)); if (calsys.getYearFromFixedDate(fd) != y) { max--; } break; } // Handle cutover here. long fd = getCurrentFixedDate(); BaseCalendar cal; if (gregorianCutoverYear == gregorianCutoverYearJulian) { cal = getCutoverCalendarSystem(); } else if (y == gregorianCutoverYear) { cal = gcal; } else { cal = getJulianCalendarSystem(); } long day1 = fd - (7 * (woy - min)); // Make sure that the min week has the current DAY_OF_WEEK if (cal.getYearFromFixedDate(day1) != y) { min++; } // Make sure the same thing for the max week fd += 7 * (max - woy); cal = (fd >= gregorianCutoverDate) ? gcal : getJulianCalendarSystem(); if (cal.getYearFromFixedDate(fd) != y) { max--; } // value: the new WEEK_OF_YEAR which must be converted // to month and day of month. value = getRolledValue(woy, amount, min, max) - 1; BaseCalendar.Date d = getCalendarDate(day1 + value * 7); set(MONTH, d.getMonth() - 1); set(DAY_OF_MONTH, d.getDayOfMonth()); return; } case WEEK_OF_MONTH: { boolean isCutoverYear = isCutoverYear(cdate.getNormalizedYear()); // dow: relative day of week from first day of week int dow = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek(); if (dow < 0) { dow += 7; } long fd = getCurrentFixedDate(); long month1; // fixed date of the first day (usually 1) of the month int monthLength; // actual month length if (isCutoverYear) { month1 = getFixedDateMonth1(cdate, fd); monthLength = actualMonthLength(); } else { month1 = fd - internalGet(DAY_OF_MONTH) + 1; monthLength = calsys.getMonthLength(cdate); } // the first day of week of the month. long monthDay1st = calsys.getDayOfWeekDateOnOrBefore(month1 + 6, getFirstDayOfWeek()); // if the week has enough days to form a week, the // week starts from the previous month. if ((int)(monthDay1st - month1) >= getMinimalDaysInFirstWeek()) { monthDay1st -= 7; } max = getActualMaximum(field); // value: the new WEEK_OF_MONTH value int value = getRolledValue(internalGet(field), amount, 1, max) - 1; // nfd: fixed date of the rolled date long nfd = monthDay1st + value * 7 + dow; // Unlike WEEK_OF_YEAR, we need to change day of week if the // nfd is out of the month. if (nfd < month1) { nfd = month1; } else if (nfd >= (month1 + monthLength)) { nfd = month1 + monthLength - 1; } int dayOfMonth; if (isCutoverYear) { // If we are in the cutover year, convert nfd to // its calendar date and use dayOfMonth. BaseCalendar.Date d = getCalendarDate(nfd); dayOfMonth = d.getDayOfMonth(); } else { dayOfMonth = (int)(nfd - month1) + 1; } set(DAY_OF_MONTH, dayOfMonth); return; } case DAY_OF_MONTH: { if (!isCutoverYear(cdate.getNormalizedYear())) { max = calsys.getMonthLength(cdate); break; } // Cutover year handling long fd = getCurrentFixedDate(); long month1 = getFixedDateMonth1(cdate, fd); // It may not be a regular month. Convert the date and range to // the relative values, perform the roll, and // convert the result back to the rolled date. int value = getRolledValue((int)(fd - month1), amount, 0, actualMonthLength() - 1); BaseCalendar.Date d = getCalendarDate(month1 + value); assert d.getMonth()-1 == internalGet(MONTH); set(DAY_OF_MONTH, d.getDayOfMonth()); return; } case DAY_OF_YEAR: { max = getActualMaximum(field); if (!isCutoverYear(cdate.getNormalizedYear())) { break; } // Handle cutover here. long fd = getCurrentFixedDate(); long jan1 = fd - internalGet(DAY_OF_YEAR) + 1; int value = getRolledValue((int)(fd - jan1) + 1, amount, min, max); BaseCalendar.Date d = getCalendarDate(jan1 + value - 1); set(MONTH, d.getMonth() - 1); set(DAY_OF_MONTH, d.getDayOfMonth()); return; } case DAY_OF_WEEK: { if (!isCutoverYear(cdate.getNormalizedYear())) { // If the week of year is in the same year, we can // just change DAY_OF_WEEK. int weekOfYear = internalGet(WEEK_OF_YEAR); if (weekOfYear > 1 && weekOfYear < 52) { set(WEEK_OF_YEAR, weekOfYear); // update stamp[WEEK_OF_YEAR] max = SATURDAY; break; } } // We need to handle it in a different way around year // boundaries and in the cutover year. Note that // changing era and year values violates the roll // rule: not changing larger calendar fields... amount %= 7; if (amount == 0) { return; } long fd = getCurrentFixedDate(); long dowFirst = calsys.getDayOfWeekDateOnOrBefore(fd, getFirstDayOfWeek()); fd += amount; if (fd < dowFirst) { fd += 7; } else if (fd >= dowFirst + 7) { fd -= 7; } BaseCalendar.Date d = getCalendarDate(fd); set(ERA, (d.getNormalizedYear() <= 0 ? BCE : CE)); set(d.getYear(), d.getMonth() - 1, d.getDayOfMonth()); return; } case DAY_OF_WEEK_IN_MONTH: { min = 1; // after normalized, min should be 1. if (!isCutoverYear(cdate.getNormalizedYear())) { int dom = internalGet(DAY_OF_MONTH); int monthLength = calsys.getMonthLength(cdate); int lastDays = monthLength % 7; max = monthLength / 7; int x = (dom - 1) % 7; if (x < lastDays) { max++; } set(DAY_OF_WEEK, internalGet(DAY_OF_WEEK)); break; } // Cutover year handling long fd = getCurrentFixedDate(); long month1 = getFixedDateMonth1(cdate, fd); int monthLength = actualMonthLength(); int lastDays = monthLength % 7; max = monthLength / 7; int x = (int)(fd - month1) % 7; if (x < lastDays) { max++; } int value = getRolledValue(internalGet(field), amount, min, max) - 1; fd = month1 + value * 7 + x; BaseCalendar cal = (fd >= gregorianCutoverDate) ? gcal : getJulianCalendarSystem(); BaseCalendar.Date d = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE); cal.getCalendarDateFromFixedDate(d, fd); set(DAY_OF_MONTH, d.getDayOfMonth()); return; } } set(field, getRolledValue(internalGet(field), amount, min, max)); } /** {@collect.stats} * {@description.open} * Returns the minimum value for the given calendar field of this * <code>GregorianCalendar</code> instance. The minimum value is * defined as the smallest value returned by the {@link * Calendar#get(int) get} method for any possible time value, * taking into consideration the current values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * {@link #getGregorianChange() getGregorianChange} and * {@link Calendar#getTimeZone() getTimeZone} methods. * {@description.close} * * @param field the calendar field. * @return the minimum value for the given calendar field. * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ public int getMinimum(int field) { return MIN_VALUES[field]; } /** {@collect.stats} * {@description.open} * Returns the maximum value for the given calendar field of this * <code>GregorianCalendar</code> instance. The maximum value is * defined as the largest value returned by the {@link * Calendar#get(int) get} method for any possible time value, * taking into consideration the current values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * {@link #getGregorianChange() getGregorianChange} and * {@link Calendar#getTimeZone() getTimeZone} methods. * {@description.close} * * @param field the calendar field. * @return the maximum value for the given calendar field. * @see #getMinimum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ public int getMaximum(int field) { switch (field) { case MONTH: case DAY_OF_MONTH: case DAY_OF_YEAR: case WEEK_OF_YEAR: case WEEK_OF_MONTH: case DAY_OF_WEEK_IN_MONTH: case YEAR: { // On or after Gregorian 200-3-1, Julian and Gregorian // calendar dates are the same or Gregorian dates are // larger (i.e., there is a "gap") after 300-3-1. if (gregorianCutoverYear > 200) { break; } // There might be "overlapping" dates. GregorianCalendar gc = (GregorianCalendar) clone(); gc.setLenient(true); gc.setTimeInMillis(gregorianCutover); int v1 = gc.getActualMaximum(field); gc.setTimeInMillis(gregorianCutover-1); int v2 = gc.getActualMaximum(field); return Math.max(MAX_VALUES[field], Math.max(v1, v2)); } } return MAX_VALUES[field]; } /** {@collect.stats} * {@description.open} * Returns the highest minimum value for the given calendar field * of this <code>GregorianCalendar</code> instance. The highest * minimum value is defined as the largest value returned by * {@link #getActualMinimum(int)} for any possible time value, * taking into consideration the current values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * {@link #getGregorianChange() getGregorianChange} and * {@link Calendar#getTimeZone() getTimeZone} methods. * {@description.close} * * @param field the calendar field. * @return the highest minimum value for the given calendar field. * @see #getMinimum(int) * @see #getMaximum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ public int getGreatestMinimum(int field) { if (field == DAY_OF_MONTH) { BaseCalendar.Date d = getGregorianCutoverDate(); long mon1 = getFixedDateMonth1(d, gregorianCutoverDate); d = getCalendarDate(mon1); return Math.max(MIN_VALUES[field], d.getDayOfMonth()); } return MIN_VALUES[field]; } /** {@collect.stats} * {@description.open} * Returns the lowest maximum value for the given calendar field * of this <code>GregorianCalendar</code> instance. The lowest * maximum value is defined as the smallest value returned by * {@link #getActualMaximum(int)} for any possible time value, * taking into consideration the current values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * {@link #getGregorianChange() getGregorianChange} and * {@link Calendar#getTimeZone() getTimeZone} methods. * {@description.close} * * @param field the calendar field * @return the lowest maximum value for the given calendar field. * @see #getMinimum(int) * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ public int getLeastMaximum(int field) { switch (field) { case MONTH: case DAY_OF_MONTH: case DAY_OF_YEAR: case WEEK_OF_YEAR: case WEEK_OF_MONTH: case DAY_OF_WEEK_IN_MONTH: case YEAR: { GregorianCalendar gc = (GregorianCalendar) clone(); gc.setLenient(true); gc.setTimeInMillis(gregorianCutover); int v1 = gc.getActualMaximum(field); gc.setTimeInMillis(gregorianCutover-1); int v2 = gc.getActualMaximum(field); return Math.min(LEAST_MAX_VALUES[field], Math.min(v1, v2)); } } return LEAST_MAX_VALUES[field]; } /** {@collect.stats} * {@description.open} * Returns the minimum value that this calendar field could have, * taking into consideration the given time value and the current * values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * {@link #getGregorianChange() getGregorianChange} and * {@link Calendar#getTimeZone() getTimeZone} methods. * * <p>For example, if the Gregorian change date is January 10, * 1970 and the date of this <code>GregorianCalendar</code> is * January 20, 1970, the actual minimum value of the * <code>DAY_OF_MONTH</code> field is 10 because the previous date * of January 10, 1970 is December 27, 1996 (in the Julian * calendar). Therefore, December 28, 1969 to January 9, 1970 * don't exist. * {@description.close} * * @param field the calendar field * @return the minimum of the given field for the time value of * this <code>GregorianCalendar</code> * @see #getMinimum(int) * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMaximum(int) * @since 1.2 */ public int getActualMinimum(int field) { if (field == DAY_OF_MONTH) { GregorianCalendar gc = getNormalizedCalendar(); int year = gc.cdate.getNormalizedYear(); if (year == gregorianCutoverYear || year == gregorianCutoverYearJulian) { long month1 = getFixedDateMonth1(gc.cdate, gc.calsys.getFixedDate(gc.cdate)); BaseCalendar.Date d = getCalendarDate(month1); return d.getDayOfMonth(); } } return getMinimum(field); } /** {@collect.stats} * {@description.open} * Returns the maximum value that this calendar field could have, * taking into consideration the given time value and the current * values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * {@link #getGregorianChange() getGregorianChange} and * {@link Calendar#getTimeZone() getTimeZone} methods. * For example, if the date of this instance is February 1, 2004, * the actual maximum value of the <code>DAY_OF_MONTH</code> field * is 29 because 2004 is a leap year, and if the date of this * instance is February 1, 2005, it's 28. * {@description.close} * * @param field the calendar field * @return the maximum of the given field for the time value of * this <code>GregorianCalendar</code> * @see #getMinimum(int) * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) * @since 1.2 */ public int getActualMaximum(int field) { final int fieldsForFixedMax = ERA_MASK|DAY_OF_WEEK_MASK|HOUR_MASK|AM_PM_MASK| HOUR_OF_DAY_MASK|MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK| ZONE_OFFSET_MASK|DST_OFFSET_MASK; if ((fieldsForFixedMax & (1<<field)) != 0) { return getMaximum(field); } GregorianCalendar gc = getNormalizedCalendar(); BaseCalendar.Date date = gc.cdate; BaseCalendar cal = gc.calsys; int normalizedYear = date.getNormalizedYear(); int value = -1; switch (field) { case MONTH: { if (!gc.isCutoverYear(normalizedYear)) { value = DECEMBER; break; } // January 1 of the next year may or may not exist. long nextJan1; do { nextJan1 = gcal.getFixedDate(++normalizedYear, BaseCalendar.JANUARY, 1, null); } while (nextJan1 < gregorianCutoverDate); BaseCalendar.Date d = (BaseCalendar.Date) date.clone(); cal.getCalendarDateFromFixedDate(d, nextJan1 - 1); value = d.getMonth() - 1; } break; case DAY_OF_MONTH: { value = cal.getMonthLength(date); if (!gc.isCutoverYear(normalizedYear) || date.getDayOfMonth() == value) { break; } // Handle cutover year. long fd = gc.getCurrentFixedDate(); if (fd >= gregorianCutoverDate) { break; } int monthLength = gc.actualMonthLength(); long monthEnd = gc.getFixedDateMonth1(gc.cdate, fd) + monthLength - 1; // Convert the fixed date to its calendar date. BaseCalendar.Date d = gc.getCalendarDate(monthEnd); value = d.getDayOfMonth(); } break; case DAY_OF_YEAR: { if (!gc.isCutoverYear(normalizedYear)) { value = cal.getYearLength(date); break; } // Handle cutover year. long jan1; if (gregorianCutoverYear == gregorianCutoverYearJulian) { BaseCalendar cocal = gc.getCutoverCalendarSystem(); jan1 = cocal.getFixedDate(normalizedYear, 1, 1, null); } else if (normalizedYear == gregorianCutoverYearJulian) { jan1 = cal.getFixedDate(normalizedYear, 1, 1, null); } else { jan1 = gregorianCutoverDate; } // January 1 of the next year may or may not exist. long nextJan1 = gcal.getFixedDate(++normalizedYear, 1, 1, null); if (nextJan1 < gregorianCutoverDate) { nextJan1 = gregorianCutoverDate; } assert jan1 <= cal.getFixedDate(date.getNormalizedYear(), date.getMonth(), date.getDayOfMonth(), date); assert nextJan1 >= cal.getFixedDate(date.getNormalizedYear(), date.getMonth(), date.getDayOfMonth(), date); value = (int)(nextJan1 - jan1); } break; case WEEK_OF_YEAR: { if (!gc.isCutoverYear(normalizedYear)) { // Get the day of week of January 1 of the year CalendarDate d = cal.newCalendarDate(TimeZone.NO_TIMEZONE); d.setDate(date.getYear(), BaseCalendar.JANUARY, 1); int dayOfWeek = cal.getDayOfWeek(d); // Normalize the day of week with the firstDayOfWeek value dayOfWeek -= getFirstDayOfWeek(); if (dayOfWeek < 0) { dayOfWeek += 7; } value = 52; int magic = dayOfWeek + getMinimalDaysInFirstWeek() - 1; if ((magic == 6) || (date.isLeapYear() && (magic == 5 || magic == 12))) { value++; } break; } if (gc == this) { gc = (GregorianCalendar) gc.clone(); } gc.set(DAY_OF_YEAR, getActualMaximum(DAY_OF_YEAR)); value = gc.get(WEEK_OF_YEAR); } break; case WEEK_OF_MONTH: { if (!gc.isCutoverYear(normalizedYear)) { CalendarDate d = cal.newCalendarDate(null); d.setDate(date.getYear(), date.getMonth(), 1); int dayOfWeek = cal.getDayOfWeek(d); int monthLength = cal.getMonthLength(d); dayOfWeek -= getFirstDayOfWeek(); if (dayOfWeek < 0) { dayOfWeek += 7; } int nDaysFirstWeek = 7 - dayOfWeek; // # of days in the first week value = 3; if (nDaysFirstWeek >= getMinimalDaysInFirstWeek()) { value++; } monthLength -= nDaysFirstWeek + 7 * 3; if (monthLength > 0) { value++; if (monthLength > 7) { value++; } } break; } // Cutover year handling if (gc == this) { gc = (GregorianCalendar) gc.clone(); } int y = gc.internalGet(YEAR); int m = gc.internalGet(MONTH); do { value = gc.get(WEEK_OF_MONTH); gc.add(WEEK_OF_MONTH, +1); } while (gc.get(YEAR) == y && gc.get(MONTH) == m); } break; case DAY_OF_WEEK_IN_MONTH: { // may be in the Gregorian cutover month int ndays, dow1; int dow = date.getDayOfWeek(); if (!gc.isCutoverYear(normalizedYear)) { BaseCalendar.Date d = (BaseCalendar.Date) date.clone(); ndays = cal.getMonthLength(d); d.setDayOfMonth(1); cal.normalize(d); dow1 = d.getDayOfWeek(); } else { // Let a cloned GregorianCalendar take care of the cutover cases. if (gc == this) { gc = (GregorianCalendar) clone(); } ndays = gc.actualMonthLength(); gc.set(DAY_OF_MONTH, gc.getActualMinimum(DAY_OF_MONTH)); dow1 = gc.get(DAY_OF_WEEK); } int x = dow - dow1; if (x < 0) { x += 7; } ndays -= x; value = (ndays + 6) / 7; } break; case YEAR: /* The year computation is no different, in principle, from the * others, however, the range of possible maxima is large. In * addition, the way we know we've exceeded the range is different. * For these reasons, we use the special case code below to handle * this field. * * The actual maxima for YEAR depend on the type of calendar: * * Gregorian = May 17, 292275056 BCE - Aug 17, 292278994 CE * Julian = Dec 2, 292269055 BCE - Jan 3, 292272993 CE * Hybrid = Dec 2, 292269055 BCE - Aug 17, 292278994 CE * * We know we've exceeded the maximum when either the month, date, * time, or era changes in response to setting the year. We don't * check for month, date, and time here because the year and era are * sufficient to detect an invalid year setting. NOTE: If code is * added to check the month and date in the future for some reason, * Feb 29 must be allowed to shift to Mar 1 when setting the year. */ { if (gc == this) { gc = (GregorianCalendar) clone(); } // Calculate the millisecond offset from the beginning // of the year of this calendar and adjust the max // year value if we are beyond the limit in the max // year. long current = gc.getYearOffsetInMillis(); if (gc.internalGetEra() == CE) { gc.setTimeInMillis(Long.MAX_VALUE); value = gc.get(YEAR); long maxEnd = gc.getYearOffsetInMillis(); if (current > maxEnd) { value--; } } else { CalendarSystem mincal = gc.getTimeInMillis() >= gregorianCutover ? gcal : getJulianCalendarSystem(); CalendarDate d = mincal.getCalendarDate(Long.MIN_VALUE, getZone()); long maxEnd = (cal.getDayOfYear(d) - 1) * 24 + d.getHours(); maxEnd *= 60; maxEnd += d.getMinutes(); maxEnd *= 60; maxEnd += d.getSeconds(); maxEnd *= 1000; maxEnd += d.getMillis(); value = d.getYear(); if (value <= 0) { assert mincal == gcal; value = 1 - value; } if (current < maxEnd) { value--; } } } break; default: throw new ArrayIndexOutOfBoundsException(field); } return value; } /** {@collect.stats} * {@description.open} * Returns the millisecond offset from the beginning of this * year. * {@description.close} * {@property.open internal} * This Calendar object must have been normalized. * {@property.close} */ private final long getYearOffsetInMillis() { long t = (internalGet(DAY_OF_YEAR) - 1) * 24; t += internalGet(HOUR_OF_DAY); t *= 60; t += internalGet(MINUTE); t *= 60; t += internalGet(SECOND); t *= 1000; return t + internalGet(MILLISECOND) - (internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET)); } public Object clone() { GregorianCalendar other = (GregorianCalendar) super.clone(); other.gdate = (BaseCalendar.Date) gdate.clone(); if (cdate != null) { if (cdate != gdate) { other.cdate = (BaseCalendar.Date) cdate.clone(); } else { other.cdate = other.gdate; } } other.originalFields = null; other.zoneOffsets = null; return other; } public TimeZone getTimeZone() { TimeZone zone = super.getTimeZone(); // To share the zone by CalendarDates gdate.setZone(zone); if (cdate != null && cdate != gdate) { cdate.setZone(zone); } return zone; } public void setTimeZone(TimeZone zone) { super.setTimeZone(zone); // To share the zone by CalendarDates gdate.setZone(zone); if (cdate != null && cdate != gdate) { cdate.setZone(zone); } } ////////////////////// // Proposed public API ////////////////////// /** {@collect.stats} * {@description.open} * Returns the year that corresponds to the <code>WEEK_OF_YEAR</code> field. * This may be one year before or after the Gregorian or Julian year stored * in the <code>YEAR</code> field. For example, January 1, 1999 is considered * Friday of week 53 of 1998 (if minimal days in first week is * 2 or less, and the first day of the week is Sunday). Given * these same settings, the ISO year of January 1, 1999 is * 1998. * * <p>This method calls {@link Calendar#complete} before * calculating the week-based year. * {@description.close} * * @return the year corresponding to the <code>WEEK_OF_YEAR</code> field, which * may be one year before or after the <code>YEAR</code> field. * @see #YEAR * @see #WEEK_OF_YEAR */ /* public int getWeekBasedYear() { complete(); // TODO: Below doesn't work for gregorian cutover... int weekOfYear = internalGet(WEEK_OF_YEAR); int year = internalGet(YEAR); if (internalGet(MONTH) == Calendar.JANUARY) { if (weekOfYear >= 52) { --year; } } else { if (weekOfYear == 1) { ++year; } } return year; } */ ///////////////////////////// // Time => Fields computation ///////////////////////////// /** {@collect.stats} * {@description.open} * The fixed date corresponding to gdate. If the value is * Long.MIN_VALUE, the fixed date value is unknown. Currently, * Julian calendar dates are not cached. * {@description.close} */ transient private long cachedFixedDate = Long.MIN_VALUE; /** {@collect.stats} * {@description.open} * Converts the time value (millisecond offset from the <a * href="Calendar.html#Epoch">Epoch</a>) to calendar field values. * The time is <em>not</em> * recomputed first; to recompute the time, then the fields, call the * <code>complete</code> method. * {@description.close} * * @see Calendar#complete */ protected void computeFields() { int mask = 0; if (isPartiallyNormalized()) { // Determine which calendar fields need to be computed. mask = getSetStateFields(); int fieldMask = ~mask & ALL_FIELDS; // We have to call computTime in case calsys == null in // order to set calsys and cdate. (6263644) if (fieldMask != 0 || calsys == null) { mask |= computeFields(fieldMask, mask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK)); assert mask == ALL_FIELDS; } } else { mask = ALL_FIELDS; computeFields(mask, 0); } // After computing all the fields, set the field state to `COMPUTED'. setFieldsComputed(mask); } /** {@collect.stats} * {@description.open} * This computeFields implements the conversion from UTC * (millisecond offset from the Epoch) to calendar * field values. fieldMask specifies which fields to change the * setting state to COMPUTED, although all fields are set to * the correct values. This is required to fix 4685354. * {@description.close} * * @param fieldMask a bit mask to specify which fields to change * the setting state. * @param tzMask a bit mask to specify which time zone offset * fields to be used for time calculations * @return a new field mask that indicates what field values have * actually been set. */ private int computeFields(int fieldMask, int tzMask) { int zoneOffset = 0; TimeZone tz = getZone(); if (zoneOffsets == null) { zoneOffsets = new int[2]; } if (tzMask != (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) { if (tz instanceof ZoneInfo) { zoneOffset = ((ZoneInfo)tz).getOffsets(time, zoneOffsets); } else { zoneOffset = tz.getOffset(time); zoneOffsets[0] = tz.getRawOffset(); zoneOffsets[1] = zoneOffset - zoneOffsets[0]; } } if (tzMask != 0) { if (isFieldSet(tzMask, ZONE_OFFSET)) { zoneOffsets[0] = internalGet(ZONE_OFFSET); } if (isFieldSet(tzMask, DST_OFFSET)) { zoneOffsets[1] = internalGet(DST_OFFSET); } zoneOffset = zoneOffsets[0] + zoneOffsets[1]; } // By computing time and zoneOffset separately, we can take // the wider range of time+zoneOffset than the previous // implementation. long fixedDate = zoneOffset / ONE_DAY; int timeOfDay = zoneOffset % (int)ONE_DAY; fixedDate += time / ONE_DAY; timeOfDay += (int) (time % ONE_DAY); if (timeOfDay >= ONE_DAY) { timeOfDay -= ONE_DAY; ++fixedDate; } else { while (timeOfDay < 0) { timeOfDay += ONE_DAY; --fixedDate; } } fixedDate += EPOCH_OFFSET; int era = CE; int year; if (fixedDate >= gregorianCutoverDate) { // Handle Gregorian dates. assert cachedFixedDate == Long.MIN_VALUE || gdate.isNormalized() : "cache control: not normalized"; assert cachedFixedDate == Long.MIN_VALUE || gcal.getFixedDate(gdate.getNormalizedYear(), gdate.getMonth(), gdate.getDayOfMonth(), gdate) == cachedFixedDate : "cache control: inconsictency" + ", cachedFixedDate=" + cachedFixedDate + ", computed=" + gcal.getFixedDate(gdate.getNormalizedYear(), gdate.getMonth(), gdate.getDayOfMonth(), gdate) + ", date=" + gdate; // See if we can use gdate to avoid date calculation. if (fixedDate != cachedFixedDate) { gcal.getCalendarDateFromFixedDate(gdate, fixedDate); cachedFixedDate = fixedDate; } year = gdate.getYear(); if (year <= 0) { year = 1 - year; era = BCE; } calsys = gcal; cdate = gdate; assert cdate.getDayOfWeek() > 0 : "dow="+cdate.getDayOfWeek()+", date="+cdate; } else { // Handle Julian calendar dates. calsys = getJulianCalendarSystem(); cdate = (BaseCalendar.Date) jcal.newCalendarDate(getZone()); jcal.getCalendarDateFromFixedDate(cdate, fixedDate); Era e = cdate.getEra(); if (e == jeras[0]) { era = BCE; } year = cdate.getYear(); } // Always set the ERA and YEAR values. internalSet(ERA, era); internalSet(YEAR, year); int mask = fieldMask | (ERA_MASK|YEAR_MASK); int month = cdate.getMonth() - 1; // 0-based int dayOfMonth = cdate.getDayOfMonth(); // Set the basic date fields. if ((fieldMask & (MONTH_MASK|DAY_OF_MONTH_MASK|DAY_OF_WEEK_MASK)) != 0) { internalSet(MONTH, month); internalSet(DAY_OF_MONTH, dayOfMonth); internalSet(DAY_OF_WEEK, cdate.getDayOfWeek()); mask |= MONTH_MASK|DAY_OF_MONTH_MASK|DAY_OF_WEEK_MASK; } if ((fieldMask & (HOUR_OF_DAY_MASK|AM_PM_MASK|HOUR_MASK |MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK)) != 0) { if (timeOfDay != 0) { int hours = timeOfDay / ONE_HOUR; internalSet(HOUR_OF_DAY, hours); internalSet(AM_PM, hours / 12); // Assume AM == 0 internalSet(HOUR, hours % 12); int r = timeOfDay % ONE_HOUR; internalSet(MINUTE, r / ONE_MINUTE); r %= ONE_MINUTE; internalSet(SECOND, r / ONE_SECOND); internalSet(MILLISECOND, r % ONE_SECOND); } else { internalSet(HOUR_OF_DAY, 0); internalSet(AM_PM, AM); internalSet(HOUR, 0); internalSet(MINUTE, 0); internalSet(SECOND, 0); internalSet(MILLISECOND, 0); } mask |= (HOUR_OF_DAY_MASK|AM_PM_MASK|HOUR_MASK |MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK); } if ((fieldMask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) != 0) { internalSet(ZONE_OFFSET, zoneOffsets[0]); internalSet(DST_OFFSET, zoneOffsets[1]); mask |= (ZONE_OFFSET_MASK|DST_OFFSET_MASK); } if ((fieldMask & (DAY_OF_YEAR_MASK|WEEK_OF_YEAR_MASK|WEEK_OF_MONTH_MASK|DAY_OF_WEEK_IN_MONTH_MASK)) != 0) { int normalizedYear = cdate.getNormalizedYear(); long fixedDateJan1 = calsys.getFixedDate(normalizedYear, 1, 1, cdate); int dayOfYear = (int)(fixedDate - fixedDateJan1) + 1; long fixedDateMonth1 = fixedDate - dayOfMonth + 1; int cutoverGap = 0; int cutoverYear = (calsys == gcal) ? gregorianCutoverYear : gregorianCutoverYearJulian; int relativeDayOfMonth = dayOfMonth - 1; // If we are in the cutover year, we need some special handling. if (normalizedYear == cutoverYear) { // Need to take care of the "missing" days. if (getCutoverCalendarSystem() == jcal) { // We need to find out where we are. The cutover // gap could even be more than one year. (One // year difference in ~48667 years.) fixedDateJan1 = getFixedDateJan1(cdate, fixedDate); if (fixedDate >= gregorianCutoverDate) { fixedDateMonth1 = getFixedDateMonth1(cdate, fixedDate); } } int realDayOfYear = (int)(fixedDate - fixedDateJan1) + 1; cutoverGap = dayOfYear - realDayOfYear; dayOfYear = realDayOfYear; relativeDayOfMonth = (int)(fixedDate - fixedDateMonth1); } internalSet(DAY_OF_YEAR, dayOfYear); internalSet(DAY_OF_WEEK_IN_MONTH, relativeDayOfMonth / 7 + 1); int weekOfYear = getWeekNumber(fixedDateJan1, fixedDate); // The spec is to calculate WEEK_OF_YEAR in the // ISO8601-style. This creates problems, though. if (weekOfYear == 0) { // If the date belongs to the last week of the // previous year, use the week number of "12/31" of // the "previous" year. Again, if the previous year is // the Gregorian cutover year, we need to take care of // it. Usually the previous day of January 1 is // December 31, which is not always true in // GregorianCalendar. long fixedDec31 = fixedDateJan1 - 1; long prevJan1; if (normalizedYear > (cutoverYear + 1)) { prevJan1 = fixedDateJan1 - 365; if (CalendarUtils.isGregorianLeapYear(normalizedYear - 1)) { --prevJan1; } } else { BaseCalendar calForJan1 = calsys; int prevYear = normalizedYear - 1; if (prevYear == cutoverYear) { calForJan1 = getCutoverCalendarSystem(); } prevJan1 = calForJan1.getFixedDate(prevYear, BaseCalendar.JANUARY, 1, null); while (prevJan1 > fixedDec31) { prevJan1 = getJulianCalendarSystem().getFixedDate(--prevYear, BaseCalendar.JANUARY, 1, null); } } weekOfYear = getWeekNumber(prevJan1, fixedDec31); } else { if (normalizedYear > gregorianCutoverYear || normalizedYear < (gregorianCutoverYearJulian - 1)) { // Regular years if (weekOfYear >= 52) { long nextJan1 = fixedDateJan1 + 365; if (cdate.isLeapYear()) { nextJan1++; } long nextJan1st = calsys.getDayOfWeekDateOnOrBefore(nextJan1 + 6, getFirstDayOfWeek()); int ndays = (int)(nextJan1st - nextJan1); if (ndays >= getMinimalDaysInFirstWeek() && fixedDate >= (nextJan1st - 7)) { // The first days forms a week in which the date is included. weekOfYear = 1; } } } else { BaseCalendar calForJan1 = calsys; int nextYear = normalizedYear + 1; if (nextYear == (gregorianCutoverYearJulian + 1) && nextYear < gregorianCutoverYear) { // In case the gap is more than one year. nextYear = gregorianCutoverYear; } if (nextYear == gregorianCutoverYear) { calForJan1 = getCutoverCalendarSystem(); } long nextJan1 = calForJan1.getFixedDate(nextYear, BaseCalendar.JANUARY, 1, null); if (nextJan1 < fixedDate) { nextJan1 = gregorianCutoverDate; calForJan1 = gcal; } long nextJan1st = calForJan1.getDayOfWeekDateOnOrBefore(nextJan1 + 6, getFirstDayOfWeek()); int ndays = (int)(nextJan1st - nextJan1); if (ndays >= getMinimalDaysInFirstWeek() && fixedDate >= (nextJan1st - 7)) { // The first days forms a week in which the date is included. weekOfYear = 1; } } } internalSet(WEEK_OF_YEAR, weekOfYear); internalSet(WEEK_OF_MONTH, getWeekNumber(fixedDateMonth1, fixedDate)); mask |= (DAY_OF_YEAR_MASK|WEEK_OF_YEAR_MASK|WEEK_OF_MONTH_MASK|DAY_OF_WEEK_IN_MONTH_MASK); } return mask; } /** {@collect.stats} * {@description.open} * Returns the number of weeks in a period between fixedDay1 and * fixedDate. The getFirstDayOfWeek-getMinimalDaysInFirstWeek rule * is applied to calculate the number of weeks. * {@description.close} * * @param fixedDay1 the fixed date of the first day of the period * @param fixedDate the fixed date of the last day of the period * @return the number of weeks of the given period */ private final int getWeekNumber(long fixedDay1, long fixedDate) { // We can always use `gcal' since Julian and Gregorian are the // same thing for this calculation. long fixedDay1st = gcal.getDayOfWeekDateOnOrBefore(fixedDay1 + 6, getFirstDayOfWeek()); int ndays = (int)(fixedDay1st - fixedDay1); assert ndays <= 7; if (ndays >= getMinimalDaysInFirstWeek()) { fixedDay1st -= 7; } int normalizedDayOfPeriod = (int)(fixedDate - fixedDay1st); if (normalizedDayOfPeriod >= 0) { return normalizedDayOfPeriod / 7 + 1; } return CalendarUtils.floorDivide(normalizedDayOfPeriod, 7) + 1; } /** {@collect.stats} * {@description.open} * Converts calendar field values to the time value (millisecond * offset from the <a href="Calendar.html#Epoch">Epoch</a>). * {@description.close} * * @exception IllegalArgumentException if any calendar fields are invalid. */ protected void computeTime() { // In non-lenient mode, perform brief checking of calendar // fields which have been set externally. Through this // checking, the field values are stored in originalFields[] // to see if any of them are normalized later. if (!isLenient()) { if (originalFields == null) { originalFields = new int[FIELD_COUNT]; } for (int field = 0; field < FIELD_COUNT; field++) { int value = internalGet(field); if (isExternallySet(field)) { // Quick validation for any out of range values if (value < getMinimum(field) || value > getMaximum(field)) { throw new IllegalArgumentException(getFieldName(field)); } } originalFields[field] = value; } } // Let the super class determine which calendar fields to be // used to calculate the time. int fieldMask = selectFields(); // The year defaults to the epoch start. We don't check // fieldMask for YEAR because YEAR is a mandatory field to // determine the date. int year = isSet(YEAR) ? internalGet(YEAR) : EPOCH_YEAR; int era = internalGetEra(); if (era == BCE) { year = 1 - year; } else if (era != CE) { // Even in lenient mode we disallow ERA values other than CE & BCE. // (The same normalization rule as add()/roll() could be // applied here in lenient mode. But this checking is kept // unchanged for compatibility as of 1.5.) throw new IllegalArgumentException("Invalid era"); } // If year is 0 or negative, we need to set the ERA value later. if (year <= 0 && !isSet(ERA)) { fieldMask |= ERA_MASK; setFieldsComputed(ERA_MASK); } // Calculate the time of day. We rely on the convention that // an UNSET field has 0. long timeOfDay = 0; if (isFieldSet(fieldMask, HOUR_OF_DAY)) { timeOfDay += (long) internalGet(HOUR_OF_DAY); } else { timeOfDay += internalGet(HOUR); // The default value of AM_PM is 0 which designates AM. if (isFieldSet(fieldMask, AM_PM)) { timeOfDay += 12 * internalGet(AM_PM); } } timeOfDay *= 60; timeOfDay += internalGet(MINUTE); timeOfDay *= 60; timeOfDay += internalGet(SECOND); timeOfDay *= 1000; timeOfDay += internalGet(MILLISECOND); // Convert the time of day to the number of days and the // millisecond offset from midnight. long fixedDate = timeOfDay / ONE_DAY; timeOfDay %= ONE_DAY; while (timeOfDay < 0) { timeOfDay += ONE_DAY; --fixedDate; } // Calculate the fixed date since January 1, 1 (Gregorian). calculateFixedDate: { long gfd, jfd; if (year > gregorianCutoverYear && year > gregorianCutoverYearJulian) { gfd = fixedDate + getFixedDate(gcal, year, fieldMask); if (gfd >= gregorianCutoverDate) { fixedDate = gfd; break calculateFixedDate; } jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask); } else if (year < gregorianCutoverYear && year < gregorianCutoverYearJulian) { jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask); if (jfd < gregorianCutoverDate) { fixedDate = jfd; break calculateFixedDate; } gfd = jfd; } else { gfd = fixedDate + getFixedDate(gcal, year, fieldMask); jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask); } // Now we have to determine which calendar date it is. if (gfd >= gregorianCutoverDate) { if (jfd >= gregorianCutoverDate) { fixedDate = gfd; } else { // The date is in an "overlapping" period. No way // to disambiguate it. Determine it using the // previous date calculation. if (calsys == gcal || calsys == null) { fixedDate = gfd; } else { fixedDate = jfd; } } } else { if (jfd < gregorianCutoverDate) { fixedDate = jfd; } else { // The date is in a "missing" period. if (!isLenient()) { throw new IllegalArgumentException("the specified date doesn't exist"); } // Take the Julian date for compatibility, which // will produce a Gregorian date. fixedDate = jfd; } } } // millis represents local wall-clock time in milliseconds. long millis = (fixedDate - EPOCH_OFFSET) * ONE_DAY + timeOfDay; // Compute the time zone offset and DST offset. There are two potential // ambiguities here. We'll assume a 2:00 am (wall time) switchover time // for discussion purposes here. // 1. The transition into DST. Here, a designated time of 2:00 am - 2:59 am // can be in standard or in DST depending. However, 2:00 am is an invalid // representation (the representation jumps from 1:59:59 am Std to 3:00:00 am DST). // We assume standard time. // 2. The transition out of DST. Here, a designated time of 1:00 am - 1:59 am // can be in standard or DST. Both are valid representations (the rep // jumps from 1:59:59 DST to 1:00:00 Std). // Again, we assume standard time. // We use the TimeZone object, unless the user has explicitly set the ZONE_OFFSET // or DST_OFFSET fields; then we use those fields. TimeZone zone = getZone(); if (zoneOffsets == null) { zoneOffsets = new int[2]; } int tzMask = fieldMask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK); if (tzMask != (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) { if (zone instanceof ZoneInfo) { ((ZoneInfo)zone).getOffsetsByWall(millis, zoneOffsets); } else { int gmtOffset = isFieldSet(fieldMask, ZONE_OFFSET) ? internalGet(ZONE_OFFSET) : zone.getRawOffset(); zone.getOffsets(millis - gmtOffset, zoneOffsets); } } if (tzMask != 0) { if (isFieldSet(tzMask, ZONE_OFFSET)) { zoneOffsets[0] = internalGet(ZONE_OFFSET); } if (isFieldSet(tzMask, DST_OFFSET)) { zoneOffsets[1] = internalGet(DST_OFFSET); } } // Adjust the time zone offset values to get the UTC time. millis -= zoneOffsets[0] + zoneOffsets[1]; // Set this calendar's time in milliseconds time = millis; int mask = computeFields(fieldMask | getSetStateFields(), tzMask); if (!isLenient()) { for (int field = 0; field < FIELD_COUNT; field++) { if (!isExternallySet(field)) { continue; } if (originalFields[field] != internalGet(field)) { // Restore the original field values System.arraycopy(originalFields, 0, fields, 0, fields.length); throw new IllegalArgumentException(getFieldName(field)); } } } setFieldsNormalized(mask); } /** {@collect.stats} * {@description.open} * Computes the fixed date under either the Gregorian or the * Julian calendar, using the given year and the specified calendar fields. * {@description.close} * * @param cal the CalendarSystem to be used for the date calculation * @param year the normalized year number, with 0 indicating the * year 1 BCE, -1 indicating 2 BCE, etc. * @param fieldMask the calendar fields to be used for the date calculation * @return the fixed date * @see Calendar#selectFields */ private long getFixedDate(BaseCalendar cal, int year, int fieldMask) { int month = JANUARY; if (isFieldSet(fieldMask, MONTH)) { // No need to check if MONTH has been set (no isSet(MONTH) // call) since its unset value happens to be JANUARY (0). month = internalGet(MONTH); // If the month is out of range, adjust it into range if (month > DECEMBER) { year += month / 12; month %= 12; } else if (month < JANUARY) { int[] rem = new int[1]; year += CalendarUtils.floorDivide(month, 12, rem); month = rem[0]; } } // Get the fixed date since Jan 1, 1 (Gregorian). We are on // the first day of either `month' or January in 'year'. long fixedDate = cal.getFixedDate(year, month + 1, 1, cal == gcal ? gdate : null); if (isFieldSet(fieldMask, MONTH)) { // Month-based calculations if (isFieldSet(fieldMask, DAY_OF_MONTH)) { // We are on the first day of the month. Just add the // offset if DAY_OF_MONTH is set. If the isSet call // returns false, that means DAY_OF_MONTH has been // selected just because of the selected // combination. We don't need to add any since the // default value is the 1st. if (isSet(DAY_OF_MONTH)) { // To avoid underflow with DAY_OF_MONTH-1, add // DAY_OF_MONTH, then subtract 1. fixedDate += internalGet(DAY_OF_MONTH); fixedDate--; } } else { if (isFieldSet(fieldMask, WEEK_OF_MONTH)) { long firstDayOfWeek = cal.getDayOfWeekDateOnOrBefore(fixedDate + 6, getFirstDayOfWeek()); // If we have enough days in the first week, then // move to the previous week. if ((firstDayOfWeek - fixedDate) >= getMinimalDaysInFirstWeek()) { firstDayOfWeek -= 7; } if (isFieldSet(fieldMask, DAY_OF_WEEK)) { firstDayOfWeek = cal.getDayOfWeekDateOnOrBefore(firstDayOfWeek + 6, internalGet(DAY_OF_WEEK)); } // In lenient mode, we treat days of the previous // months as a part of the specified // WEEK_OF_MONTH. See 4633646. fixedDate = firstDayOfWeek + 7 * (internalGet(WEEK_OF_MONTH) - 1); } else { int dayOfWeek; if (isFieldSet(fieldMask, DAY_OF_WEEK)) { dayOfWeek = internalGet(DAY_OF_WEEK); } else { dayOfWeek = getFirstDayOfWeek(); } // We are basing this on the day-of-week-in-month. The only // trickiness occurs if the day-of-week-in-month is // negative. int dowim; if (isFieldSet(fieldMask, DAY_OF_WEEK_IN_MONTH)) { dowim = internalGet(DAY_OF_WEEK_IN_MONTH); } else { dowim = 1; } if (dowim >= 0) { fixedDate = cal.getDayOfWeekDateOnOrBefore(fixedDate + (7 * dowim) - 1, dayOfWeek); } else { // Go to the first day of the next week of // the specified week boundary. int lastDate = monthLength(month, year) + (7 * (dowim + 1)); // Then, get the day of week date on or before the last date. fixedDate = cal.getDayOfWeekDateOnOrBefore(fixedDate + lastDate - 1, dayOfWeek); } } } } else { if (year == gregorianCutoverYear && cal == gcal && fixedDate < gregorianCutoverDate && gregorianCutoverYear != gregorianCutoverYearJulian) { // January 1 of the year doesn't exist. Use // gregorianCutoverDate as the first day of the // year. fixedDate = gregorianCutoverDate; } // We are on the first day of the year. if (isFieldSet(fieldMask, DAY_OF_YEAR)) { // Add the offset, then subtract 1. (Make sure to avoid underflow.) fixedDate += internalGet(DAY_OF_YEAR); fixedDate--; } else { long firstDayOfWeek = cal.getDayOfWeekDateOnOrBefore(fixedDate + 6, getFirstDayOfWeek()); // If we have enough days in the first week, then move // to the previous week. if ((firstDayOfWeek - fixedDate) >= getMinimalDaysInFirstWeek()) { firstDayOfWeek -= 7; } if (isFieldSet(fieldMask, DAY_OF_WEEK)) { int dayOfWeek = internalGet(DAY_OF_WEEK); if (dayOfWeek != getFirstDayOfWeek()) { firstDayOfWeek = cal.getDayOfWeekDateOnOrBefore(firstDayOfWeek + 6, dayOfWeek); } } fixedDate = firstDayOfWeek + 7 * ((long)internalGet(WEEK_OF_YEAR) - 1); } } return fixedDate; } /** {@collect.stats} * {@description.open} * Returns this object if it's normalized (all fields and time are * in sync). Otherwise, a cloned object is returned after calling * complete() in lenient mode. * {@description.close} */ private final GregorianCalendar getNormalizedCalendar() { GregorianCalendar gc; if (isFullyNormalized()) { gc = this; } else { // Create a clone and normalize the calendar fields gc = (GregorianCalendar) this.clone(); gc.setLenient(true); gc.complete(); } return gc; } /** {@collect.stats} * {@description.open} * Returns the Julian calendar system instance (singleton). 'jcal' * and 'jeras' are set upon the return. * {@description.close} */ synchronized private static final BaseCalendar getJulianCalendarSystem() { if (jcal == null) { jcal = (JulianCalendar) CalendarSystem.forName("julian"); jeras = jcal.getEras(); } return jcal; } /** {@collect.stats} * {@description.open} * Returns the calendar system for dates before the cutover date * in the cutover year. If the cutover date is January 1, the * method returns Gregorian. Otherwise, Julian. * {@description.close} */ private BaseCalendar getCutoverCalendarSystem() { CalendarDate date = getGregorianCutoverDate(); if (date.getMonth() == BaseCalendar.JANUARY && date.getDayOfMonth() == 1) { return gcal; } return getJulianCalendarSystem(); } /** {@collect.stats} * {@description.open} * Determines if the specified year (normalized) is the Gregorian * cutover year. * {@description.close} * {@property.open internal} * This object must have been normalized. * {@property.close} */ private final boolean isCutoverYear(int normalizedYear) { int cutoverYear = (calsys == gcal) ? gregorianCutoverYear : gregorianCutoverYearJulian; return normalizedYear == cutoverYear; } /** {@collect.stats} * {@description.open} * Returns the fixed date of the first day of the year (usually * January 1) before the specified date. * {@description.close} * * @param date the date for which the first day of the year is * calculated. The date has to be in the cut-over year (Gregorian * or Julian). * @param fixedDate the fixed date representation of the date */ private final long getFixedDateJan1(BaseCalendar.Date date, long fixedDate) { assert date.getNormalizedYear() == gregorianCutoverYear || date.getNormalizedYear() == gregorianCutoverYearJulian; if (gregorianCutoverYear != gregorianCutoverYearJulian) { if (fixedDate >= gregorianCutoverDate) { // Dates before the cutover date don't exist // in the same (Gregorian) year. So, no // January 1 exists in the year. Use the // cutover date as the first day of the year. return gregorianCutoverDate; } } // January 1 of the normalized year should exist. BaseCalendar jcal = getJulianCalendarSystem(); return jcal.getFixedDate(date.getNormalizedYear(), BaseCalendar.JANUARY, 1, null); } /** {@collect.stats} * {@description.open} * Returns the fixed date of the first date of the month (usually * the 1st of the month) before the specified date. * {@description.close} * * @param date the date for which the first day of the month is * calculated. The date has to be in the cut-over year (Gregorian * or Julian). * @param fixedDate the fixed date representation of the date */ private final long getFixedDateMonth1(BaseCalendar.Date date, long fixedDate) { assert date.getNormalizedYear() == gregorianCutoverYear || date.getNormalizedYear() == gregorianCutoverYearJulian; BaseCalendar.Date gCutover = getGregorianCutoverDate(); if (gCutover.getMonth() == BaseCalendar.JANUARY && gCutover.getDayOfMonth() == 1) { // The cutover happened on January 1. return fixedDate - date.getDayOfMonth() + 1; } long fixedDateMonth1; // The cutover happened sometime during the year. if (date.getMonth() == gCutover.getMonth()) { // The cutover happened in the month. BaseCalendar.Date jLastDate = getLastJulianDate(); if (gregorianCutoverYear == gregorianCutoverYearJulian && gCutover.getMonth() == jLastDate.getMonth()) { // The "gap" fits in the same month. fixedDateMonth1 = jcal.getFixedDate(date.getNormalizedYear(), date.getMonth(), 1, null); } else { // Use the cutover date as the first day of the month. fixedDateMonth1 = gregorianCutoverDate; } } else { // The cutover happened before the month. fixedDateMonth1 = fixedDate - date.getDayOfMonth() + 1; } return fixedDateMonth1; } /** {@collect.stats} * {@description.open} * Returns a CalendarDate produced from the specified fixed date. * {@description.close} * * @param fd the fixed date */ private final BaseCalendar.Date getCalendarDate(long fd) { BaseCalendar cal = (fd >= gregorianCutoverDate) ? gcal : getJulianCalendarSystem(); BaseCalendar.Date d = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE); cal.getCalendarDateFromFixedDate(d, fd); return d; } /** {@collect.stats} * {@description.open} * Returns the Gregorian cutover date as a BaseCalendar.Date. The * date is a Gregorian date. * {@description.close} */ private final BaseCalendar.Date getGregorianCutoverDate() { return getCalendarDate(gregorianCutoverDate); } /** {@collect.stats} * {@description.open} * Returns the day before the Gregorian cutover date as a * BaseCalendar.Date. The date is a Julian date. * {@description.close} */ private final BaseCalendar.Date getLastJulianDate() { return getCalendarDate(gregorianCutoverDate - 1); } /** {@collect.stats} * {@description.open} * Returns the length of the specified month in the specified * year. * {@description.close} * {@property.open internal} * The year number must be normalized. * {@property.close} * * @see #isLeapYear(int) */ private final int monthLength(int month, int year) { return isLeapYear(year) ? LEAP_MONTH_LENGTH[month] : MONTH_LENGTH[month]; } /** {@collect.stats} * {@description.open} * Returns the length of the specified month in the year provided * by internalGet(YEAR). * {@description.close} * * @see #isLeapYear(int) */ private final int monthLength(int month) { int year = internalGet(YEAR); if (internalGetEra() == BCE) { year = 1 - year; } return monthLength(month, year); } private final int actualMonthLength() { int year = cdate.getNormalizedYear(); if (year != gregorianCutoverYear && year != gregorianCutoverYearJulian) { return calsys.getMonthLength(cdate); } BaseCalendar.Date date = (BaseCalendar.Date) cdate.clone(); long fd = calsys.getFixedDate(date); long month1 = getFixedDateMonth1(date, fd); long next1 = month1 + calsys.getMonthLength(date); if (next1 < gregorianCutoverDate) { return (int)(next1 - month1); } if (cdate != gdate) { date = (BaseCalendar.Date) gcal.newCalendarDate(TimeZone.NO_TIMEZONE); } gcal.getCalendarDateFromFixedDate(date, next1); next1 = getFixedDateMonth1(date, next1); return (int)(next1 - month1); } /** {@collect.stats} * {@description.open} * Returns the length (in days) of the specified year. * {@description.close} * {@property.open internal} * The year * must be normalized. * {@property.close} */ private final int yearLength(int year) { return isLeapYear(year) ? 366 : 365; } /** {@collect.stats} * {@description.open} * Returns the length (in days) of the year provided by * internalGet(YEAR). * {@description.close} */ private final int yearLength() { int year = internalGet(YEAR); if (internalGetEra() == BCE) { year = 1 - year; } return yearLength(year); } /** {@collect.stats} * {@description.open} * After adjustments such as add(MONTH), add(YEAR), we don't want the * month to jump around. E.g., we don't want Jan 31 + 1 month to go to Mar * 3, we want it to go to Feb 28. Adjustments which might run into this * problem call this method to retain the proper month. * {@description.close} */ private final void pinDayOfMonth() { int year = internalGet(YEAR); int monthLen; if (year > gregorianCutoverYear || year < gregorianCutoverYearJulian) { monthLen = monthLength(internalGet(MONTH)); } else { GregorianCalendar gc = getNormalizedCalendar(); monthLen = gc.getActualMaximum(DAY_OF_MONTH); } int dom = internalGet(DAY_OF_MONTH); if (dom > monthLen) { set(DAY_OF_MONTH, monthLen); } } /** {@collect.stats} * {@description.open} * Returns the fixed date value of this object. * {@description.close} * {@property.open internal} * The time value and * calendar fields must be in synch. * {@property.close} */ private final long getCurrentFixedDate() { return (calsys == gcal) ? cachedFixedDate : calsys.getFixedDate(cdate); } /** {@collect.stats} * {@description.open} * Returns the new value after 'roll'ing the specified value and amount. * {@description.close} */ private static final int getRolledValue(int value, int amount, int min, int max) { assert value >= min && value <= max; int range = max - min + 1; amount %= range; int n = value + amount; if (n > max) { n -= range; } else if (n < min) { n += range; } assert n >= min && n <= max; return n; } /** {@collect.stats} * {@description.open} * Returns the ERA. We need a special method for this because the * default ERA is CE, but a zero (unset) ERA is BCE. * {@description.close} */ private final int internalGetEra() { return isSet(ERA) ? internalGet(ERA) : CE; } /** {@collect.stats} * {@description.open} * Updates internal state. * {@description.close} */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); if (gdate == null) { gdate = (BaseCalendar.Date) gcal.newCalendarDate(getZone()); cachedFixedDate = Long.MIN_VALUE; } setGregorianChange(gregorianCutover); } }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * This class provides a skeletal implementation of the {@link List} * interface to minimize the effort required to implement this interface * backed by a "random access" data store (such as an array). For sequential * access data (such as a linked list), {@link AbstractSequentialList} should * be used in preference to this class. * {@description.close} * * {@property.open unknown} * <p>To implement an unmodifiable list, the programmer needs only to extend * this class and provide implementations for the {@link #get(int)} and * {@link List#size() size()} methods. * {@property.close} * * {@property.open unknown} * <p>To implement a modifiable list, the programmer must additionally * override the {@link #set(int, Object) set(int, E)} method (which otherwise * throws an {@code UnsupportedOperationException}). If the list is * variable-size the programmer must additionally override the * {@link #add(int, Object) add(int, E)} and {@link #remove(int)} methods. * {@property.close} * * {@property.open formal:java.util.Collection_StandardConstructors} * <p>The programmer should generally provide a void (no argument) and collection * constructor, as per the recommendation in the {@link Collection} interface * specification. * {@property.close} * * {@description.open} * <p>Unlike the other abstract collection implementations, the programmer does * <i>not</i> have to provide an iterator implementation; the iterator and * list iterator are implemented by this class, on top of the "random access" * methods: * {@link #get(int)}, * {@link #set(int, Object) set(int, E)}, * {@link #add(int, Object) add(int, E)} and * {@link #remove(int)}. * * <p>The documentation for each non-abstract method in this class describes its * implementation in detail. Each of these methods may be overridden if the * collection being implemented admits a more efficient implementation. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @author Neal Gafter * @since 1.2 */ public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ protected AbstractList() { } /** {@collect.stats} * {@description.open} * Appends the specified element to the end of this list (optional * operation). * * <p>Lists that support this operation may place limitations on what * elements may be added to this list. In particular, some * lists will refuse to add null elements, and others will impose * restrictions on the type of elements that may be added. List * classes should clearly specify in their documentation any restrictions * on what elements may be added. * * <p>This implementation calls {@code add(size(), e)}. * * <p>Note that this implementation throws an * {@code UnsupportedOperationException} unless * {@link #add(int, Object) add(int, E)} is overridden. * {@description.close} * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) * @throws UnsupportedOperationException if the {@code add} operation * is not supported by this list * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws NullPointerException if the specified element is null and this * list does not permit null elements * @throws IllegalArgumentException if some property of this element * prevents it from being added to this list */ public boolean add(E e) { add(size(), e); return true; } /** {@collect.stats} * {@inheritDoc} * * @throws IndexOutOfBoundsException {@inheritDoc} */ abstract public E get(int index); /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation always throws an * {@code UnsupportedOperationException}. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation always throws an * {@code UnsupportedOperationException}. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation always throws an * {@code UnsupportedOperationException}. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { throw new UnsupportedOperationException(); } // Search Operations /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation first gets a list iterator (with * {@code listIterator()}). Then, it iterates over the list until the * specified element is found or the end of the list is reached. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public int indexOf(Object o) { ListIterator<E> e = listIterator(); if (o==null) { while (e.hasNext()) if (e.next()==null) return e.previousIndex(); } else { while (e.hasNext()) if (o.equals(e.next())) return e.previousIndex(); } return -1; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation first gets a list iterator that points to the end * of the list (with {@code listIterator(size())}). Then, it iterates * backwards over the list until the specified element is found, or the * beginning of the list is reached. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public int lastIndexOf(Object o) { ListIterator<E> e = listIterator(size()); if (o==null) { while (e.hasPrevious()) if (e.previous()==null) return e.nextIndex(); } else { while (e.hasPrevious()) if (o.equals(e.previous())) return e.nextIndex(); } return -1; } // Bulk Operations /** {@collect.stats} * {@description.open} * Removes all of the elements from this list (optional operation). * The list will be empty after this call returns. * * <p>This implementation calls {@code removeRange(0, size())}. * * <p>Note that this implementation throws an * {@code UnsupportedOperationException} unless {@code remove(int * index)} or {@code removeRange(int fromIndex, int toIndex)} is * overridden. * {@description.close} * * @throws UnsupportedOperationException if the {@code clear} operation * is not supported by this list */ public void clear() { removeRange(0, size()); } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation gets an iterator over the specified collection * and iterates over it, inserting the elements obtained from the * iterator into this list at the appropriate position, one at a time, * using {@code add(int, E)}. * Many implementations will override this method for efficiency. * * <p>Note that this implementation throws an * {@code UnsupportedOperationException} unless * {@link #add(int, Object) add(int, E)} is overridden. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); boolean modified = false; Iterator<? extends E> e = c.iterator(); while (e.hasNext()) { add(index++, e.next()); modified = true; } return modified; } // Iterators /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this list in proper sequence. * * <p>This implementation returns a straightforward implementation of the * iterator interface, relying on the backing list's {@code size()}, * {@code get(int)}, and {@code remove(int)} methods. * * <p>Note that the iterator returned by this method will throw an * {@link UnsupportedOperationException} in response to its * {@code remove} method unless the list's {@code remove(int)} method is * overridden. * * <p>This implementation can be made to throw runtime exceptions in the * face of concurrent modification, as described in the specification * for the (protected) {@link #modCount} field. * {@description.close} * * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { return new Itr(); } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation returns {@code listIterator(0)}. * {@description.close} * * @see #listIterator(int) */ public ListIterator<E> listIterator() { return listIterator(0); } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation returns a straightforward implementation of the * {@code ListIterator} interface that extends the implementation of the * {@code Iterator} interface returned by the {@code iterator()} method. * The {@code ListIterator} implementation relies on the backing list's * {@code get(int)}, {@code set(int, E)}, {@code add(int, E)} * and {@code remove(int)} methods. * * <p>Note that the list iterator returned by this implementation will * throw an {@link UnsupportedOperationException} in response to its * {@code remove}, {@code set} and {@code add} methods unless the * list's {@code remove(int)}, {@code set(int, E)}, and * {@code add(int, E)} methods are overridden. * * <p>This implementation can be made to throw runtime exceptions in the * face of concurrent modification, as described in the specification for * the (protected) {@link #modCount} field. * {@description.close} * * @throws IndexOutOfBoundsException {@inheritDoc} */ public ListIterator<E> listIterator(final int index) { rangeCheckForAdd(index); return new ListItr(index); } private class Itr implements Iterator<E> { /** {@collect.stats} * {@description.open} * Index of element to be returned by subsequent call to next. * {@description.close} */ int cursor = 0; /** {@collect.stats} * {@description.open} * Index of element returned by most recent call to next or * previous. Reset to -1 if this element is deleted by a call * to remove. * {@description.close} */ int lastRet = -1; /** {@collect.stats} * {@description.open} * The modCount value that the iterator believes that the backing * List should have. If this expectation is violated, the iterator * has detected concurrent modification. * {@description.close} */ int expectedModCount = modCount; public boolean hasNext() { return cursor != size(); } public E next() { checkForComodification(); try { int i = cursor; E next = get(i); lastRet = i; cursor = i + 1; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { cursor = index; } public boolean hasPrevious() { return cursor != 0; } public E previous() { checkForComodification(); try { int i = cursor - 1; E previous = get(i); lastRet = cursor = i; return previous; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } public int nextIndex() { return cursor; } public int previousIndex() { return cursor-1; } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.set(lastRet, e); expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; AbstractList.this.add(i, e); lastRet = -1; cursor = i + 1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation returns a list that subclasses * {@code AbstractList}. The subclass stores, in private fields, the * offset of the subList within the backing list, the size of the subList * (which can change over its lifetime), and the expected * {@code modCount} value of the backing list. There are two variants * of the subclass, one of which implements {@code RandomAccess}. * If this list implements {@code RandomAccess} the returned list will * be an instance of the subclass that implements {@code RandomAccess}. * * <p>The subclass's {@code set(int, E)}, {@code get(int)}, * {@code add(int, E)}, {@code remove(int)}, {@code addAll(int, * Collection)} and {@code removeRange(int, int)} methods all * delegate to the corresponding methods on the backing abstract list, * after bounds-checking the index and adjusting for the offset. The * {@code addAll(Collection c)} method merely returns {@code addAll(size, * c)}. * * <p>The {@code listIterator(int)} method returns a "wrapper object" * over a list iterator on the backing list, which is created with the * corresponding method on the backing list. The {@code iterator} method * merely returns {@code listIterator()}, and the {@code size} method * merely returns the subclass's {@code size} field. * * <p>All methods first check to see if the actual {@code modCount} of * the backing list is equal to its expected value, and throw a * {@code ConcurrentModificationException} if it is not. * {@description.close} * * @throws IndexOutOfBoundsException if an endpoint index value is out of range * {@code (fromIndex < 0 || toIndex > size)} * @throws IllegalArgumentException if the endpoint indices are out of order * {@code (fromIndex > toIndex)} */ public List<E> subList(int fromIndex, int toIndex) { return (this instanceof RandomAccess ? new RandomAccessSubList<E>(this, fromIndex, toIndex) : new SubList<E>(this, fromIndex, toIndex)); } // Comparison and hashing /** {@collect.stats} * {@description.open} * Compares the specified object with this list for equality. Returns * {@code true} if and only if the specified object is also a list, both * lists have the same size, and all corresponding pairs of elements in * the two lists are <i>equal</i>. (Two elements {@code e1} and * {@code e2} are <i>equal</i> if {@code (e1==null ? e2==null : * e1.equals(e2))}.) In other words, two lists are defined to be * equal if they contain the same elements in the same order.<p> * * This implementation first checks if the specified object is this * list. If so, it returns {@code true}; if not, it checks if the * specified object is a list. If not, it returns {@code false}; if so, * it iterates over both lists, comparing corresponding pairs of elements. * If any comparison returns {@code false}, this method returns * {@code false}. If either iterator runs out of elements before the * other it returns {@code false} (as the lists are of unequal length); * otherwise it returns {@code true} when the iterations complete. * {@description.close} * * @param o the object to be compared for equality with this list * @return {@code true} if the specified object is equal to this list */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof List)) return false; ListIterator<E> e1 = listIterator(); ListIterator e2 = ((List) o).listIterator(); while(e1.hasNext() && e2.hasNext()) { E o1 = e1.next(); Object o2 = e2.next(); if (!(o1==null ? o2==null : o1.equals(o2))) return false; } return !(e1.hasNext() || e2.hasNext()); } /** {@collect.stats} * {@description.open} * Returns the hash code value for this list. * * <p>This implementation uses exactly the code that is used to define the * list hash function in the documentation for the {@link List#hashCode} * method. * {@description.close} * * @return the hash code value for this list */ public int hashCode() { int hashCode = 1; for (E e : this) hashCode = 31*hashCode + (e==null ? 0 : e.hashCode()); return hashCode; } /** {@collect.stats} * {@description.open} * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). * This call shortens the list by {@code (toIndex - fromIndex)} elements. * (If {@code toIndex==fromIndex}, this operation has no effect.) * * <p>This method is called by the {@code clear} operation on this list * and its subLists. Overriding this method to take advantage of * the internals of the list implementation can <i>substantially</i> * improve the performance of the {@code clear} operation on this list * and its subLists. * * <p>This implementation gets a list iterator positioned before * {@code fromIndex}, and repeatedly calls {@code ListIterator.next} * followed by {@code ListIterator.remove} until the entire range has * been removed. <b>Note: if {@code ListIterator.remove} requires linear * time, this implementation requires quadratic time.</b> * {@description.close} * * @param fromIndex index of first element to be removed * @param toIndex index after last element to be removed */ protected void removeRange(int fromIndex, int toIndex) { ListIterator<E> it = listIterator(fromIndex); for (int i=0, n=toIndex-fromIndex; i<n; i++) { it.next(); it.remove(); } } /** {@collect.stats} * {@description.open} * The number of times this list has been <i>structurally modified</i>. * Structural modifications are those that change the size of the * list, or otherwise perturb it in such a fashion that iterations in * progress may yield incorrect results. * * <p>This field is used by the iterator and list iterator implementation * returned by the {@code iterator} and {@code listIterator} methods. * If the value of this field changes unexpectedly, the iterator (or list * iterator) will throw a {@code ConcurrentModificationException} in * response to the {@code next}, {@code remove}, {@code previous}, * {@code set} or {@code add} operations. This provides * <i>fail-fast</i> behavior, rather than non-deterministic behavior in * the face of concurrent modification during iteration. * * <p><b>Use of this field by subclasses is optional.</b> If a subclass * wishes to provide fail-fast iterators (and list iterators), then it * merely has to increment this field in its {@code add(int, E)} and * {@code remove(int)} methods (and any other methods that it overrides * that result in structural modifications to the list). A single call to * {@code add(int, E)} or {@code remove(int)} must add no more than * one to this field, or the iterators (and list iterators) will throw * bogus {@code ConcurrentModificationExceptions}. If an implementation * does not wish to provide fail-fast iterators, this field may be * ignored. * {@description.close} */ protected transient int modCount = 0; private void rangeCheckForAdd(int index) { if (index < 0 || index > size()) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size(); } } class SubList<E> extends AbstractList<E> { private final AbstractList<E> l; private final int offset; private int size; SubList(AbstractList<E> list, int fromIndex, int toIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > list.size()) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); l = list; offset = fromIndex; size = toIndex - fromIndex; this.modCount = l.modCount; } public E set(int index, E element) { rangeCheck(index); checkForComodification(); return l.set(index+offset, element); } public E get(int index) { rangeCheck(index); checkForComodification(); return l.get(index+offset); } public int size() { checkForComodification(); return size; } public void add(int index, E element) { rangeCheckForAdd(index); checkForComodification(); l.add(index+offset, element); this.modCount = l.modCount; size++; } public E remove(int index) { rangeCheck(index); checkForComodification(); E result = l.remove(index+offset); this.modCount = l.modCount; size--; return result; } protected void removeRange(int fromIndex, int toIndex) { checkForComodification(); l.removeRange(fromIndex+offset, toIndex+offset); this.modCount = l.modCount; size -= (toIndex-fromIndex); } public boolean addAll(Collection<? extends E> c) { return addAll(size, c); } public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); int cSize = c.size(); if (cSize==0) return false; checkForComodification(); l.addAll(offset+index, c); this.modCount = l.modCount; size += cSize; return true; } public Iterator<E> iterator() { return listIterator(); } public ListIterator<E> listIterator(final int index) { checkForComodification(); rangeCheckForAdd(index); return new ListIterator<E>() { private final ListIterator<E> i = l.listIterator(index+offset); public boolean hasNext() { return nextIndex() < size; } public E next() { if (hasNext()) return i.next(); else throw new NoSuchElementException(); } public boolean hasPrevious() { return previousIndex() >= 0; } public E previous() { if (hasPrevious()) return i.previous(); else throw new NoSuchElementException(); } public int nextIndex() { return i.nextIndex() - offset; } public int previousIndex() { return i.previousIndex() - offset; } public void remove() { i.remove(); SubList.this.modCount = l.modCount; size--; } public void set(E e) { i.set(e); } public void add(E e) { i.add(e); SubList.this.modCount = l.modCount; size++; } }; } public List<E> subList(int fromIndex, int toIndex) { return new SubList<E>(this, fromIndex, toIndex); } private void rangeCheck(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void rangeCheckForAdd(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } private void checkForComodification() { if (this.modCount != l.modCount) throw new ConcurrentModificationException(); } } class RandomAccessSubList<E> extends SubList<E> implements RandomAccess { RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) { super(list, fromIndex, toIndex); } public List<E> subList(int fromIndex, int toIndex) { return new RandomAccessSubList<E>(this, fromIndex, toIndex); } }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; import java.lang.reflect.Array; /** {@collect.stats} * {@description.open} * This class consists exclusively of static methods that operate on or return * collections. It contains polymorphic algorithms that operate on * collections, "wrappers", which return a new collection backed by a * specified collection, and a few other odds and ends. * * <p>The methods of this class all throw a <tt>NullPointerException</tt> * if the collections or class objects provided to them are null. * * <p>The documentation for the polymorphic algorithms contained in this class * generally includes a brief description of the <i>implementation</i>. Such * descriptions should be regarded as <i>implementation notes</i>, rather than * parts of the <i>specification</i>. Implementors should feel free to * substitute other algorithms, so long as the specification itself is adhered * to. (For example, the algorithm used by <tt>sort</tt> does not have to be * a mergesort, but it does have to be <i>stable</i>.) * * <p>The "destructive" algorithms contained in this class, that is, the * algorithms that modify the collection on which they operate, are specified * to throw <tt>UnsupportedOperationException</tt> if the collection does not * support the appropriate mutation primitive(s), such as the <tt>set</tt> * method. These algorithms may, but are not required to, throw this * exception if an invocation would have no effect on the collection. For * example, invoking the <tt>sort</tt> method on an unmodifiable list that is * already sorted may or may not throw <tt>UnsupportedOperationException</tt>. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @author Neal Gafter * @see Collection * @see Set * @see List * @see Map * @since 1.2 */ public class Collections { // Suppresses default constructor, ensuring non-instantiability. private Collections() { } // Algorithms /* * Tuning parameters for algorithms - Many of the List algorithms have * two implementations, one of which is appropriate for RandomAccess * lists, the other for "sequential." Often, the random access variant * yields better performance on small sequential access lists. The * tuning parameters below determine the cutoff point for what constitutes * a "small" sequential access list for each algorithm. The values below * were empirically determined to work well for LinkedList. Hopefully * they should be reasonable for other sequential access List * implementations. Those doing performance work on this code would * do well to validate the values of these parameters from time to time. * (The first word of each tuning parameter name is the algorithm to which * it applies.) */ private static final int BINARYSEARCH_THRESHOLD = 5000; private static final int REVERSE_THRESHOLD = 18; private static final int SHUFFLE_THRESHOLD = 5; private static final int FILL_THRESHOLD = 25; private static final int ROTATE_THRESHOLD = 100; private static final int COPY_THRESHOLD = 10; private static final int REPLACEALL_THRESHOLD = 11; private static final int INDEXOFSUBLIST_THRESHOLD = 35; /** {@collect.stats} * {@description.open} * Sorts the specified list into ascending order, according to the * <i>natural ordering</i> of its elements. * {@description.close} * {@property.open formal:java.util.Collections_ImplementComparable} * All elements in the list must * implement the <tt>Comparable</tt> interface. Furthermore, all elements * in the list must be <i>mutually comparable</i> (that is, * <tt>e1.compareTo(e2)</tt> must not throw a <tt>ClassCastException</tt> * for any elements <tt>e1</tt> and <tt>e2</tt> in the list).<p> * {@property.close} * * {@description.open} * This sort is guaranteed to be <i>stable</i>: equal elements will * not be reordered as a result of the sort.<p> * {@description.close} * * {@property.open uncheckable} * The specified list must be modifiable, but need not be resizable.<p> * {@property.close} * * {@description.open} * The sorting algorithm is a modified mergesort (in which the merge is * omitted if the highest element in the low sublist is less than the * lowest element in the high sublist). This algorithm offers guaranteed * n log(n) performance. * * This implementation dumps the specified list into an array, sorts * the array, and iterates over the list resetting each element * from the corresponding position in the array. This avoids the * n<sup>2</sup> log(n) performance that would result from attempting * to sort a linked list in place. * {@description.close} * * @param list the list to be sorted. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> (for example, strings and integers). * @throws UnsupportedOperationException if the specified list's * list-iterator does not support the <tt>set</tt> operation. * @see Comparable */ public static <T extends Comparable<? super T>> void sort(List<T> list) { Object[] a = list.toArray(); Arrays.sort(a); ListIterator<T> i = list.listIterator(); for (int j=0; j<a.length; j++) { i.next(); i.set((T)a[j]); } } /** {@collect.stats} * {@description.open} * Sorts the specified list according to the order induced by the * specified comparator. * {@description.close} * {@property.open formal:java.util.Collections_Comparable} * All elements in the list must be <i>mutually * comparable</i> using the specified comparator (that is, * <tt>c.compare(e1, e2)</tt> must not throw a <tt>ClassCastException</tt> * for any elements <tt>e1</tt> and <tt>e2</tt> in the list).<p> * {@property.close} * * {@description.open} * This sort is guaranteed to be <i>stable</i>: equal elements will * not be reordered as a result of the sort.<p> * * The sorting algorithm is a modified mergesort (in which the merge is * omitted if the highest element in the low sublist is less than the * lowest element in the high sublist). This algorithm offers guaranteed * n log(n) performance. * {@description.close} * * {@property.open uncheckable} * The specified list must be modifiable, but need not be resizable. * {@property.close} * {@description.open} * This implementation dumps the specified list into an array, sorts * the array, and iterates over the list resetting each element * from the corresponding position in the array. This avoids the * n<sup>2</sup> log(n) performance that would result from attempting * to sort a linked list in place. * {@description.close} * * @param list the list to be sorted. * @param c the comparator to determine the order of the list. A * <tt>null</tt> value indicates that the elements' <i>natural * ordering</i> should be used. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> using the specified comparator. * @throws UnsupportedOperationException if the specified list's * list-iterator does not support the <tt>set</tt> operation. * @see Comparator */ public static <T> void sort(List<T> list, Comparator<? super T> c) { Object[] a = list.toArray(); Arrays.sort(a, (Comparator)c); ListIterator i = list.listIterator(); for (int j=0; j<a.length; j++) { i.next(); i.set(a[j]); } } /** {@collect.stats} * {@description.open} * Searches the specified list for the specified object using the binary * search algorithm. * {@description.close} * {@property.open formal:java.util.Collections_SortBeforeBinarySearch} * The list must be sorted into ascending order * according to the {@linkplain Comparable natural ordering} of its * elements (as by the {@link #sort(List)} method) prior to making this * call. If it is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the list * contains multiple elements equal to the specified object, there is no * guarantee which one will be found. * * <p>This method runs in log(n) time for a "random access" list (which * provides near-constant-time positional access). If the specified list * does not implement the {@link RandomAccess} interface and is large, * this method will do an iterator-based binary search that performs * O(n) link traversals and O(log n) element comparisons. * {@description.close} * * @param list the list to be searched. * @param key the key to be searched for. * @return the index of the search key, if it is contained in the list; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the list: the index of the first * element greater than the key, or <tt>list.size()</tt> if all * elements in the list are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> (for example, strings and * integers), or the search key is not mutually comparable * with the elements of the list. */ public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) { if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) return Collections.indexedBinarySearch(list, key); else return Collections.iteratorBinarySearch(list, key); } private static <T> int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) { int low = 0; int high = list.size()-1; while (low <= high) { int mid = (low + high) >>> 1; Comparable<? super T> midVal = list.get(mid); int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } private static <T> int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key) { int low = 0; int high = list.size()-1; ListIterator<? extends Comparable<? super T>> i = list.listIterator(); while (low <= high) { int mid = (low + high) >>> 1; Comparable<? super T> midVal = get(i, mid); int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } /** {@collect.stats} * {@description.open} * Gets the ith element from the given list by repositioning the specified * list listIterator. * {@description.close} */ private static <T> T get(ListIterator<? extends T> i, int index) { T obj = null; int pos = i.nextIndex(); if (pos <= index) { do { obj = i.next(); } while (pos++ < index); } else { do { obj = i.previous(); } while (--pos > index); } return obj; } /** {@collect.stats} * {@description.open} * Searches the specified list for the specified object using the binary * search algorithm. * {@description.close} * {@property.open formal:java.util.Collections_SortBeforeBinarySearch} * The list must be sorted into ascending order * according to the specified comparator (as by the * {@link #sort(List, Comparator) sort(List, Comparator)} * method), prior to making this call. If it is * not sorted, the results are undefined. * {@property.close} * {@description.open} * If the list contains multiple * elements equal to the specified object, there is no guarantee which one * will be found. * * <p>This method runs in log(n) time for a "random access" list (which * provides near-constant-time positional access). If the specified list * does not implement the {@link RandomAccess} interface and is large, * this method will do an iterator-based binary search that performs * O(n) link traversals and O(log n) element comparisons. * {@description.close} * * @param list the list to be searched. * @param key the key to be searched for. * @param c the comparator by which the list is ordered. * A <tt>null</tt> value indicates that the elements' * {@linkplain Comparable natural ordering} should be used. * @return the index of the search key, if it is contained in the list; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the list: the index of the first * element greater than the key, or <tt>list.size()</tt> if all * elements in the list are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> using the specified comparator, * or the search key is not mutually comparable with the * elements of the list using this comparator. */ public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) { if (c==null) return binarySearch((List) list, key); if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) return Collections.indexedBinarySearch(list, key, c); else return Collections.iteratorBinarySearch(list, key, c); } private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) { int low = 0; int high = l.size()-1; while (low <= high) { int mid = (low + high) >>> 1; T midVal = l.get(mid); int cmp = c.compare(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) { int low = 0; int high = l.size()-1; ListIterator<? extends T> i = l.listIterator(); while (low <= high) { int mid = (low + high) >>> 1; T midVal = get(i, mid); int cmp = c.compare(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } private interface SelfComparable extends Comparable<SelfComparable> {} /** {@collect.stats} * {@description.open} * Reverses the order of the elements in the specified list.<p> * * This method runs in linear time. * {@description.close} * * @param list the list whose elements are to be reversed. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the <tt>set</tt> operation. */ public static void reverse(List<?> list) { int size = list.size(); if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) { for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--) swap(list, i, j); } else { ListIterator fwd = list.listIterator(); ListIterator rev = list.listIterator(size); for (int i=0, mid=list.size()>>1; i<mid; i++) { Object tmp = fwd.next(); fwd.set(rev.previous()); rev.set(tmp); } } } /** {@collect.stats} * {@description.open} * Randomly permutes the specified list using a default source of * randomness. All permutations occur with approximately equal * likelihood.<p> * * The hedge "approximately" is used in the foregoing description because * default source of randomness is only approximately an unbiased source * of independently chosen bits. If it were a perfect source of randomly * chosen bits, then the algorithm would choose permutations with perfect * uniformity.<p> * * This implementation traverses the list backwards, from the last element * up to the second, repeatedly swapping a randomly selected element into * the "current position". Elements are randomly selected from the * portion of the list that runs from the first element to the current * position, inclusive.<p> * * This method runs in linear time. If the specified list does not * implement the {@link RandomAccess} interface and is large, this * implementation dumps the specified list into an array before shuffling * it, and dumps the shuffled array back into the list. This avoids the * quadratic behavior that would result from shuffling a "sequential * access" list in place. * {@description.close} * * @param list the list to be shuffled. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the <tt>set</tt> operation. */ public static void shuffle(List<?> list) { if (r == null) { r = new Random(); } shuffle(list, r); } private static Random r; /** {@collect.stats} * {@description.open} * Randomly permute the specified list using the specified source of * randomness. All permutations occur with equal likelihood * assuming that the source of randomness is fair.<p> * * This implementation traverses the list backwards, from the last element * up to the second, repeatedly swapping a randomly selected element into * the "current position". Elements are randomly selected from the * portion of the list that runs from the first element to the current * position, inclusive.<p> * * This method runs in linear time. If the specified list does not * implement the {@link RandomAccess} interface and is large, this * implementation dumps the specified list into an array before shuffling * it, and dumps the shuffled array back into the list. This avoids the * quadratic behavior that would result from shuffling a "sequential * access" list in place. * {@description.close} * * @param list the list to be shuffled. * @param rnd the source of randomness to use to shuffle the list. * @throws UnsupportedOperationException if the specified list or its * list-iterator does not support the <tt>set</tt> operation. */ public static void shuffle(List<?> list, Random rnd) { int size = list.size(); if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) { for (int i=size; i>1; i--) swap(list, i-1, rnd.nextInt(i)); } else { Object arr[] = list.toArray(); // Shuffle array for (int i=size; i>1; i--) swap(arr, i-1, rnd.nextInt(i)); // Dump array back into list ListIterator it = list.listIterator(); for (int i=0; i<arr.length; i++) { it.next(); it.set(arr[i]); } } } /** {@collect.stats} * {@description.open} * Swaps the elements at the specified positions in the specified list. * (If the specified positions are equal, invoking this method leaves * the list unchanged.) * {@description.close} * * @param list The list in which to swap elements. * @param i the index of one element to be swapped. * @param j the index of the other element to be swapped. * @throws IndexOutOfBoundsException if either <tt>i</tt> or <tt>j</tt> * is out of range (i &lt; 0 || i &gt;= list.size() * || j &lt; 0 || j &gt;= list.size()). * @since 1.4 */ public static void swap(List<?> list, int i, int j) { final List l = list; l.set(i, l.set(j, l.get(i))); } /** {@collect.stats} * {@description.open} * Swaps the two specified elements in the specified array. * {@description.close} */ private static void swap(Object[] arr, int i, int j) { Object tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } /** {@collect.stats} * {@description.open} * Replaces all of the elements of the specified list with the specified * element. <p> * * This method runs in linear time. * {@description.close} * * @param list the list to be filled with the specified element. * @param obj The element with which to fill the specified list. * @throws UnsupportedOperationException if the specified list or its * list-iterator does not support the <tt>set</tt> operation. */ public static <T> void fill(List<? super T> list, T obj) { int size = list.size(); if (size < FILL_THRESHOLD || list instanceof RandomAccess) { for (int i=0; i<size; i++) list.set(i, obj); } else { ListIterator<? super T> itr = list.listIterator(); for (int i=0; i<size; i++) { itr.next(); itr.set(obj); } } } /** {@collect.stats} * {@description.open} * Copies all of the elements from one list into another. After the * operation, the index of each copied element in the destination list * will be identical to its index in the source list. * {@description.close} * {@property.open formal:java.util.Collections_CopySize} * The destination * list must be at least as long as the source list. * {@property.close} * {@description.open} * If it is longer, the * remaining elements in the destination list are unaffected. <p> * * This method runs in linear time. * {@description.close} * * @param dest The destination list. * @param src The source list. * @throws IndexOutOfBoundsException if the destination list is too small * to contain the entire source List. * @throws UnsupportedOperationException if the destination list's * list-iterator does not support the <tt>set</tt> operation. */ public static <T> void copy(List<? super T> dest, List<? extends T> src) { int srcSize = src.size(); if (srcSize > dest.size()) throw new IndexOutOfBoundsException("Source does not fit in dest"); if (srcSize < COPY_THRESHOLD || (src instanceof RandomAccess && dest instanceof RandomAccess)) { for (int i=0; i<srcSize; i++) dest.set(i, src.get(i)); } else { ListIterator<? super T> di=dest.listIterator(); ListIterator<? extends T> si=src.listIterator(); for (int i=0; i<srcSize; i++) { di.next(); di.set(si.next()); } } } /** {@collect.stats} * {@description.open} * Returns the minimum element of the given collection, according to the * <i>natural ordering</i> of its elements. * {@description.close} * {@property.open formal:java.util.Collections_ImplementComparable} * All elements in the * collection must implement the <tt>Comparable</tt> interface. * Furthermore, all elements in the collection must be <i>mutually * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and * <tt>e2</tt> in the collection).<p> * {@property.close} * * {@description.open} * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * {@description.close} * * @param coll the collection whose minimum element is to be determined. * @return the minimum element of the given collection, according * to the <i>natural ordering</i> of its elements. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> (for example, strings and * integers). * @throws NoSuchElementException if the collection is empty. * @see Comparable */ public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) < 0) candidate = next; } return candidate; } /** {@collect.stats} * {@description.open} * Returns the minimum element of the given collection, according to the * order induced by the specified comparator. * {@description.close} * {@property.open formal:java.util.Collections_Comparable} * All elements in the * collection must be <i>mutually comparable</i> by the specified * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and * <tt>e2</tt> in the collection).<p> * {@property.close} * * {@description.open} * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * {@description.close} * * @param coll the collection whose minimum element is to be determined. * @param comp the comparator with which to determine the minimum element. * A <tt>null</tt> value indicates that the elements' <i>natural * ordering</i> should be used. * @return the minimum element of the given collection, according * to the specified comparator. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> using the specified comparator. * @throws NoSuchElementException if the collection is empty. * @see Comparable */ public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) { if (comp==null) return (T)min((Collection<SelfComparable>) (Collection) coll); Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (comp.compare(next, candidate) < 0) candidate = next; } return candidate; } /** {@collect.stats} * {@description.open} * Returns the maximum element of the given collection, according to the * <i>natural ordering</i> of its elements. * {@description.close} * {@property.open formal:java.util.Collections_ImplementComparable} * All elements in the * collection must implement the <tt>Comparable</tt> interface. * Furthermore, all elements in the collection must be <i>mutually * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and * <tt>e2</tt> in the collection).<p> * {@property.close} * * {@description.open} * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * {@description.close} * * @param coll the collection whose maximum element is to be determined. * @return the maximum element of the given collection, according * to the <i>natural ordering</i> of its elements. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> (for example, strings and * integers). * @throws NoSuchElementException if the collection is empty. * @see Comparable */ public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) > 0) candidate = next; } return candidate; } /** {@collect.stats} * {@description.open} * Returns the maximum element of the given collection, according to the * order induced by the specified comparator. * {@description.close} * {@property.open formal:java.util.Collections_Comparable} * All elements in the * collection must be <i>mutually comparable</i> by the specified * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and * <tt>e2</tt> in the collection).<p> * {@property.close} * * {@description.open} * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * {@description.close} * * @param coll the collection whose maximum element is to be determined. * @param comp the comparator with which to determine the maximum element. * A <tt>null</tt> value indicates that the elements' <i>natural * ordering</i> should be used. * @return the maximum element of the given collection, according * to the specified comparator. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> using the specified comparator. * @throws NoSuchElementException if the collection is empty. * @see Comparable */ public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) { if (comp==null) return (T)max((Collection<SelfComparable>) (Collection) coll); Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (comp.compare(next, candidate) > 0) candidate = next; } return candidate; } /** {@collect.stats} * {@description.open} * Rotates the elements in the specified list by the specified distance. * After calling this method, the element at index <tt>i</tt> will be * the element previously at index <tt>(i - distance)</tt> mod * <tt>list.size()</tt>, for all values of <tt>i</tt> between <tt>0</tt> * and <tt>list.size()-1</tt>, inclusive. (This method has no effect on * the size of the list.) * * <p>For example, suppose <tt>list</tt> comprises<tt> [t, a, n, k, s]</tt>. * After invoking <tt>Collections.rotate(list, 1)</tt> (or * <tt>Collections.rotate(list, -4)</tt>), <tt>list</tt> will comprise * <tt>[s, t, a, n, k]</tt>. * * <p>Note that this method can usefully be applied to sublists to * move one or more elements within a list while preserving the * order of the remaining elements. For example, the following idiom * moves the element at index <tt>j</tt> forward to position * <tt>k</tt> (which must be greater than or equal to <tt>j</tt>): * <pre> * Collections.rotate(list.subList(j, k+1), -1); * </pre> * To make this concrete, suppose <tt>list</tt> comprises * <tt>[a, b, c, d, e]</tt>. To move the element at index <tt>1</tt> * (<tt>b</tt>) forward two positions, perform the following invocation: * <pre> * Collections.rotate(l.subList(1, 4), -1); * </pre> * The resulting list is <tt>[a, c, d, b, e]</tt>. * * <p>To move more than one element forward, increase the absolute value * of the rotation distance. To move elements backward, use a positive * shift distance. * * <p>If the specified list is small or implements the {@link * RandomAccess} interface, this implementation exchanges the first * element into the location it should go, and then repeatedly exchanges * the displaced element into the location it should go until a displaced * element is swapped into the first element. If necessary, the process * is repeated on the second and successive elements, until the rotation * is complete. If the specified list is large and doesn't implement the * <tt>RandomAccess</tt> interface, this implementation breaks the * list into two sublist views around index <tt>-distance mod size</tt>. * Then the {@link #reverse(List)} method is invoked on each sublist view, * and finally it is invoked on the entire list. For a more complete * description of both algorithms, see Section 2.3 of Jon Bentley's * <i>Programming Pearls</i> (Addison-Wesley, 1986). * {@description.close} * * @param list the list to be rotated. * @param distance the distance to rotate the list. There are no * constraints on this value; it may be zero, negative, or * greater than <tt>list.size()</tt>. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the <tt>set</tt> operation. * @since 1.4 */ public static void rotate(List<?> list, int distance) { if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD) rotate1(list, distance); else rotate2(list, distance); } private static <T> void rotate1(List<T> list, int distance) { int size = list.size(); if (size == 0) return; distance = distance % size; if (distance < 0) distance += size; if (distance == 0) return; for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) { T displaced = list.get(cycleStart); int i = cycleStart; do { i += distance; if (i >= size) i -= size; displaced = list.set(i, displaced); nMoved ++; } while(i != cycleStart); } } private static void rotate2(List<?> list, int distance) { int size = list.size(); if (size == 0) return; int mid = -distance % size; if (mid < 0) mid += size; if (mid == 0) return; reverse(list.subList(0, mid)); reverse(list.subList(mid, size)); reverse(list); } /** {@collect.stats} * {@description.open} * Replaces all occurrences of one specified value in a list with another. * More formally, replaces with <tt>newVal</tt> each element <tt>e</tt> * in <tt>list</tt> such that * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>. * (This method has no effect on the size of the list.) * {@description.close} * * @param list the list in which replacement is to occur. * @param oldVal the old value to be replaced. * @param newVal the new value with which <tt>oldVal</tt> is to be * replaced. * @return <tt>true</tt> if <tt>list</tt> contained one or more elements * <tt>e</tt> such that * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the <tt>set</tt> operation. * @since 1.4 */ public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) { boolean result = false; int size = list.size(); if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) { if (oldVal==null) { for (int i=0; i<size; i++) { if (list.get(i)==null) { list.set(i, newVal); result = true; } } } else { for (int i=0; i<size; i++) { if (oldVal.equals(list.get(i))) { list.set(i, newVal); result = true; } } } } else { ListIterator<T> itr=list.listIterator(); if (oldVal==null) { for (int i=0; i<size; i++) { if (itr.next()==null) { itr.set(newVal); result = true; } } } else { for (int i=0; i<size; i++) { if (oldVal.equals(itr.next())) { itr.set(newVal); result = true; } } } } return result; } /** {@collect.stats} * {@description.open} * Returns the starting position of the first occurrence of the specified * target list within the specified source list, or -1 if there is no * such occurrence. More formally, returns the lowest index <tt>i</tt> * such that <tt>source.subList(i, i+target.size()).equals(target)</tt>, * or -1 if there is no such index. (Returns -1 if * <tt>target.size() > source.size()</tt>.) * * <p>This implementation uses the "brute force" technique of scanning * over the source list, looking for a match with the target at each * location in turn. * {@description.close} * * @param source the list in which to search for the first occurrence * of <tt>target</tt>. * @param target the list to search for as a subList of <tt>source</tt>. * @return the starting position of the first occurrence of the specified * target list within the specified source list, or -1 if there * is no such occurrence. * @since 1.4 */ public static int indexOfSubList(List<?> source, List<?> target) { int sourceSize = source.size(); int targetSize = target.size(); int maxCandidate = sourceSize - targetSize; if (sourceSize < INDEXOFSUBLIST_THRESHOLD || (source instanceof RandomAccess&&target instanceof RandomAccess)) { nextCand: for (int candidate = 0; candidate <= maxCandidate; candidate++) { for (int i=0, j=candidate; i<targetSize; i++, j++) if (!eq(target.get(i), source.get(j))) continue nextCand; // Element mismatch, try next cand return candidate; // All elements of candidate matched target } } else { // Iterator version of above algorithm ListIterator<?> si = source.listIterator(); nextCand: for (int candidate = 0; candidate <= maxCandidate; candidate++) { ListIterator<?> ti = target.listIterator(); for (int i=0; i<targetSize; i++) { if (!eq(ti.next(), si.next())) { // Back up source iterator to next candidate for (int j=0; j<i; j++) si.previous(); continue nextCand; } } return candidate; } } return -1; // No candidate matched the target } /** {@collect.stats} * {@description.open} * Returns the starting position of the last occurrence of the specified * target list within the specified source list, or -1 if there is no such * occurrence. More formally, returns the highest index <tt>i</tt> * such that <tt>source.subList(i, i+target.size()).equals(target)</tt>, * or -1 if there is no such index. (Returns -1 if * <tt>target.size() > source.size()</tt>.) * * <p>This implementation uses the "brute force" technique of iterating * over the source list, looking for a match with the target at each * location in turn. * {@description.close} * * @param source the list in which to search for the last occurrence * of <tt>target</tt>. * @param target the list to search for as a subList of <tt>source</tt>. * @return the starting position of the last occurrence of the specified * target list within the specified source list, or -1 if there * is no such occurrence. * @since 1.4 */ public static int lastIndexOfSubList(List<?> source, List<?> target) { int sourceSize = source.size(); int targetSize = target.size(); int maxCandidate = sourceSize - targetSize; if (sourceSize < INDEXOFSUBLIST_THRESHOLD || source instanceof RandomAccess) { // Index access version nextCand: for (int candidate = maxCandidate; candidate >= 0; candidate--) { for (int i=0, j=candidate; i<targetSize; i++, j++) if (!eq(target.get(i), source.get(j))) continue nextCand; // Element mismatch, try next cand return candidate; // All elements of candidate matched target } } else { // Iterator version of above algorithm if (maxCandidate < 0) return -1; ListIterator<?> si = source.listIterator(maxCandidate); nextCand: for (int candidate = maxCandidate; candidate >= 0; candidate--) { ListIterator<?> ti = target.listIterator(); for (int i=0; i<targetSize; i++) { if (!eq(ti.next(), si.next())) { if (candidate != 0) { // Back up source iterator to next candidate for (int j=0; j<=i+1; j++) si.previous(); } continue nextCand; } } return candidate; } } return -1; // No candidate matched the target } // Unmodifiable Wrappers /** {@collect.stats} * {@description.open} * Returns an unmodifiable view of the specified collection. This method * allows modules to provide users with "read-only" access to internal * collections. Query operations on the returned collection "read through" * to the specified collection, and attempts to modify the returned * collection, whether direct or via its iterator, result in an * <tt>UnsupportedOperationException</tt>.<p> * * The returned collection does <i>not</i> pass the hashCode and equals * operations through to the backing collection, but relies on * <tt>Object</tt>'s <tt>equals</tt> and <tt>hashCode</tt> methods. This * is necessary to preserve the contracts of these operations in the case * that the backing collection is a set or a list.<p> * * The returned collection will be serializable if the specified collection * is serializable. * {@description.close} * * @param c the collection for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified collection. */ public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) { return new UnmodifiableCollection<T>(c); } /** {@collect.stats} * @serial include */ static class UnmodifiableCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 1820017752578914078L; final Collection<? extends E> c; UnmodifiableCollection(Collection<? extends E> c) { if (c==null) throw new NullPointerException(); this.c = c; } public int size() {return c.size();} public boolean isEmpty() {return c.isEmpty();} public boolean contains(Object o) {return c.contains(o);} public Object[] toArray() {return c.toArray();} public <T> T[] toArray(T[] a) {return c.toArray(a);} public String toString() {return c.toString();} public Iterator<E> iterator() { return new Iterator<E>() { private final Iterator<? extends E> i = c.iterator(); public boolean hasNext() {return i.hasNext();} public E next() {return i.next();} public void remove() { throw new UnsupportedOperationException(); } }; } public boolean add(E e) { throw new UnsupportedOperationException(); } public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean containsAll(Collection<?> coll) { return c.containsAll(coll); } public boolean addAll(Collection<? extends E> coll) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection<?> coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection<?> coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } } /** {@collect.stats} * {@description.open} * Returns an unmodifiable view of the specified set. This method allows * modules to provide users with "read-only" access to internal sets. * Query operations on the returned set "read through" to the specified * set, and attempts to modify the returned set, whether direct or via its * iterator, result in an <tt>UnsupportedOperationException</tt>.<p> * * The returned set will be serializable if the specified set * is serializable. * {@description.close} * * @param s the set for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified set. */ public static <T> Set<T> unmodifiableSet(Set<? extends T> s) { return new UnmodifiableSet<T>(s); } /** {@collect.stats} * @serial include */ static class UnmodifiableSet<E> extends UnmodifiableCollection<E> implements Set<E>, Serializable { private static final long serialVersionUID = -9215047833775013803L; UnmodifiableSet(Set<? extends E> s) {super(s);} public boolean equals(Object o) {return o == this || c.equals(o);} public int hashCode() {return c.hashCode();} } /** {@collect.stats} * {@description.open} * Returns an unmodifiable view of the specified sorted set. This method * allows modules to provide users with "read-only" access to internal * sorted sets. Query operations on the returned sorted set "read * through" to the specified sorted set. Attempts to modify the returned * sorted set, whether direct, via its iterator, or via its * <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in * an <tt>UnsupportedOperationException</tt>.<p> * * The returned sorted set will be serializable if the specified sorted set * is serializable. * {@description.close} * * @param s the sorted set for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified sorted set. */ public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) { return new UnmodifiableSortedSet<T>(s); } /** {@collect.stats} * @serial include */ static class UnmodifiableSortedSet<E> extends UnmodifiableSet<E> implements SortedSet<E>, Serializable { private static final long serialVersionUID = -4929149591599911165L; private final SortedSet<E> ss; UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;} public Comparator<? super E> comparator() {return ss.comparator();} public SortedSet<E> subSet(E fromElement, E toElement) { return new UnmodifiableSortedSet<E>(ss.subSet(fromElement,toElement)); } public SortedSet<E> headSet(E toElement) { return new UnmodifiableSortedSet<E>(ss.headSet(toElement)); } public SortedSet<E> tailSet(E fromElement) { return new UnmodifiableSortedSet<E>(ss.tailSet(fromElement)); } public E first() {return ss.first();} public E last() {return ss.last();} } /** {@collect.stats} * {@description.open} * Returns an unmodifiable view of the specified list. This method allows * modules to provide users with "read-only" access to internal * lists. Query operations on the returned list "read through" to the * specified list, and attempts to modify the returned list, whether * direct or via its iterator, result in an * <tt>UnsupportedOperationException</tt>.<p> * * The returned list will be serializable if the specified list * is serializable. Similarly, the returned list will implement * {@link RandomAccess} if the specified list does. * {@description.close} * * @param list the list for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified list. */ public static <T> List<T> unmodifiableList(List<? extends T> list) { return (list instanceof RandomAccess ? new UnmodifiableRandomAccessList<T>(list) : new UnmodifiableList<T>(list)); } /** {@collect.stats} * @serial include */ static class UnmodifiableList<E> extends UnmodifiableCollection<E> implements List<E> { private static final long serialVersionUID = -283967356065247728L; final List<? extends E> list; UnmodifiableList(List<? extends E> list) { super(list); this.list = list; } public boolean equals(Object o) {return o == this || list.equals(o);} public int hashCode() {return list.hashCode();} public E get(int index) {return list.get(index);} public E set(int index, E element) { throw new UnsupportedOperationException(); } public void add(int index, E element) { throw new UnsupportedOperationException(); } public E remove(int index) { throw new UnsupportedOperationException(); } public int indexOf(Object o) {return list.indexOf(o);} public int lastIndexOf(Object o) {return list.lastIndexOf(o);} public boolean addAll(int index, Collection<? extends E> c) { throw new UnsupportedOperationException(); } public ListIterator<E> listIterator() {return listIterator(0);} public ListIterator<E> listIterator(final int index) { return new ListIterator<E>() { private final ListIterator<? extends E> i = list.listIterator(index); public boolean hasNext() {return i.hasNext();} public E next() {return i.next();} public boolean hasPrevious() {return i.hasPrevious();} public E previous() {return i.previous();} public int nextIndex() {return i.nextIndex();} public int previousIndex() {return i.previousIndex();} public void remove() { throw new UnsupportedOperationException(); } public void set(E e) { throw new UnsupportedOperationException(); } public void add(E e) { throw new UnsupportedOperationException(); } }; } public List<E> subList(int fromIndex, int toIndex) { return new UnmodifiableList<E>(list.subList(fromIndex, toIndex)); } /** {@collect.stats} * {@description.open} * UnmodifiableRandomAccessList instances are serialized as * UnmodifiableList instances to allow them to be deserialized * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList). * This method inverts the transformation. As a beneficial * side-effect, it also grafts the RandomAccess marker onto * UnmodifiableList instances that were serialized in pre-1.4 JREs. * * Note: Unfortunately, UnmodifiableRandomAccessList instances * serialized in 1.4.1 and deserialized in 1.4 will become * UnmodifiableList instances, as this method was missing in 1.4. * {@description.close} */ private Object readResolve() { return (list instanceof RandomAccess ? new UnmodifiableRandomAccessList<E>(list) : this); } } /** {@collect.stats} * @serial include */ static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E> implements RandomAccess { UnmodifiableRandomAccessList(List<? extends E> list) { super(list); } public List<E> subList(int fromIndex, int toIndex) { return new UnmodifiableRandomAccessList<E>( list.subList(fromIndex, toIndex)); } private static final long serialVersionUID = -2542308836966382001L; /** {@collect.stats} * {@description.open} * Allows instances to be deserialized in pre-1.4 JREs (which do * not have UnmodifiableRandomAccessList). UnmodifiableList has * a readResolve method that inverts this transformation upon * deserialization. * {@description.close} */ private Object writeReplace() { return new UnmodifiableList<E>(list); } } /** {@collect.stats} * {@description.open} * Returns an unmodifiable view of the specified map. This method * allows modules to provide users with "read-only" access to internal * maps. Query operations on the returned map "read through" * to the specified map, and attempts to modify the returned * map, whether direct or via its collection views, result in an * <tt>UnsupportedOperationException</tt>.<p> * * The returned map will be serializable if the specified map * is serializable. * {@description.close} * * @param m the map for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified map. */ public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) { return new UnmodifiableMap<K,V>(m); } /** {@collect.stats} * @serial include */ private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable { private static final long serialVersionUID = -1034234728574286014L; private final Map<? extends K, ? extends V> m; UnmodifiableMap(Map<? extends K, ? extends V> m) { if (m==null) throw new NullPointerException(); this.m = m; } public int size() {return m.size();} public boolean isEmpty() {return m.isEmpty();} public boolean containsKey(Object key) {return m.containsKey(key);} public boolean containsValue(Object val) {return m.containsValue(val);} public V get(Object key) {return m.get(key);} public V put(K key, V value) { throw new UnsupportedOperationException(); } public V remove(Object key) { throw new UnsupportedOperationException(); } public void putAll(Map<? extends K, ? extends V> m) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } private transient Set<K> keySet = null; private transient Set<Map.Entry<K,V>> entrySet = null; private transient Collection<V> values = null; public Set<K> keySet() { if (keySet==null) keySet = unmodifiableSet(m.keySet()); return keySet; } public Set<Map.Entry<K,V>> entrySet() { if (entrySet==null) entrySet = new UnmodifiableEntrySet<K,V>(m.entrySet()); return entrySet; } public Collection<V> values() { if (values==null) values = unmodifiableCollection(m.values()); return values; } public boolean equals(Object o) {return o == this || m.equals(o);} public int hashCode() {return m.hashCode();} public String toString() {return m.toString();} /** {@collect.stats} * {@description.open} * We need this class in addition to UnmodifiableSet as * Map.Entries themselves permit modification of the backing Map * via their setValue operation. This class is subtle: there are * many possible attacks that must be thwarted. * {@description.close} * * @serial include */ static class UnmodifiableEntrySet<K,V> extends UnmodifiableSet<Map.Entry<K,V>> { private static final long serialVersionUID = 7854390611657943733L; UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) { super((Set)s); } public Iterator<Map.Entry<K,V>> iterator() { return new Iterator<Map.Entry<K,V>>() { private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator(); public boolean hasNext() { return i.hasNext(); } public Map.Entry<K,V> next() { return new UnmodifiableEntry<K,V>(i.next()); } public void remove() { throw new UnsupportedOperationException(); } }; } public Object[] toArray() { Object[] a = c.toArray(); for (int i=0; i<a.length; i++) a[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)a[i]); return a; } public <T> T[] toArray(T[] a) { // We don't pass a to c.toArray, to avoid window of // vulnerability wherein an unscrupulous multithreaded client // could get his hands on raw (unwrapped) Entries from c. Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0)); for (int i=0; i<arr.length; i++) arr[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)arr[i]); if (arr.length > a.length) return (T[])arr; System.arraycopy(arr, 0, a, 0, arr.length); if (a.length > arr.length) a[arr.length] = null; return a; } /** {@collect.stats} * {@description.open} * This method is overridden to protect the backing set against * an object with a nefarious equals function that senses * that the equality-candidate is Map.Entry and calls its * setValue method. * {@description.close} */ public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; return c.contains( new UnmodifiableEntry<Object,Object>((Map.Entry<?,?>) o)); } /** {@collect.stats} * {@description.open} * The next two methods are overridden to protect against * an unscrupulous List whose contains(Object o) method senses * when o is a Map.Entry, and calls o.setValue. * {@description.close} */ public boolean containsAll(Collection<?> coll) { Iterator<?> e = coll.iterator(); while (e.hasNext()) if (!contains(e.next())) // Invokes safe contains() above return false; return true; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Set s = (Set) o; if (s.size() != c.size()) return false; return containsAll(s); // Invokes safe containsAll() above } /** {@collect.stats} * {@description.open} * This "wrapper class" serves two purposes: it prevents * the client from modifying the backing Map, by short-circuiting * the setValue method, and it protects the backing Map against * an ill-behaved Map.Entry that attempts to modify another * Map Entry when asked to perform an equality check. * {@description.close} */ private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> { private Map.Entry<? extends K, ? extends V> e; UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e) {this.e = e;} public K getKey() {return e.getKey();} public V getValue() {return e.getValue();} public V setValue(V value) { throw new UnsupportedOperationException(); } public int hashCode() {return e.hashCode();} public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry t = (Map.Entry)o; return eq(e.getKey(), t.getKey()) && eq(e.getValue(), t.getValue()); } public String toString() {return e.toString();} } } } /** {@collect.stats} * {@description.open} * Returns an unmodifiable view of the specified sorted map. This method * allows modules to provide users with "read-only" access to internal * sorted maps. Query operations on the returned sorted map "read through" * to the specified sorted map. Attempts to modify the returned * sorted map, whether direct, via its collection views, or via its * <tt>subMap</tt>, <tt>headMap</tt>, or <tt>tailMap</tt> views, result in * an <tt>UnsupportedOperationException</tt>.<p> * * The returned sorted map will be serializable if the specified sorted map * is serializable. * {@description.close} * * @param m the sorted map for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified sorted map. */ public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) { return new UnmodifiableSortedMap<K,V>(m); } /** {@collect.stats} * @serial include */ static class UnmodifiableSortedMap<K,V> extends UnmodifiableMap<K,V> implements SortedMap<K,V>, Serializable { private static final long serialVersionUID = -8806743815996713206L; private final SortedMap<K, ? extends V> sm; UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;} public Comparator<? super K> comparator() {return sm.comparator();} public SortedMap<K,V> subMap(K fromKey, K toKey) { return new UnmodifiableSortedMap<K,V>(sm.subMap(fromKey, toKey)); } public SortedMap<K,V> headMap(K toKey) { return new UnmodifiableSortedMap<K,V>(sm.headMap(toKey)); } public SortedMap<K,V> tailMap(K fromKey) { return new UnmodifiableSortedMap<K,V>(sm.tailMap(fromKey)); } public K firstKey() {return sm.firstKey();} public K lastKey() {return sm.lastKey();} } // Synch Wrappers /** {@collect.stats} * {@description.open} * Returns a synchronized (thread-safe) collection backed by the specified * collection. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing collection is accomplished * through the returned collection.<p> * {@description.close} * * {@property.open formal:java.util.Collections_SynchronizedCollection} * It is imperative that the user manually synchronize on the returned * collection when iterating over it: * <pre> * Collection c = Collections.synchronizedCollection(myCollection); * ... * synchronized(c) { * Iterator i = c.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * {@property.close} * * {@description.open} * <p>The returned collection does <i>not</i> pass the <tt>hashCode</tt> * and <tt>equals</tt> operations through to the backing collection, but * relies on <tt>Object</tt>'s equals and hashCode methods. This is * necessary to preserve the contracts of these operations in the case * that the backing collection is a set or a list.<p> * * The returned collection will be serializable if the specified collection * is serializable. * {@description.close} * * @param c the collection to be "wrapped" in a synchronized collection. * @return a synchronized view of the specified collection. */ public static <T> Collection<T> synchronizedCollection(Collection<T> c) { return new SynchronizedCollection<T>(c); } static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) { return new SynchronizedCollection<T>(c, mutex); } /** {@collect.stats} * @serial include */ static class SynchronizedCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 3053995032091335093L; final Collection<E> c; // Backing Collection final Object mutex; // Object on which to synchronize SynchronizedCollection(Collection<E> c) { if (c==null) throw new NullPointerException(); this.c = c; mutex = this; } SynchronizedCollection(Collection<E> c, Object mutex) { this.c = c; this.mutex = mutex; } public int size() { synchronized(mutex) {return c.size();} } public boolean isEmpty() { synchronized(mutex) {return c.isEmpty();} } public boolean contains(Object o) { synchronized(mutex) {return c.contains(o);} } public Object[] toArray() { synchronized(mutex) {return c.toArray();} } public <T> T[] toArray(T[] a) { synchronized(mutex) {return c.toArray(a);} } public Iterator<E> iterator() { return c.iterator(); // Must be manually synched by user! } public boolean add(E e) { synchronized(mutex) {return c.add(e);} } public boolean remove(Object o) { synchronized(mutex) {return c.remove(o);} } public boolean containsAll(Collection<?> coll) { synchronized(mutex) {return c.containsAll(coll);} } public boolean addAll(Collection<? extends E> coll) { synchronized(mutex) {return c.addAll(coll);} } public boolean removeAll(Collection<?> coll) { synchronized(mutex) {return c.removeAll(coll);} } public boolean retainAll(Collection<?> coll) { synchronized(mutex) {return c.retainAll(coll);} } public void clear() { synchronized(mutex) {c.clear();} } public String toString() { synchronized(mutex) {return c.toString();} } private void writeObject(ObjectOutputStream s) throws IOException { synchronized(mutex) {s.defaultWriteObject();} } } /** {@collect.stats} * {@description.open} * Returns a synchronized (thread-safe) set backed by the specified * set. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing set is accomplished * through the returned set.<p> * {@description.close} * * {@property.open formal:java.util.Collections_SynchronizedCollection} * It is imperative that the user manually synchronize on the returned * set when iterating over it: * <pre> * Set s = Collections.synchronizedSet(new HashSet()); * ... * synchronized(s) { * Iterator i = s.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * {@property.close} * * {@description.open} * <p>The returned set will be serializable if the specified set is * serializable. * {@description.close} * * @param s the set to be "wrapped" in a synchronized set. * @return a synchronized view of the specified set. */ public static <T> Set<T> synchronizedSet(Set<T> s) { return new SynchronizedSet<T>(s); } static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) { return new SynchronizedSet<T>(s, mutex); } /** {@collect.stats} * @serial include */ static class SynchronizedSet<E> extends SynchronizedCollection<E> implements Set<E> { private static final long serialVersionUID = 487447009682186044L; SynchronizedSet(Set<E> s) { super(s); } SynchronizedSet(Set<E> s, Object mutex) { super(s, mutex); } public boolean equals(Object o) { synchronized(mutex) {return c.equals(o);} } public int hashCode() { synchronized(mutex) {return c.hashCode();} } } /** {@collect.stats} * {@description.open} * Returns a synchronized (thread-safe) sorted set backed by the specified * sorted set. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing sorted set is accomplished * through the returned sorted set (or its views).<p> * {@description.close} * * {@property.open formal:java.util.Collections_SynchronizedCollection} * It is imperative that the user manually synchronize on the returned * sorted set when iterating over it or any of its <tt>subSet</tt>, * <tt>headSet</tt>, or <tt>tailSet</tt> views. * <pre> * SortedSet s = Collections.synchronizedSortedSet(new TreeSet()); * ... * synchronized(s) { * Iterator i = s.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * or: * <pre> * SortedSet s = Collections.synchronizedSortedSet(new TreeSet()); * SortedSet s2 = s.headSet(foo); * ... * synchronized(s) { // Note: s, not s2!!! * Iterator i = s2.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * {@property.close} * * {@description.open} * <p>The returned sorted set will be serializable if the specified * sorted set is serializable. * {@description.close} * * @param s the sorted set to be "wrapped" in a synchronized sorted set. * @return a synchronized view of the specified sorted set. */ public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) { return new SynchronizedSortedSet<T>(s); } /** {@collect.stats} * @serial include */ static class SynchronizedSortedSet<E> extends SynchronizedSet<E> implements SortedSet<E> { private static final long serialVersionUID = 8695801310862127406L; final private SortedSet<E> ss; SynchronizedSortedSet(SortedSet<E> s) { super(s); ss = s; } SynchronizedSortedSet(SortedSet<E> s, Object mutex) { super(s, mutex); ss = s; } public Comparator<? super E> comparator() { synchronized(mutex) {return ss.comparator();} } public SortedSet<E> subSet(E fromElement, E toElement) { synchronized(mutex) { return new SynchronizedSortedSet<E>( ss.subSet(fromElement, toElement), mutex); } } public SortedSet<E> headSet(E toElement) { synchronized(mutex) { return new SynchronizedSortedSet<E>(ss.headSet(toElement), mutex); } } public SortedSet<E> tailSet(E fromElement) { synchronized(mutex) { return new SynchronizedSortedSet<E>(ss.tailSet(fromElement),mutex); } } public E first() { synchronized(mutex) {return ss.first();} } public E last() { synchronized(mutex) {return ss.last();} } } /** {@collect.stats} * {@description.open} * Returns a synchronized (thread-safe) list backed by the specified * list. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing list is accomplished * through the returned list.<p> * {@description.close} * * {@property.open formal:java.util.Collections_SynchronizedCollection} * It is imperative that the user manually synchronize on the returned * list when iterating over it: * <pre> * List list = Collections.synchronizedList(new ArrayList()); * ... * synchronized(list) { * Iterator i = list.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * {@property.close} * * {@description.open} * <p>The returned list will be serializable if the specified list is * serializable. * {@description.close} * * @param list the list to be "wrapped" in a synchronized list. * @return a synchronized view of the specified list. */ public static <T> List<T> synchronizedList(List<T> list) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<T>(list) : new SynchronizedList<T>(list)); } static <T> List<T> synchronizedList(List<T> list, Object mutex) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<T>(list, mutex) : new SynchronizedList<T>(list, mutex)); } /** {@collect.stats} * @serial include */ static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> { private static final long serialVersionUID = -7754090372962971524L; final List<E> list; SynchronizedList(List<E> list) { super(list); this.list = list; } SynchronizedList(List<E> list, Object mutex) { super(list, mutex); this.list = list; } public boolean equals(Object o) { synchronized(mutex) {return list.equals(o);} } public int hashCode() { synchronized(mutex) {return list.hashCode();} } public E get(int index) { synchronized(mutex) {return list.get(index);} } public E set(int index, E element) { synchronized(mutex) {return list.set(index, element);} } public void add(int index, E element) { synchronized(mutex) {list.add(index, element);} } public E remove(int index) { synchronized(mutex) {return list.remove(index);} } public int indexOf(Object o) { synchronized(mutex) {return list.indexOf(o);} } public int lastIndexOf(Object o) { synchronized(mutex) {return list.lastIndexOf(o);} } public boolean addAll(int index, Collection<? extends E> c) { synchronized(mutex) {return list.addAll(index, c);} } public ListIterator<E> listIterator() { return list.listIterator(); // Must be manually synched by user } public ListIterator<E> listIterator(int index) { return list.listIterator(index); // Must be manually synched by user } public List<E> subList(int fromIndex, int toIndex) { synchronized(mutex) { return new SynchronizedList<E>(list.subList(fromIndex, toIndex), mutex); } } /** {@collect.stats} * {@description.open} * SynchronizedRandomAccessList instances are serialized as * SynchronizedList instances to allow them to be deserialized * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList). * This method inverts the transformation. As a beneficial * side-effect, it also grafts the RandomAccess marker onto * SynchronizedList instances that were serialized in pre-1.4 JREs. * * Note: Unfortunately, SynchronizedRandomAccessList instances * serialized in 1.4.1 and deserialized in 1.4 will become * SynchronizedList instances, as this method was missing in 1.4. * {@description.close} */ private Object readResolve() { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<E>(list) : this); } } /** {@collect.stats} * @serial include */ static class SynchronizedRandomAccessList<E> extends SynchronizedList<E> implements RandomAccess { SynchronizedRandomAccessList(List<E> list) { super(list); } SynchronizedRandomAccessList(List<E> list, Object mutex) { super(list, mutex); } public List<E> subList(int fromIndex, int toIndex) { synchronized(mutex) { return new SynchronizedRandomAccessList<E>( list.subList(fromIndex, toIndex), mutex); } } private static final long serialVersionUID = 1530674583602358482L; /** {@collect.stats} * {@description.open} * Allows instances to be deserialized in pre-1.4 JREs (which do * not have SynchronizedRandomAccessList). SynchronizedList has * a readResolve method that inverts this transformation upon * deserialization. * {@description.close} */ private Object writeReplace() { return new SynchronizedList<E>(list); } } /** {@collect.stats} * {@description.open} * Returns a synchronized (thread-safe) map backed by the specified * map. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing map is accomplished * through the returned map.<p> * {@description.close} * * {@property.open formal:java.util.Collections_SynchronizedMap} * It is imperative that the user manually synchronize on the returned * map when iterating over any of its collection views: * <pre> * Map m = Collections.synchronizedMap(new HashMap()); * ... * Set s = m.keySet(); // Needn't be in synchronized block * ... * synchronized(m) { // Synchronizing on m, not s! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * {@property.close} * * {@description.open} * <p>The returned map will be serializable if the specified map is * serializable. * {@description.close} * * @param m the map to be "wrapped" in a synchronized map. * @return a synchronized view of the specified map. */ public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) { return new SynchronizedMap<K,V>(m); } /** {@collect.stats} * @serial include */ private static class SynchronizedMap<K,V> implements Map<K,V>, Serializable { private static final long serialVersionUID = 1978198479659022715L; private final Map<K,V> m; // Backing Map final Object mutex; // Object on which to synchronize SynchronizedMap(Map<K,V> m) { if (m==null) throw new NullPointerException(); this.m = m; mutex = this; } SynchronizedMap(Map<K,V> m, Object mutex) { this.m = m; this.mutex = mutex; } public int size() { synchronized(mutex) {return m.size();} } public boolean isEmpty() { synchronized(mutex) {return m.isEmpty();} } public boolean containsKey(Object key) { synchronized(mutex) {return m.containsKey(key);} } public boolean containsValue(Object value) { synchronized(mutex) {return m.containsValue(value);} } public V get(Object key) { synchronized(mutex) {return m.get(key);} } public V put(K key, V value) { synchronized(mutex) {return m.put(key, value);} } public V remove(Object key) { synchronized(mutex) {return m.remove(key);} } public void putAll(Map<? extends K, ? extends V> map) { synchronized(mutex) {m.putAll(map);} } public void clear() { synchronized(mutex) {m.clear();} } private transient Set<K> keySet = null; private transient Set<Map.Entry<K,V>> entrySet = null; private transient Collection<V> values = null; public Set<K> keySet() { synchronized(mutex) { if (keySet==null) keySet = new SynchronizedSet<K>(m.keySet(), mutex); return keySet; } } public Set<Map.Entry<K,V>> entrySet() { synchronized(mutex) { if (entrySet==null) entrySet = new SynchronizedSet<Map.Entry<K,V>>(m.entrySet(), mutex); return entrySet; } } public Collection<V> values() { synchronized(mutex) { if (values==null) values = new SynchronizedCollection<V>(m.values(), mutex); return values; } } public boolean equals(Object o) { synchronized(mutex) {return m.equals(o);} } public int hashCode() { synchronized(mutex) {return m.hashCode();} } public String toString() { synchronized(mutex) {return m.toString();} } private void writeObject(ObjectOutputStream s) throws IOException { synchronized(mutex) {s.defaultWriteObject();} } } /** {@collect.stats} * {@description.open} * Returns a synchronized (thread-safe) sorted map backed by the specified * sorted map. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing sorted map is accomplished * through the returned sorted map (or its views).<p> * {@description.close} * * {@property.open formal:java.util.Collections_SynchronizedMap} * It is imperative that the user manually synchronize on the returned * sorted map when iterating over any of its collection views, or the * collections views of any of its <tt>subMap</tt>, <tt>headMap</tt> or * <tt>tailMap</tt> views. * <pre> * SortedMap m = Collections.synchronizedSortedMap(new TreeMap()); * ... * Set s = m.keySet(); // Needn't be in synchronized block * ... * synchronized(m) { // Synchronizing on m, not s! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * or: * <pre> * SortedMap m = Collections.synchronizedSortedMap(new TreeMap()); * SortedMap m2 = m.subMap(foo, bar); * ... * Set s2 = m2.keySet(); // Needn't be in synchronized block * ... * synchronized(m) { // Synchronizing on m, not m2 or s2! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * {@property.close} * * {@description.open} * <p>The returned sorted map will be serializable if the specified * sorted map is serializable. * {@description.close} * * @param m the sorted map to be "wrapped" in a synchronized sorted map. * @return a synchronized view of the specified sorted map. */ public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) { return new SynchronizedSortedMap<K,V>(m); } /** {@collect.stats} * @serial include */ static class SynchronizedSortedMap<K,V> extends SynchronizedMap<K,V> implements SortedMap<K,V> { private static final long serialVersionUID = -8798146769416483793L; private final SortedMap<K,V> sm; SynchronizedSortedMap(SortedMap<K,V> m) { super(m); sm = m; } SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) { super(m, mutex); sm = m; } public Comparator<? super K> comparator() { synchronized(mutex) {return sm.comparator();} } public SortedMap<K,V> subMap(K fromKey, K toKey) { synchronized(mutex) { return new SynchronizedSortedMap<K,V>( sm.subMap(fromKey, toKey), mutex); } } public SortedMap<K,V> headMap(K toKey) { synchronized(mutex) { return new SynchronizedSortedMap<K,V>(sm.headMap(toKey), mutex); } } public SortedMap<K,V> tailMap(K fromKey) { synchronized(mutex) { return new SynchronizedSortedMap<K,V>(sm.tailMap(fromKey),mutex); } } public K firstKey() { synchronized(mutex) {return sm.firstKey();} } public K lastKey() { synchronized(mutex) {return sm.lastKey();} } } // Dynamically typesafe collection wrappers /** {@collect.stats} * {@description.open} * Returns a dynamically typesafe view of the specified collection. * Any attempt to insert an element of the wrong type will result in an * immediate {@link ClassCastException}. Assuming a collection * contains no incorrectly typed elements prior to the time a * dynamically typesafe view is generated, and that all subsequent * access to the collection takes place through the view, it is * <i>guaranteed</i> that the collection cannot contain an incorrectly * typed element. * * <p>The generics mechanism in the language provides compile-time * (static) type checking, but it is possible to defeat this mechanism * with unchecked casts. Usually this is not a problem, as the compiler * issues warnings on all such unchecked operations. There are, however, * times when static type checking alone is not sufficient. For example, * suppose a collection is passed to a third-party library and it is * imperative that the library code not corrupt the collection by * inserting an element of the wrong type. * * <p>Another use of dynamically typesafe views is debugging. Suppose a * program fails with a {@code ClassCastException}, indicating that an * incorrectly typed element was put into a parameterized collection. * Unfortunately, the exception can occur at any time after the erroneous * element is inserted, so it typically provides little or no information * as to the real source of the problem. If the problem is reproducible, * one can quickly determine its source by temporarily modifying the * program to wrap the collection with a dynamically typesafe view. * For example, this declaration: * <pre> {@code * Collection<String> c = new HashSet<String>(); * }</pre> * may be replaced temporarily by this one: * <pre> {@code * Collection<String> c = Collections.checkedCollection( * new HashSet<String>(), String.class); * }</pre> * Running the program again will cause it to fail at the point where * an incorrectly typed element is inserted into the collection, clearly * identifying the source of the problem. Once the problem is fixed, the * modified declaration may be reverted back to the original. * * <p>The returned collection does <i>not</i> pass the hashCode and equals * operations through to the backing collection, but relies on * {@code Object}'s {@code equals} and {@code hashCode} methods. This * is necessary to preserve the contracts of these operations in the case * that the backing collection is a set or a list. * * <p>The returned collection will be serializable if the specified * collection is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned collection permits insertion of null elements * whenever the backing collection does. * {@description.close} * * @param c the collection for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code c} is permitted to hold * @return a dynamically typesafe view of the specified collection * @since 1.5 */ public static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type) { return new CheckedCollection<E>(c, type); } @SuppressWarnings("unchecked") static <T> T[] zeroLengthArray(Class<T> type) { return (T[]) Array.newInstance(type, 0); } /** {@collect.stats} * @serial include */ static class CheckedCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 1578914078182001775L; final Collection<E> c; final Class<E> type; void typeCheck(Object o) { if (o != null && !type.isInstance(o)) throw new ClassCastException(badElementMsg(o)); } private String badElementMsg(Object o) { return "Attempt to insert " + o.getClass() + " element into collection with element type " + type; } CheckedCollection(Collection<E> c, Class<E> type) { if (c==null || type == null) throw new NullPointerException(); this.c = c; this.type = type; } public int size() { return c.size(); } public boolean isEmpty() { return c.isEmpty(); } public boolean contains(Object o) { return c.contains(o); } public Object[] toArray() { return c.toArray(); } public <T> T[] toArray(T[] a) { return c.toArray(a); } public String toString() { return c.toString(); } public boolean remove(Object o) { return c.remove(o); } public void clear() { c.clear(); } public boolean containsAll(Collection<?> coll) { return c.containsAll(coll); } public boolean removeAll(Collection<?> coll) { return c.removeAll(coll); } public boolean retainAll(Collection<?> coll) { return c.retainAll(coll); } public Iterator<E> iterator() { final Iterator<E> it = c.iterator(); return new Iterator<E>() { public boolean hasNext() { return it.hasNext(); } public E next() { return it.next(); } public void remove() { it.remove(); }}; } public boolean add(E e) { typeCheck(e); return c.add(e); } private E[] zeroLengthElementArray = null; // Lazily initialized private E[] zeroLengthElementArray() { return zeroLengthElementArray != null ? zeroLengthElementArray : (zeroLengthElementArray = zeroLengthArray(type)); } @SuppressWarnings("unchecked") Collection<E> checkedCopyOf(Collection<? extends E> coll) { Object[] a = null; try { E[] z = zeroLengthElementArray(); a = coll.toArray(z); // Defend against coll violating the toArray contract if (a.getClass() != z.getClass()) a = Arrays.copyOf(a, a.length, z.getClass()); } catch (ArrayStoreException ignore) { // To get better and consistent diagnostics, // we call typeCheck explicitly on each element. // We call clone() to defend against coll retaining a // reference to the returned array and storing a bad // element into it after it has been type checked. a = coll.toArray().clone(); for (Object o : a) typeCheck(o); } // A slight abuse of the type system, but safe here. return (Collection<E>) Arrays.asList(a); } public boolean addAll(Collection<? extends E> coll) { // Doing things this way insulates us from concurrent changes // in the contents of coll and provides all-or-nothing // semantics (which we wouldn't get if we type-checked each // element as we added it) return c.addAll(checkedCopyOf(coll)); } } /** {@collect.stats} * {@description.open} * Returns a dynamically typesafe view of the specified set. * Any attempt to insert an element of the wrong type will result in * an immediate {@link ClassCastException}. Assuming a set contains * no incorrectly typed elements prior to the time a dynamically typesafe * view is generated, and that all subsequent access to the set * takes place through the view, it is <i>guaranteed</i> that the * set cannot contain an incorrectly typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned set will be serializable if the specified set is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned set permits insertion of null elements whenever * the backing set does. * {@description.close} * * @param s the set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold * @return a dynamically typesafe view of the specified set * @since 1.5 */ public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) { return new CheckedSet<E>(s, type); } /** {@collect.stats} * @serial include */ static class CheckedSet<E> extends CheckedCollection<E> implements Set<E>, Serializable { private static final long serialVersionUID = 4694047833775013803L; CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); } public boolean equals(Object o) { return o == this || c.equals(o); } public int hashCode() { return c.hashCode(); } } /** {@collect.stats} * {@description.open} * Returns a dynamically typesafe view of the specified sorted set. * Any attempt to insert an element of the wrong type will result in an * immediate {@link ClassCastException}. Assuming a sorted set * contains no incorrectly typed elements prior to the time a * dynamically typesafe view is generated, and that all subsequent * access to the sorted set takes place through the view, it is * <i>guaranteed</i> that the sorted set cannot contain an incorrectly * typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned sorted set will be serializable if the specified sorted * set is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned sorted set permits insertion of null elements * whenever the backing sorted set does. * {@description.close} * * @param s the sorted set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold * @return a dynamically typesafe view of the specified sorted set * @since 1.5 */ public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s, Class<E> type) { return new CheckedSortedSet<E>(s, type); } /** {@collect.stats} * @serial include */ static class CheckedSortedSet<E> extends CheckedSet<E> implements SortedSet<E>, Serializable { private static final long serialVersionUID = 1599911165492914959L; private final SortedSet<E> ss; CheckedSortedSet(SortedSet<E> s, Class<E> type) { super(s, type); ss = s; } public Comparator<? super E> comparator() { return ss.comparator(); } public E first() { return ss.first(); } public E last() { return ss.last(); } public SortedSet<E> subSet(E fromElement, E toElement) { return checkedSortedSet(ss.subSet(fromElement,toElement), type); } public SortedSet<E> headSet(E toElement) { return checkedSortedSet(ss.headSet(toElement), type); } public SortedSet<E> tailSet(E fromElement) { return checkedSortedSet(ss.tailSet(fromElement), type); } } /** {@collect.stats} * {@description.open} * Returns a dynamically typesafe view of the specified list. * Any attempt to insert an element of the wrong type will result in * an immediate {@link ClassCastException}. Assuming a list contains * no incorrectly typed elements prior to the time a dynamically typesafe * view is generated, and that all subsequent access to the list * takes place through the view, it is <i>guaranteed</i> that the * list cannot contain an incorrectly typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned list will be serializable if the specified list * is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned list permits insertion of null elements whenever * the backing list does. * {@description.close} * * @param list the list for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code list} is permitted to hold * @return a dynamically typesafe view of the specified list * @since 1.5 */ public static <E> List<E> checkedList(List<E> list, Class<E> type) { return (list instanceof RandomAccess ? new CheckedRandomAccessList<E>(list, type) : new CheckedList<E>(list, type)); } /** {@collect.stats} * @serial include */ static class CheckedList<E> extends CheckedCollection<E> implements List<E> { private static final long serialVersionUID = 65247728283967356L; final List<E> list; CheckedList(List<E> list, Class<E> type) { super(list, type); this.list = list; } public boolean equals(Object o) { return o == this || list.equals(o); } public int hashCode() { return list.hashCode(); } public E get(int index) { return list.get(index); } public E remove(int index) { return list.remove(index); } public int indexOf(Object o) { return list.indexOf(o); } public int lastIndexOf(Object o) { return list.lastIndexOf(o); } public E set(int index, E element) { typeCheck(element); return list.set(index, element); } public void add(int index, E element) { typeCheck(element); list.add(index, element); } public boolean addAll(int index, Collection<? extends E> c) { return list.addAll(index, checkedCopyOf(c)); } public ListIterator<E> listIterator() { return listIterator(0); } public ListIterator<E> listIterator(final int index) { final ListIterator<E> i = list.listIterator(index); return new ListIterator<E>() { public boolean hasNext() { return i.hasNext(); } public E next() { return i.next(); } public boolean hasPrevious() { return i.hasPrevious(); } public E previous() { return i.previous(); } public int nextIndex() { return i.nextIndex(); } public int previousIndex() { return i.previousIndex(); } public void remove() { i.remove(); } public void set(E e) { typeCheck(e); i.set(e); } public void add(E e) { typeCheck(e); i.add(e); } }; } public List<E> subList(int fromIndex, int toIndex) { return new CheckedList<E>(list.subList(fromIndex, toIndex), type); } } /** {@collect.stats} * @serial include */ static class CheckedRandomAccessList<E> extends CheckedList<E> implements RandomAccess { private static final long serialVersionUID = 1638200125423088369L; CheckedRandomAccessList(List<E> list, Class<E> type) { super(list, type); } public List<E> subList(int fromIndex, int toIndex) { return new CheckedRandomAccessList<E>( list.subList(fromIndex, toIndex), type); } } /** {@collect.stats} * {@description.open} * Returns a dynamically typesafe view of the specified map. * Any attempt to insert a mapping whose key or value have the wrong * type will result in an immediate {@link ClassCastException}. * Similarly, any attempt to modify the value currently associated with * a key will result in an immediate {@link ClassCastException}, * whether the modification is attempted directly through the map * itself, or through a {@link Map.Entry} instance obtained from the * map's {@link Map#entrySet() entry set} view. * * <p>Assuming a map contains no incorrectly typed keys or values * prior to the time a dynamically typesafe view is generated, and * that all subsequent access to the map takes place through the view * (or one of its collection views), it is <i>guaranteed</i> that the * map cannot contain an incorrectly typed key or value. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned map will be serializable if the specified map is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned map permits insertion of null keys or values * whenever the backing map does. * {@description.close} * * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold * @param valueType the type of value that {@code m} is permitted to hold * @return a dynamically typesafe view of the specified map * @since 1.5 */ public static <K, V> Map<K, V> checkedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) { return new CheckedMap<K,V>(m, keyType, valueType); } /** {@collect.stats} * @serial include */ private static class CheckedMap<K,V> implements Map<K,V>, Serializable { private static final long serialVersionUID = 5742860141034234728L; private final Map<K, V> m; final Class<K> keyType; final Class<V> valueType; private void typeCheck(Object key, Object value) { if (key != null && !keyType.isInstance(key)) throw new ClassCastException(badKeyMsg(key)); if (value != null && !valueType.isInstance(value)) throw new ClassCastException(badValueMsg(value)); } private String badKeyMsg(Object key) { return "Attempt to insert " + key.getClass() + " key into map with key type " + keyType; } private String badValueMsg(Object value) { return "Attempt to insert " + value.getClass() + " value into map with value type " + valueType; } CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) { if (m == null || keyType == null || valueType == null) throw new NullPointerException(); this.m = m; this.keyType = keyType; this.valueType = valueType; } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean containsKey(Object key) { return m.containsKey(key); } public boolean containsValue(Object v) { return m.containsValue(v); } public V get(Object key) { return m.get(key); } public V remove(Object key) { return m.remove(key); } public void clear() { m.clear(); } public Set<K> keySet() { return m.keySet(); } public Collection<V> values() { return m.values(); } public boolean equals(Object o) { return o == this || m.equals(o); } public int hashCode() { return m.hashCode(); } public String toString() { return m.toString(); } public V put(K key, V value) { typeCheck(key, value); return m.put(key, value); } @SuppressWarnings("unchecked") public void putAll(Map<? extends K, ? extends V> t) { // Satisfy the following goals: // - good diagnostics in case of type mismatch // - all-or-nothing semantics // - protection from malicious t // - correct behavior if t is a concurrent map Object[] entries = t.entrySet().toArray(); List<Map.Entry<K,V>> checked = new ArrayList<Map.Entry<K,V>>(entries.length); for (Object o : entries) { Map.Entry<?,?> e = (Map.Entry<?,?>) o; Object k = e.getKey(); Object v = e.getValue(); typeCheck(k, v); checked.add( new AbstractMap.SimpleImmutableEntry<K,V>((K) k, (V) v)); } for (Map.Entry<K,V> e : checked) m.put(e.getKey(), e.getValue()); } private transient Set<Map.Entry<K,V>> entrySet = null; public Set<Map.Entry<K,V>> entrySet() { if (entrySet==null) entrySet = new CheckedEntrySet<K,V>(m.entrySet(), valueType); return entrySet; } /** {@collect.stats} * {@description.open} * We need this class in addition to CheckedSet as Map.Entry permits * modification of the backing Map via the setValue operation. This * class is subtle: there are many possible attacks that must be * thwarted. * {@description.close} * * @serial exclude */ static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> { private final Set<Map.Entry<K,V>> s; private final Class<V> valueType; CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) { this.s = s; this.valueType = valueType; } public int size() { return s.size(); } public boolean isEmpty() { return s.isEmpty(); } public String toString() { return s.toString(); } public int hashCode() { return s.hashCode(); } public void clear() { s.clear(); } public boolean add(Map.Entry<K, V> e) { throw new UnsupportedOperationException(); } public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) { throw new UnsupportedOperationException(); } public Iterator<Map.Entry<K,V>> iterator() { final Iterator<Map.Entry<K, V>> i = s.iterator(); final Class<V> valueType = this.valueType; return new Iterator<Map.Entry<K,V>>() { public boolean hasNext() { return i.hasNext(); } public void remove() { i.remove(); } public Map.Entry<K,V> next() { return checkedEntry(i.next(), valueType); } }; } @SuppressWarnings("unchecked") public Object[] toArray() { Object[] source = s.toArray(); /* * Ensure that we don't get an ArrayStoreException even if * s.toArray returns an array of something other than Object */ Object[] dest = (CheckedEntry.class.isInstance( source.getClass().getComponentType()) ? source : new Object[source.length]); for (int i = 0; i < source.length; i++) dest[i] = checkedEntry((Map.Entry<K,V>)source[i], valueType); return dest; } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { // We don't pass a to s.toArray, to avoid window of // vulnerability wherein an unscrupulous multithreaded client // could get his hands on raw (unwrapped) Entries from s. T[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0)); for (int i=0; i<arr.length; i++) arr[i] = (T) checkedEntry((Map.Entry<K,V>)arr[i], valueType); if (arr.length > a.length) return arr; System.arraycopy(arr, 0, a, 0, arr.length); if (a.length > arr.length) a[arr.length] = null; return a; } /** {@collect.stats} * {@description.open} * This method is overridden to protect the backing set against * an object with a nefarious equals function that senses * that the equality-candidate is Map.Entry and calls its * setValue method. * {@description.close} */ public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>) o; return s.contains( (e instanceof CheckedEntry) ? e : checkedEntry(e, valueType)); } /** {@collect.stats} * {@description.open} * The bulk collection methods are overridden to protect * against an unscrupulous collection whose contains(Object o) * method senses when o is a Map.Entry, and calls o.setValue. * {@description.close} */ public boolean containsAll(Collection<?> c) { for (Object o : c) if (!contains(o)) // Invokes safe contains() above return false; return true; } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; return s.remove(new AbstractMap.SimpleImmutableEntry <Object, Object>((Map.Entry<?,?>)o)); } public boolean removeAll(Collection<?> c) { return batchRemove(c, false); } public boolean retainAll(Collection<?> c) { return batchRemove(c, true); } private boolean batchRemove(Collection<?> c, boolean complement) { boolean modified = false; Iterator<Map.Entry<K,V>> it = iterator(); while (it.hasNext()) { if (c.contains(it.next()) != complement) { it.remove(); modified = true; } } return modified; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Set<?> that = (Set<?>) o; return that.size() == s.size() && containsAll(that); // Invokes safe containsAll() above } static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e, Class<T> valueType) { return new CheckedEntry<K,V,T>(e, valueType); } /** {@collect.stats} * {@description.open} * This "wrapper class" serves two purposes: it prevents * the client from modifying the backing Map, by short-circuiting * the setValue method, and it protects the backing Map against * an ill-behaved Map.Entry that attempts to modify another * Map.Entry when asked to perform an equality check. * {@description.close} */ private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> { private final Map.Entry<K, V> e; private final Class<T> valueType; CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) { this.e = e; this.valueType = valueType; } public K getKey() { return e.getKey(); } public V getValue() { return e.getValue(); } public int hashCode() { return e.hashCode(); } public String toString() { return e.toString(); } public V setValue(V value) { if (value != null && !valueType.isInstance(value)) throw new ClassCastException(badValueMsg(value)); return e.setValue(value); } private String badValueMsg(Object value) { return "Attempt to insert " + value.getClass() + " value into map with value type " + valueType; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Map.Entry)) return false; return e.equals(new AbstractMap.SimpleImmutableEntry <Object, Object>((Map.Entry<?,?>)o)); } } } } /** {@collect.stats} * {@description.open} * Returns a dynamically typesafe view of the specified sorted map. * Any attempt to insert a mapping whose key or value have the wrong * type will result in an immediate {@link ClassCastException}. * Similarly, any attempt to modify the value currently associated with * a key will result in an immediate {@link ClassCastException}, * whether the modification is attempted directly through the map * itself, or through a {@link Map.Entry} instance obtained from the * map's {@link Map#entrySet() entry set} view. * * <p>Assuming a map contains no incorrectly typed keys or values * prior to the time a dynamically typesafe view is generated, and * that all subsequent access to the map takes place through the view * (or one of its collection views), it is <i>guaranteed</i> that the * map cannot contain an incorrectly typed key or value. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned map will be serializable if the specified map is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned map permits insertion of null keys or values * whenever the backing map does. * {@description.close} * * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold * @param valueType the type of value that {@code m} is permitted to hold * @return a dynamically typesafe view of the specified map * @since 1.5 */ public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m, Class<K> keyType, Class<V> valueType) { return new CheckedSortedMap<K,V>(m, keyType, valueType); } /** {@collect.stats} * @serial include */ static class CheckedSortedMap<K,V> extends CheckedMap<K,V> implements SortedMap<K,V>, Serializable { private static final long serialVersionUID = 1599671320688067438L; private final SortedMap<K, V> sm; CheckedSortedMap(SortedMap<K, V> m, Class<K> keyType, Class<V> valueType) { super(m, keyType, valueType); sm = m; } public Comparator<? super K> comparator() { return sm.comparator(); } public K firstKey() { return sm.firstKey(); } public K lastKey() { return sm.lastKey(); } public SortedMap<K,V> subMap(K fromKey, K toKey) { return checkedSortedMap(sm.subMap(fromKey, toKey), keyType, valueType); } public SortedMap<K,V> headMap(K toKey) { return checkedSortedMap(sm.headMap(toKey), keyType, valueType); } public SortedMap<K,V> tailMap(K fromKey) { return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType); } } // Empty collections /** {@collect.stats} * {@description.open} * Returns an iterator that has no elements. More precisely, * * <ul compact> * * <li>{@link Iterator#hasNext hasNext} always returns {@code * false}. * * <li>{@link Iterator#next next} always throws {@link * NoSuchElementException}. * * <li>{@link Iterator#remove remove} always throws {@link * IllegalStateException}. * * </ul> * * <p>Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * {@description.close} * * @return an empty iterator * @since 1.7 */ @SuppressWarnings("unchecked") static <T> Iterator<T> emptyIterator() { return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR; } private static class EmptyIterator<E> implements Iterator<E> { static final EmptyIterator<Object> EMPTY_ITERATOR = new EmptyIterator<Object>(); public boolean hasNext() { return false; } public E next() { throw new NoSuchElementException(); } public void remove() { throw new IllegalStateException(); } } /** {@collect.stats} * {@description.open} * Returns a list iterator that has no elements. More precisely, * * <ul compact> * * <li>{@link Iterator#hasNext hasNext} and {@link * ListIterator#hasPrevious hasPrevious} always return {@code * false}. * * <li>{@link Iterator#next next} and {@link ListIterator#previous * previous} always throw {@link NoSuchElementException}. * * <li>{@link Iterator#remove remove} and {@link ListIterator#set * set} always throw {@link IllegalStateException}. * * <li>{@link ListIterator#add add} always throws {@link * UnsupportedOperationException}. * * <li>{@link ListIterator#nextIndex nextIndex} always returns * {@code 0} . * * <li>{@link ListIterator#previousIndex previousIndex} always * returns {@code -1}. * * </ul> * * <p>Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * {@description.close} * * @return an empty list iterator * @since 1.7 */ @SuppressWarnings("unchecked") static <T> ListIterator<T> emptyListIterator() { return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR; } private static class EmptyListIterator<E> extends EmptyIterator<E> implements ListIterator<E> { static final EmptyListIterator<Object> EMPTY_ITERATOR = new EmptyListIterator<Object>(); public boolean hasPrevious() { return false; } public E previous() { throw new NoSuchElementException(); } public int nextIndex() { return 0; } public int previousIndex() { return -1; } public void set(E e) { throw new IllegalStateException(); } public void add(E e) { throw new UnsupportedOperationException(); } } /** {@collect.stats} * {@description.open} * Returns an enumeration that has no elements. More precisely, * * <ul compact> * * <li>{@link Enumeration#hasMoreElements hasMoreElements} always * returns {@code false}. * * <li> {@link Enumeration#nextElement nextElement} always throws * {@link NoSuchElementException}. * * </ul> * * <p>Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * {@description.close} * * @return an empty enumeration * @since 1.7 */ @SuppressWarnings("unchecked") static <T> Enumeration<T> emptyEnumeration() { return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION; } private static class EmptyEnumeration<E> implements Enumeration<E> { static final EmptyEnumeration<Object> EMPTY_ENUMERATION = new EmptyEnumeration<Object>(); public boolean hasMoreElements() { return false; } public E nextElement() { throw new NoSuchElementException(); } } /** {@collect.stats} * {@description.open} * The empty set (immutable). This set is serializable. * {@description.close} * * @see #emptySet() */ @SuppressWarnings("unchecked") public static final Set EMPTY_SET = new EmptySet<Object>(); /** {@collect.stats} * {@description.open} * Returns the empty set (immutable). This set is serializable. * Unlike the like-named field, this method is parameterized. * * <p>This example illustrates the type-safe way to obtain an empty set: * <pre> * Set&lt;String&gt; s = Collections.emptySet(); * </pre> * Implementation note: Implementations of this method need not * create a separate <tt>Set</tt> object for each call. Using this * method is likely to have comparable cost to using the like-named * field. (Unlike this method, the field does not provide type safety.) * {@description.close} * * @see #EMPTY_SET * @since 1.5 */ @SuppressWarnings("unchecked") public static final <T> Set<T> emptySet() { return (Set<T>) EMPTY_SET; } /** {@collect.stats} * @serial include */ private static class EmptySet<E> extends AbstractSet<E> implements Serializable { private static final long serialVersionUID = 1582296315990362920L; public Iterator<E> iterator() { return emptyIterator(); } public int size() {return 0;} public boolean isEmpty() {return true;} public boolean contains(Object obj) {return false;} public boolean containsAll(Collection<?> c) { return c.isEmpty(); } public Object[] toArray() { return new Object[0]; } public <T> T[] toArray(T[] a) { if (a.length > 0) a[0] = null; return a; } // Preserves singleton property private Object readResolve() { return EMPTY_SET; } } /** {@collect.stats} * {@description.open} * The empty list (immutable). This list is serializable. * {@description.close} * * @see #emptyList() */ @SuppressWarnings("unchecked") public static final List EMPTY_LIST = new EmptyList<Object>(); /** {@collect.stats} * {@description.open} * Returns the empty list (immutable). This list is serializable. * * <p>This example illustrates the type-safe way to obtain an empty list: * <pre> * List&lt;String&gt; s = Collections.emptyList(); * </pre> * Implementation note: Implementations of this method need not * create a separate <tt>List</tt> object for each call. Using this * method is likely to have comparable cost to using the like-named * field. (Unlike this method, the field does not provide type safety.) * {@description.close} * * @see #EMPTY_LIST * @since 1.5 */ @SuppressWarnings("unchecked") public static final <T> List<T> emptyList() { return (List<T>) EMPTY_LIST; } /** {@collect.stats} * @serial include */ private static class EmptyList<E> extends AbstractList<E> implements RandomAccess, Serializable { private static final long serialVersionUID = 8842843931221139166L; public Iterator<E> iterator() { return emptyIterator(); } public ListIterator<E> listIterator() { return emptyListIterator(); } public int size() {return 0;} public boolean isEmpty() {return true;} public boolean contains(Object obj) {return false;} public boolean containsAll(Collection<?> c) { return c.isEmpty(); } public Object[] toArray() { return new Object[0]; } public <T> T[] toArray(T[] a) { if (a.length > 0) a[0] = null; return a; } public E get(int index) { throw new IndexOutOfBoundsException("Index: "+index); } public boolean equals(Object o) { return (o instanceof List) && ((List<?>)o).isEmpty(); } public int hashCode() { return 1; } // Preserves singleton property private Object readResolve() { return EMPTY_LIST; } } /** {@collect.stats} * {@description.open} * The empty map (immutable). This map is serializable. * {@description.close} * * @see #emptyMap() * @since 1.3 */ @SuppressWarnings("unchecked") public static final Map EMPTY_MAP = new EmptyMap<Object,Object>(); /** {@collect.stats} * {@description.open} * Returns the empty map (immutable). This map is serializable. * * <p>This example illustrates the type-safe way to obtain an empty set: * <pre> * Map&lt;String, Date&gt; s = Collections.emptyMap(); * </pre> * Implementation note: Implementations of this method need not * create a separate <tt>Map</tt> object for each call. Using this * method is likely to have comparable cost to using the like-named * field. (Unlike this method, the field does not provide type safety.) * {@description.close} * * @see #EMPTY_MAP * @since 1.5 */ @SuppressWarnings("unchecked") public static final <K,V> Map<K,V> emptyMap() { return (Map<K,V>) EMPTY_MAP; } private static class EmptyMap<K,V> extends AbstractMap<K,V> implements Serializable { private static final long serialVersionUID = 6428348081105594320L; public int size() {return 0;} public boolean isEmpty() {return true;} public boolean containsKey(Object key) {return false;} public boolean containsValue(Object value) {return false;} public V get(Object key) {return null;} public Set<K> keySet() {return emptySet();} public Collection<V> values() {return emptySet();} public Set<Map.Entry<K,V>> entrySet() {return emptySet();} public boolean equals(Object o) { return (o instanceof Map) && ((Map<?,?>)o).isEmpty(); } public int hashCode() {return 0;} // Preserves singleton property private Object readResolve() { return EMPTY_MAP; } } // Singleton collections /** {@collect.stats} * {@description.open} * Returns an immutable set containing only the specified object. * The returned set is serializable. * {@description.close} * * @param o the sole object to be stored in the returned set. * @return an immutable set containing only the specified object. */ public static <T> Set<T> singleton(T o) { return new SingletonSet<T>(o); } static <E> Iterator<E> singletonIterator(final E e) { return new Iterator<E>() { private boolean hasNext = true; public boolean hasNext() { return hasNext; } public E next() { if (hasNext) { hasNext = false; return e; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } }; } /** {@collect.stats} * @serial include */ private static class SingletonSet<E> extends AbstractSet<E> implements Serializable { private static final long serialVersionUID = 3193687207550431679L; final private E element; SingletonSet(E e) {element = e;} public Iterator<E> iterator() { return singletonIterator(element); } public int size() {return 1;} public boolean contains(Object o) {return eq(o, element);} } /** {@collect.stats} * {@description.open} * Returns an immutable list containing only the specified object. * The returned list is serializable. * {@description.close} * * @param o the sole object to be stored in the returned list. * @return an immutable list containing only the specified object. * @since 1.3 */ public static <T> List<T> singletonList(T o) { return new SingletonList<T>(o); } private static class SingletonList<E> extends AbstractList<E> implements RandomAccess, Serializable { private static final long serialVersionUID = 3093736618740652951L; private final E element; SingletonList(E obj) {element = obj;} public Iterator<E> iterator() { return singletonIterator(element); } public int size() {return 1;} public boolean contains(Object obj) {return eq(obj, element);} public E get(int index) { if (index != 0) throw new IndexOutOfBoundsException("Index: "+index+", Size: 1"); return element; } } /** {@collect.stats} * {@description.open} * Returns an immutable map, mapping only the specified key to the * specified value. The returned map is serializable. * {@description.close} * * @param key the sole key to be stored in the returned map. * @param value the value to which the returned map maps <tt>key</tt>. * @return an immutable map containing only the specified key-value * mapping. * @since 1.3 */ public static <K,V> Map<K,V> singletonMap(K key, V value) { return new SingletonMap<K,V>(key, value); } private static class SingletonMap<K,V> extends AbstractMap<K,V> implements Serializable { private static final long serialVersionUID = -6979724477215052911L; private final K k; private final V v; SingletonMap(K key, V value) { k = key; v = value; } public int size() {return 1;} public boolean isEmpty() {return false;} public boolean containsKey(Object key) {return eq(key, k);} public boolean containsValue(Object value) {return eq(value, v);} public V get(Object key) {return (eq(key, k) ? v : null);} private transient Set<K> keySet = null; private transient Set<Map.Entry<K,V>> entrySet = null; private transient Collection<V> values = null; public Set<K> keySet() { if (keySet==null) keySet = singleton(k); return keySet; } public Set<Map.Entry<K,V>> entrySet() { if (entrySet==null) entrySet = Collections.<Map.Entry<K,V>>singleton( new SimpleImmutableEntry<K,V>(k, v)); return entrySet; } public Collection<V> values() { if (values==null) values = singleton(v); return values; } } // Miscellaneous /** {@collect.stats} * {@description.open} * Returns an immutable list consisting of <tt>n</tt> copies of the * specified object. The newly allocated data object is tiny (it contains * a single reference to the data object). This method is useful in * combination with the <tt>List.addAll</tt> method to grow lists. * The returned list is serializable. * {@description.close} * * @param n the number of elements in the returned list. * @param o the element to appear repeatedly in the returned list. * @return an immutable list consisting of <tt>n</tt> copies of the * specified object. * @throws IllegalArgumentException if n &lt; 0. * @see List#addAll(Collection) * @see List#addAll(int, Collection) */ public static <T> List<T> nCopies(int n, T o) { if (n < 0) throw new IllegalArgumentException("List length = " + n); return new CopiesList<T>(n, o); } /** {@collect.stats} * @serial include */ private static class CopiesList<E> extends AbstractList<E> implements RandomAccess, Serializable { private static final long serialVersionUID = 2739099268398711800L; final int n; final E element; CopiesList(int n, E e) { assert n >= 0; this.n = n; element = e; } public int size() { return n; } public boolean contains(Object obj) { return n != 0 && eq(obj, element); } public int indexOf(Object o) { return contains(o) ? 0 : -1; } public int lastIndexOf(Object o) { return contains(o) ? n - 1 : -1; } public E get(int index) { if (index < 0 || index >= n) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+n); return element; } public Object[] toArray() { final Object[] a = new Object[n]; if (element != null) Arrays.fill(a, 0, n, element); return a; } public <T> T[] toArray(T[] a) { final int n = this.n; if (a.length < n) { a = (T[])java.lang.reflect.Array .newInstance(a.getClass().getComponentType(), n); if (element != null) Arrays.fill(a, 0, n, element); } else { Arrays.fill(a, 0, n, element); if (a.length > n) a[n] = null; } return a; } public List<E> subList(int fromIndex, int toIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > n) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); return new CopiesList<E>(toIndex - fromIndex, element); } } /** {@collect.stats} * {@description.open} * Returns a comparator that imposes the reverse of the <i>natural * ordering</i> on a collection of objects that implement the * <tt>Comparable</tt> interface. (The natural ordering is the ordering * imposed by the objects' own <tt>compareTo</tt> method.) This enables a * simple idiom for sorting (or maintaining) collections (or arrays) of * objects that implement the <tt>Comparable</tt> interface in * reverse-natural-order. For example, suppose a is an array of * strings. Then: <pre> * Arrays.sort(a, Collections.reverseOrder()); * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p> * * The returned comparator is serializable. * {@description.close} * * @return a comparator that imposes the reverse of the <i>natural * ordering</i> on a collection of objects that implement * the <tt>Comparable</tt> interface. * @see Comparable */ public static <T> Comparator<T> reverseOrder() { return (Comparator<T>) ReverseComparator.REVERSE_ORDER; } /** {@collect.stats} * @serial include */ private static class ReverseComparator implements Comparator<Comparable<Object>>, Serializable { private static final long serialVersionUID = 7207038068494060240L; static final ReverseComparator REVERSE_ORDER = new ReverseComparator(); public int compare(Comparable<Object> c1, Comparable<Object> c2) { return c2.compareTo(c1); } private Object readResolve() { return reverseOrder(); } } /** {@collect.stats} * {@description.open} * Returns a comparator that imposes the reverse ordering of the specified * comparator. If the specified comparator is null, this method is * equivalent to {@link #reverseOrder()} (in other words, it returns a * comparator that imposes the reverse of the <i>natural ordering</i> on a * collection of objects that implement the Comparable interface). * * <p>The returned comparator is serializable (assuming the specified * comparator is also serializable or null). * {@description.close} * * @return a comparator that imposes the reverse ordering of the * specified comparator * @since 1.5 */ public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) { if (cmp == null) return reverseOrder(); if (cmp instanceof ReverseComparator2) return ((ReverseComparator2<T>)cmp).cmp; return new ReverseComparator2<T>(cmp); } /** {@collect.stats} * @serial include */ private static class ReverseComparator2<T> implements Comparator<T>, Serializable { private static final long serialVersionUID = 4374092139857L; /** {@collect.stats} * {@description.open} * The comparator specified in the static factory. This will never * be null, as the static factory returns a ReverseComparator * instance if its argument is null. * {@description.close} * * @serial */ final Comparator<T> cmp; ReverseComparator2(Comparator<T> cmp) { assert cmp != null; this.cmp = cmp; } public int compare(T t1, T t2) { return cmp.compare(t2, t1); } public boolean equals(Object o) { return (o == this) || (o instanceof ReverseComparator2 && cmp.equals(((ReverseComparator2)o).cmp)); } public int hashCode() { return cmp.hashCode() ^ Integer.MIN_VALUE; } } /** {@collect.stats} * {@description.open} * Returns an enumeration over the specified collection. This provides * interoperability with legacy APIs that require an enumeration * as input. * {@description.close} * * @param c the collection for which an enumeration is to be returned. * @return an enumeration over the specified collection. * @see Enumeration */ public static <T> Enumeration<T> enumeration(final Collection<T> c) { return new Enumeration<T>() { private final Iterator<T> i = c.iterator(); public boolean hasMoreElements() { return i.hasNext(); } public T nextElement() { return i.next(); } }; } /** {@collect.stats} * {@description.open} * Returns an array list containing the elements returned by the * specified enumeration in the order they are returned by the * enumeration. This method provides interoperability between * legacy APIs that return enumerations and new APIs that require * collections. * {@description.close} * * @param e enumeration providing elements for the returned * array list * @return an array list containing the elements returned * by the specified enumeration. * @since 1.4 * @see Enumeration * @see ArrayList */ public static <T> ArrayList<T> list(Enumeration<T> e) { ArrayList<T> l = new ArrayList<T>(); while (e.hasMoreElements()) l.add(e.nextElement()); return l; } /** {@collect.stats} * {@description.open} * Returns true if the specified arguments are equal, or both null. * {@description.close} */ static boolean eq(Object o1, Object o2) { return o1==null ? o2==null : o1.equals(o2); } /** {@collect.stats} * {@description.open} * Returns the number of elements in the specified collection equal to the * specified object. More formally, returns the number of elements * <tt>e</tt> in the collection such that * <tt>(o == null ? e == null : o.equals(e))</tt>. * {@description.close} * * @param c the collection in which to determine the frequency * of <tt>o</tt> * @param o the object whose frequency is to be determined * @throws NullPointerException if <tt>c</tt> is null * @since 1.5 */ public static int frequency(Collection<?> c, Object o) { int result = 0; if (o == null) { for (Object e : c) if (e == null) result++; } else { for (Object e : c) if (o.equals(e)) result++; } return result; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if the two specified collections have no * elements in common. * * <p>Care must be exercised if this method is used on collections that * do not comply with the general contract for <tt>Collection</tt>. * Implementations may elect to iterate over either collection and test * for containment in the other collection (or to perform any equivalent * computation). If either collection uses a nonstandard equality test * (as does a {@link SortedSet} whose ordering is not <i>compatible with * equals</i>, or the key set of an {@link IdentityHashMap}), both * collections must use the same nonstandard equality test, or the * result of this method is undefined. * * <p>Note that it is permissible to pass the same collection in both * parameters, in which case the method will return true if and only if * the collection is empty. * {@description.close} * * @param c1 a collection * @param c2 a collection * @throws NullPointerException if either collection is null * @since 1.5 */ public static boolean disjoint(Collection<?> c1, Collection<?> c2) { /* * We're going to iterate through c1 and test for inclusion in c2. * If c1 is a Set and c2 isn't, swap the collections. Otherwise, * place the shorter collection in c1. Hopefully this heuristic * will minimize the cost of the operation. */ if ((c1 instanceof Set) && !(c2 instanceof Set) || (c1.size() > c2.size())) { Collection<?> tmp = c1; c1 = c2; c2 = tmp; } for (Object e : c1) if (c2.contains(e)) return false; return true; } /** {@collect.stats} * {@description.open} * Adds all of the specified elements to the specified collection. * Elements to be added may be specified individually or as an array. * The behavior of this convenience method is identical to that of * <tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely * to run significantly faster under most implementations. * * <p>When elements are specified individually, this method provides a * convenient way to add a few elements to an existing collection: * <pre> * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon"); * </pre> * {@description.close} * * @param c the collection into which <tt>elements</tt> are to be inserted * @param elements the elements to insert into <tt>c</tt> * @return <tt>true</tt> if the collection changed as a result of the call * @throws UnsupportedOperationException if <tt>c</tt> does not support * the <tt>add</tt> operation * @throws NullPointerException if <tt>elements</tt> contains one or more * null values and <tt>c</tt> does not permit null elements, or * if <tt>c</tt> or <tt>elements</tt> are <tt>null</tt> * @throws IllegalArgumentException if some property of a value in * <tt>elements</tt> prevents it from being added to <tt>c</tt> * @see Collection#addAll(Collection) * @since 1.5 */ public static <T> boolean addAll(Collection<? super T> c, T... elements) { boolean result = false; for (T element : elements) result |= c.add(element); return result; } /** {@collect.stats} * {@description.open} * Returns a set backed by the specified map. The resulting set displays * the same ordering, concurrency, and performance characteristics as the * backing map. In essence, this factory method provides a {@link Set} * implementation corresponding to any {@link Map} implementation. * {@description.close} * {@property.open formal:java.util.Collections_UnnecessaryNewSetFromMap} * There * is no need to use this method on a {@link Map} implementation that * already has a corresponding {@link Set} implementation (such as {@link * HashMap} or {@link TreeMap}). * {@property.close} * * <p>Each method invocation on the set returned by this method results in * exactly one method invocation on the backing map or its <tt>keySet</tt> * view, with one exception. The <tt>addAll</tt> method is implemented * as a sequence of <tt>put</tt> invocations on the backing map. * {@description.close} * * {@property.open formal:java.util.Collections_NewSetFromMap} * <p>The specified map must be empty at the time this method is invoked, * and should not be accessed directly after this method returns. These * conditions are ensured if the map is created empty, passed directly * to this method, and no reference to the map is retained, as illustrated * in the following code fragment: * <pre> * Set&lt;Object&gt; weakHashSet = Collections.newSetFromMap( * new WeakHashMap&lt;Object, Boolean&gt;()); * </pre> * {@property.close} * * @param map the backing map * @return the set backed by the map * @throws IllegalArgumentException if <tt>map</tt> is not empty * @since 1.6 */ public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) { return new SetFromMap<E>(map); } private static class SetFromMap<E> extends AbstractSet<E> implements Set<E>, Serializable { private final Map<E, Boolean> m; // The backing map private transient Set<E> s; // Its keySet SetFromMap(Map<E, Boolean> map) { if (!map.isEmpty()) throw new IllegalArgumentException("Map is non-empty"); m = map; s = map.keySet(); } public void clear() { m.clear(); } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean contains(Object o) { return m.containsKey(o); } public boolean remove(Object o) { return m.remove(o) != null; } public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; } public Iterator<E> iterator() { return s.iterator(); } public Object[] toArray() { return s.toArray(); } public <T> T[] toArray(T[] a) { return s.toArray(a); } public String toString() { return s.toString(); } public int hashCode() { return s.hashCode(); } public boolean equals(Object o) { return o == this || s.equals(o); } public boolean containsAll(Collection<?> c) {return s.containsAll(c);} public boolean removeAll(Collection<?> c) {return s.removeAll(c);} public boolean retainAll(Collection<?> c) {return s.retainAll(c);} // addAll is the only inherited implementation private static final long serialVersionUID = 2454657854757543876L; private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); s = m.keySet(); } } /** {@collect.stats} * {@description.open} * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo) * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>, * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This * view can be useful when you would like to use a method * requiring a <tt>Queue</tt> but you need Lifo ordering. * * <p>Each method invocation on the queue returned by this method * results in exactly one method invocation on the backing deque, with * one exception. The {@link Queue#addAll addAll} method is * implemented as a sequence of {@link Deque#addFirst addFirst} * invocations on the backing deque. * {@description.close} * * @param deque the deque * @return the queue * @since 1.6 */ public static <T> Queue<T> asLifoQueue(Deque<T> deque) { return new AsLIFOQueue<T>(deque); } static class AsLIFOQueue<E> extends AbstractQueue<E> implements Queue<E>, Serializable { private static final long serialVersionUID = 1802017725587941708L; private final Deque<E> q; AsLIFOQueue(Deque<E> q) { this.q = q; } public boolean add(E e) { q.addFirst(e); return true; } public boolean offer(E e) { return q.offerFirst(e); } public E poll() { return q.pollFirst(); } public E remove() { return q.removeFirst(); } public E peek() { return q.peekFirst(); } public E element() { return q.getFirst(); } public void clear() { q.clear(); } public int size() { return q.size(); } public boolean isEmpty() { return q.isEmpty(); } public boolean contains(Object o) { return q.contains(o); } public boolean remove(Object o) { return q.remove(o); } public Iterator<E> iterator() { return q.iterator(); } public Object[] toArray() { return q.toArray(); } public <T> T[] toArray(T[] a) { return q.toArray(a); } public String toString() { return q.toString(); } public boolean containsAll(Collection<?> c) {return q.containsAll(c);} public boolean removeAll(Collection<?> c) {return q.removeAll(c);} public boolean retainAll(Collection<?> c) {return q.retainAll(c);} // We use inherited addAll; forwarding addAll would be wrong } }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * A {@link Map} that further provides a <i>total ordering</i> on its keys. * The map is ordered according to the {@linkplain Comparable natural * ordering} of its keys, or by a {@link Comparator} typically * provided at sorted map creation time. This order is reflected when * iterating over the sorted map's collection views (returned by the * <tt>entrySet</tt>, <tt>keySet</tt> and <tt>values</tt> methods). * Several additional operations are provided to take advantage of the * ordering. (This interface is the map analogue of {@link * SortedSet}.) * * <p>All keys inserted into a sorted map must implement the <tt>Comparable</tt> * interface (or be accepted by the specified comparator). Furthermore, all * such keys must be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> (or * <tt>comparator.compare(k1, k2)</tt>) must not throw a * <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in * the sorted map. Attempts to violate this restriction will cause the * offending method or constructor invocation to throw a * <tt>ClassCastException</tt>. * * <p>Note that the ordering maintained by a sorted map (whether or not an * explicit comparator is provided) must be <i>consistent with equals</i> if * the sorted map is to correctly implement the <tt>Map</tt> interface. (See * the <tt>Comparable</tt> interface or <tt>Comparator</tt> interface for a * precise definition of <i>consistent with equals</i>.) This is so because * the <tt>Map</tt> interface is defined in terms of the <tt>equals</tt> * operation, but a sorted map performs all key comparisons using its * <tt>compareTo</tt> (or <tt>compare</tt>) method, so two keys that are * deemed equal by this method are, from the standpoint of the sorted map, * equal. The behavior of a tree map <i>is</i> well-defined even if its * ordering is inconsistent with equals; it just fails to obey the general * contract of the <tt>Map</tt> interface. * {@description.close} * * {@property.open formal:java.util.SortedMap_StandardConstructors} * <p>All general-purpose sorted map implementation classes should * provide four "standard" constructors: 1) A void (no arguments) * constructor, which creates an empty sorted map sorted according to * the natural ordering of its keys. 2) A constructor with a * single argument of type <tt>Comparator</tt>, which creates an empty * sorted map sorted according to the specified comparator. 3) A * constructor with a single argument of type <tt>Map</tt>, which * creates a new map with the same key-value mappings as its argument, * sorted according to the keys' natural ordering. 4) A constructor * with a single argument of type <tt>SortedMap</tt>, * which creates a new sorted map with the same key-value mappings and * the same ordering as the input sorted map. There is no way to * enforce this recommendation, as interfaces cannot contain * constructors. * {@property.close} * * {@description.open} * <p>Note: several methods return submaps with restricted key ranges. * Such ranges are <i>half-open</i>, that is, they include their low * endpoint but not their high endpoint (where applicable). If you need a * <i>closed range</i> (which includes both endpoints), and the key type * allows for calculation of the successor of a given key, merely request * the subrange from <tt>lowEndpoint</tt> to * <tt>successor(highEndpoint)</tt>. For example, suppose that <tt>m</tt> * is a map whose keys are strings. The following idiom obtains a view * containing all of the key-value mappings in <tt>m</tt> whose keys are * between <tt>low</tt> and <tt>high</tt>, inclusive:<pre> * SortedMap&lt;String, V&gt; sub = m.subMap(low, high+"\0");</pre> * * A similar technique can be used to generate an <i>open range</i> * (which contains neither endpoint). The following idiom obtains a * view containing all of the key-value mappings in <tt>m</tt> whose keys * are between <tt>low</tt> and <tt>high</tt>, exclusive:<pre> * SortedMap&lt;String, V&gt; sub = m.subMap(low+"\0", high);</pre> * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Josh Bloch * @see Map * @see TreeMap * @see SortedSet * @see Comparator * @see Comparable * @see Collection * @see ClassCastException * @since 1.2 */ public interface SortedMap<K,V> extends Map<K,V> { /** {@collect.stats} * {@description.open} * Returns the comparator used to order the keys in this map, or * <tt>null</tt> if this map uses the {@linkplain Comparable * natural ordering} of its keys. * {@description.close} * * @return the comparator used to order the keys in this map, * or <tt>null</tt> if this map uses the natural ordering * of its keys */ Comparator<? super K> comparator(); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this map whose keys range from * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive. (If * <tt>fromKey</tt> and <tt>toKey</tt> are equal, the returned map * is empty.) The returned map is backed by this map, so changes * in the returned map are reflected in this map, and vice-versa. * The returned map supports all optional map operations that this * map supports. * * <p>The returned map will throw an <tt>IllegalArgumentException</tt> * on an attempt to insert a key outside its range. * {@description.close} * * @param fromKey low endpoint (inclusive) of the keys in the returned map * @param toKey high endpoint (exclusive) of the keys in the returned map * @return a view of the portion of this map whose keys range from * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive * @throws ClassCastException if <tt>fromKey</tt> and <tt>toKey</tt> * cannot be compared to one another using this map's comparator * (or, if the map has no comparator, using natural ordering). * Implementations may, but are not required to, throw this * exception if <tt>fromKey</tt> or <tt>toKey</tt> * cannot be compared to keys currently in the map. * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> * is null and this map does not permit null keys * @throws IllegalArgumentException if <tt>fromKey</tt> is greater than * <tt>toKey</tt>; or if this map itself has a restricted * range, and <tt>fromKey</tt> or <tt>toKey</tt> lies * outside the bounds of the range */ SortedMap<K,V> subMap(K fromKey, K toKey); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this map whose keys are * strictly less than <tt>toKey</tt>. The returned map is backed * by this map, so changes in the returned map are reflected in * this map, and vice-versa. The returned map supports all * optional map operations that this map supports. * * <p>The returned map will throw an <tt>IllegalArgumentException</tt> * on an attempt to insert a key outside its range. * {@description.close} * * @param toKey high endpoint (exclusive) of the keys in the returned map * @return a view of the portion of this map whose keys are strictly * less than <tt>toKey</tt> * @throws ClassCastException if <tt>toKey</tt> is not compatible * with this map's comparator (or, if the map has no comparator, * if <tt>toKey</tt> does not implement {@link Comparable}). * Implementations may, but are not required to, throw this * exception if <tt>toKey</tt> cannot be compared to keys * currently in the map. * @throws NullPointerException if <tt>toKey</tt> is null and * this map does not permit null keys * @throws IllegalArgumentException if this map itself has a * restricted range, and <tt>toKey</tt> lies outside the * bounds of the range */ SortedMap<K,V> headMap(K toKey); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this map whose keys are * greater than or equal to <tt>fromKey</tt>. The returned map is * backed by this map, so changes in the returned map are * reflected in this map, and vice-versa. The returned map * supports all optional map operations that this map supports. * * <p>The returned map will throw an <tt>IllegalArgumentException</tt> * on an attempt to insert a key outside its range. * {@description.close} * * @param fromKey low endpoint (inclusive) of the keys in the returned map * @return a view of the portion of this map whose keys are greater * than or equal to <tt>fromKey</tt> * @throws ClassCastException if <tt>fromKey</tt> is not compatible * with this map's comparator (or, if the map has no comparator, * if <tt>fromKey</tt> does not implement {@link Comparable}). * Implementations may, but are not required to, throw this * exception if <tt>fromKey</tt> cannot be compared to keys * currently in the map. * @throws NullPointerException if <tt>fromKey</tt> is null and * this map does not permit null keys * @throws IllegalArgumentException if this map itself has a * restricted range, and <tt>fromKey</tt> lies outside the * bounds of the range */ SortedMap<K,V> tailMap(K fromKey); /** {@collect.stats} * {@description.open} * Returns the first (lowest) key currently in this map. * {@description.close} * * @return the first (lowest) key currently in this map * @throws NoSuchElementException if this map is empty */ K firstKey(); /** {@collect.stats} * {@description.open} * Returns the last (highest) key currently in this map. * {@description.close} * * @return the last (highest) key currently in this map * @throws NoSuchElementException if this map is empty */ K lastKey(); /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the keys contained in this map. * The set's iterator returns the keys in ascending order. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. * {@property.close} * * @return a set view of the keys contained in this map, sorted in * ascending order */ Set<K> keySet(); /** {@collect.stats} * {@description.open} * Returns a {@link Collection} view of the values contained in this map. * The collection's iterator returns the values in ascending order * of the corresponding keys. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is * modified while an iteration over the collection is in progress * (except through the iterator's own <tt>remove</tt> operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Collection.remove</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not * support the <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} * * @return a collection view of the values contained in this map, * sorted in ascending key order */ Collection<V> values(); /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the mappings contained in this map. * The set's iterator returns the entries in ascending key order. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation, or through the * <tt>setValue</tt> operation on a map entry returned by the * iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and * <tt>clear</tt> operations. It does not support the * <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} * * @return a set view of the mappings contained in this map, * sorted in ascending key order */ Set<Map.Entry<K, V>> entrySet(); }
Java
/* * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when the argument corresponding to the format * specifier is of an incompatible type. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any * method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @since 1.5 */ public class IllegalFormatConversionException extends IllegalFormatException { private static final long serialVersionUID = 17000126L; private char c; private Class arg; /** {@collect.stats} * {@description.open} * Constructs an instance of this class with the mismatched conversion and * the corresponding argument class. * {@description.close} * * @param c * Inapplicable conversion * * @param arg * Class of the mismatched argument */ public IllegalFormatConversionException(char c, Class<?> arg) { if (arg == null) throw new NullPointerException(); this.c = c; this.arg = arg; } /** {@collect.stats} * {@description.open} * Returns the inapplicable conversion. * {@description.close} * * @return The inapplicable conversion */ public char getConversion() { return c; } /** {@collect.stats} * {@description.open} * Returns the class of the mismatched argument. * {@description.close} * * @return The class of the mismatched argument */ public Class<?> getArgumentClass() { return arg; } // javadoc inherited from Throwable.java public String getMessage() { return String.format("%c != %s", c, arg.getName()); } }
Java
/* * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Private implementation class for EnumSet, for "jumbo" enum types * (i.e., those with more than 64 elements). * {@description.close} * * @author Josh Bloch * @since 1.5 * @serial exclude */ class JumboEnumSet<E extends Enum<E>> extends EnumSet<E> { /** {@collect.stats} * {@description.open} * Bit vector representation of this set. The ith bit of the jth * element of this array represents the presence of universe[64*j +i] * in this set. * {@description.close} */ private long elements[]; // Redundant - maintained for performance private int size = 0; JumboEnumSet(Class<E>elementType, Enum[] universe) { super(elementType, universe); elements = new long[(universe.length + 63) >>> 6]; } void addRange(E from, E to) { int fromIndex = from.ordinal() >>> 6; int toIndex = to.ordinal() >>> 6; if (fromIndex == toIndex) { elements[fromIndex] = (-1L >>> (from.ordinal() - to.ordinal() - 1)) << from.ordinal(); } else { elements[fromIndex] = (-1L << from.ordinal()); for (int i = fromIndex + 1; i < toIndex; i++) elements[i] = -1; elements[toIndex] = -1L >>> (63 - to.ordinal()); } size = to.ordinal() - from.ordinal() + 1; } void addAll() { for (int i = 0; i < elements.length; i++) elements[i] = -1; elements[elements.length - 1] >>>= -universe.length; size = universe.length; } void complement() { for (int i = 0; i < elements.length; i++) elements[i] = ~elements[i]; elements[elements.length - 1] &= (-1L >>> -universe.length); size = universe.length - size; } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements contained in this set. The * iterator traverses the elements in their <i>natural order</i> (which is * the order in which the enum constants are declared). * {@description.close} * {@property.open formal:java.util.Collection_UnsafeIterator} * The returned * Iterator is a "weakly consistent" iterator that will never throw {@link * ConcurrentModificationException}. * {@property.close} * * @return an iterator over the elements contained in this set */ public Iterator<E> iterator() { return new EnumSetIterator<E>(); } private class EnumSetIterator<E extends Enum<E>> implements Iterator<E> { /** {@collect.stats} * {@description.open} * A bit vector representing the elements in the current "word" * of the set not yet returned by this iterator. * {@description.close} */ long unseen; /** {@collect.stats} * {@description.open} * The index corresponding to unseen in the elements array. * {@description.close} */ int unseenIndex = 0; /** {@collect.stats} * {@description.open} * The bit representing the last element returned by this iterator * but not removed, or zero if no such element exists. * {@description.close} */ long lastReturned = 0; /** {@collect.stats} * {@description.open} * The index corresponding to lastReturned in the elements array. * {@description.close} */ int lastReturnedIndex = 0; EnumSetIterator() { unseen = elements[0]; } public boolean hasNext() { while (unseen == 0 && unseenIndex < elements.length - 1) unseen = elements[++unseenIndex]; return unseen != 0; } public E next() { if (!hasNext()) throw new NoSuchElementException(); lastReturned = unseen & -unseen; lastReturnedIndex = unseenIndex; unseen -= lastReturned; return (E) universe[(lastReturnedIndex << 6) + Long.numberOfTrailingZeros(lastReturned)]; } public void remove() { if (lastReturned == 0) throw new IllegalStateException(); elements[lastReturnedIndex] -= lastReturned; size--; lastReturned = 0; } } /** {@collect.stats} * {@description.open} * Returns the number of elements in this set. * {@description.close} * * @return the number of elements in this set */ public int size() { return size; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains no elements. * {@description.close} * * @return <tt>true</tt> if this set contains no elements */ public boolean isEmpty() { return size == 0; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains the specified element. * {@description.close} * * @param e element to be checked for containment in this collection * @return <tt>true</tt> if this set contains the specified element */ public boolean contains(Object e) { if (e == null) return false; Class eClass = e.getClass(); if (eClass != elementType && eClass.getSuperclass() != elementType) return false; int eOrdinal = ((Enum)e).ordinal(); return (elements[eOrdinal >>> 6] & (1L << eOrdinal)) != 0; } // Modification Operations /** {@collect.stats} * {@description.open} * Adds the specified element to this set if it is not already present. * {@description.close} * * @param e element to be added to this set * @return <tt>true</tt> if the set changed as a result of the call * * @throws NullPointerException if <tt>e</tt> is null */ public boolean add(E e) { typeCheck(e); int eOrdinal = e.ordinal(); int eWordNum = eOrdinal >>> 6; long oldElements = elements[eWordNum]; elements[eWordNum] |= (1L << eOrdinal); boolean result = (elements[eWordNum] != oldElements); if (result) size++; return result; } /** {@collect.stats} * {@description.open} * Removes the specified element from this set if it is present. * {@description.close} * * @param e element to be removed from this set, if present * @return <tt>true</tt> if the set contained the specified element */ public boolean remove(Object e) { if (e == null) return false; Class eClass = e.getClass(); if (eClass != elementType && eClass.getSuperclass() != elementType) return false; int eOrdinal = ((Enum)e).ordinal(); int eWordNum = eOrdinal >>> 6; long oldElements = elements[eWordNum]; elements[eWordNum] &= ~(1L << eOrdinal); boolean result = (elements[eWordNum] != oldElements); if (result) size--; return result; } // Bulk Operations /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains all of the elements * in the specified collection. * {@description.close} * * @param c collection to be checked for containment in this set * @return <tt>true</tt> if this set contains all of the elements * in the specified collection * @throws NullPointerException if the specified collection is null */ public boolean containsAll(Collection<?> c) { if (!(c instanceof JumboEnumSet)) return super.containsAll(c); JumboEnumSet es = (JumboEnumSet)c; if (es.elementType != elementType) return es.isEmpty(); for (int i = 0; i < elements.length; i++) if ((es.elements[i] & ~elements[i]) != 0) return false; return true; } /** {@collect.stats} * {@description.open} * Adds all of the elements in the specified collection to this set. * {@description.close} * * @param c collection whose elements are to be added to this set * @return <tt>true</tt> if this set changed as a result of the call * @throws NullPointerException if the specified collection or any of * its elements are null */ public boolean addAll(Collection<? extends E> c) { if (!(c instanceof JumboEnumSet)) return super.addAll(c); JumboEnumSet es = (JumboEnumSet)c; if (es.elementType != elementType) { if (es.isEmpty()) return false; else throw new ClassCastException( es.elementType + " != " + elementType); } for (int i = 0; i < elements.length; i++) elements[i] |= es.elements[i]; return recalculateSize(); } /** {@collect.stats} * {@description.open} * Removes from this set all of its elements that are contained in * the specified collection. * {@description.close} * * @param c elements to be removed from this set * @return <tt>true</tt> if this set changed as a result of the call * @throws NullPointerException if the specified collection is null */ public boolean removeAll(Collection<?> c) { if (!(c instanceof JumboEnumSet)) return super.removeAll(c); JumboEnumSet es = (JumboEnumSet)c; if (es.elementType != elementType) return false; for (int i = 0; i < elements.length; i++) elements[i] &= ~es.elements[i]; return recalculateSize(); } /** {@collect.stats} * {@description.open} * Retains only the elements in this set that are contained in the * specified collection. * {@description.close} * * @param c elements to be retained in this set * @return <tt>true</tt> if this set changed as a result of the call * @throws NullPointerException if the specified collection is null */ public boolean retainAll(Collection<?> c) { if (!(c instanceof JumboEnumSet)) return super.retainAll(c); JumboEnumSet<?> es = (JumboEnumSet<?>)c; if (es.elementType != elementType) { boolean changed = (size != 0); clear(); return changed; } for (int i = 0; i < elements.length; i++) elements[i] &= es.elements[i]; return recalculateSize(); } /** {@collect.stats} * {@description.open} * Removes all of the elements from this set. * {@description.close} */ public void clear() { Arrays.fill(elements, 0); size = 0; } /** {@collect.stats} * {@description.open} * Compares the specified object with this set for equality. Returns * <tt>true</tt> if the given object is also a set, the two sets have * the same size, and every member of the given set is contained in * this set. * {@description.close} * * @param e object to be compared for equality with this set * @return <tt>true</tt> if the specified object is equal to this set */ public boolean equals(Object o) { if (!(o instanceof JumboEnumSet)) return super.equals(o); JumboEnumSet es = (JumboEnumSet)o; if (es.elementType != elementType) return size == 0 && es.size == 0; return Arrays.equals(es.elements, elements); } /** {@collect.stats} * {@description.open} * Recalculates the size of the set. Returns true if it's changed. * {@description.close} */ private boolean recalculateSize() { int oldSize = size; size = 0; for (long elt : elements) size += Long.bitCount(elt); return size != oldSize; } public EnumSet<E> clone() { JumboEnumSet<E> result = (JumboEnumSet<E>) super.clone(); result.elements = (long[]) result.elements.clone(); return result; } }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Error thrown when something goes wrong while loading a service provider. * * <p> This error will be thrown in the following situations: * * <ul> * * <li> The format of a provider-configuration file violates the <a * href="ServiceLoader.html#format">specification</a>; </li> * * <li> An {@link java.io.IOException IOException} occurs while reading a * provider-configuration file; </li> * * <li> A concrete provider class named in a provider-configuration file * cannot be found; </li> * * <li> A concrete provider class is not a subclass of the service class; * </li> * * <li> A concrete provider class cannot be instantiated; or * * <li> Some other kind of error occurs. </li> * * </ul> * {@description.close} * * * @author Mark Reinhold * @since 1.6 */ public class ServiceConfigurationError extends Error { private static final long serialVersionUID = 74132770414881L; /** {@collect.stats} * {@description.open} * Constructs a new instance with the specified message. * {@description.close} * * @param msg The message, or <tt>null</tt> if there is no message * */ public ServiceConfigurationError(String msg) { super(msg); } /** {@collect.stats} * {@description.open} * Constructs a new instance with the specified message and cause. * {@description.close} * * @param msg The message, or <tt>null</tt> if there is no message * * @param cause The cause, or <tt>null</tt> if the cause is nonexistent * or unknown */ public ServiceConfigurationError(String msg, Throwable cause) { super(msg, cause); } }
Java
/* * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when a character with an invalid Unicode code * point as defined by {@link Character#isValidCodePoint} is passed to the * {@link Formatter}. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any * method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @since 1.5 */ public class IllegalFormatCodePointException extends IllegalFormatException { private static final long serialVersionUID = 19080630L; private int c; /** {@collect.stats} * {@description.open} * Constructs an instance of this class with the specified illegal code * point as defined by {@link Character#isValidCodePoint}. * {@description.close} * * @param c * The illegal Unicode code point */ public IllegalFormatCodePointException(int c) { this.c = c; } /** {@collect.stats} * {@description.open} * Returns the illegal code point as defined by {@link * Character#isValidCodePoint}. * {@description.close} * * @return The illegal Unicode code point */ public int getCodePoint() { return c; } public String getMessage() { return String.format("Code point = %#x", c); } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * <p>Hash table and linked list implementation of the <tt>Set</tt> interface, * with predictable iteration order. This implementation differs from * <tt>HashSet</tt> in that it maintains a doubly-linked list running through * all of its entries. This linked list defines the iteration ordering, * which is the order in which elements were inserted into the set * (<i>insertion-order</i>). Note that insertion order is <i>not</i> affected * if an element is <i>re-inserted</i> into the set. (An element <tt>e</tt> * is reinserted into a set <tt>s</tt> if <tt>s.add(e)</tt> is invoked when * <tt>s.contains(e)</tt> would return <tt>true</tt> immediately prior to * the invocation.) * * <p>This implementation spares its clients from the unspecified, generally * chaotic ordering provided by {@link HashSet}, without incurring the * increased cost associated with {@link TreeSet}. It can be used to * produce a copy of a set that has the same order as the original, regardless * of the original set's implementation: * <pre> * void foo(Set s) { * Set copy = new LinkedHashSet(s); * ... * } * </pre> * This technique is particularly useful if a module takes a set on input, * copies it, and later returns results whose order is determined by that of * the copy. (Clients generally appreciate having things returned in the same * order they were presented.) * * <p>This class provides all of the optional <tt>Set</tt> operations, and * permits null elements. Like <tt>HashSet</tt>, it provides constant-time * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and * <tt>remove</tt>), assuming the hash function disperses elements * properly among the buckets. Performance is likely to be just slightly * below that of <tt>HashSet</tt>, due to the added expense of maintaining the * linked list, with one exception: Iteration over a <tt>LinkedHashSet</tt> * requires time proportional to the <i>size</i> of the set, regardless of * its capacity. Iteration over a <tt>HashSet</tt> is likely to be more * expensive, requiring time proportional to its <i>capacity</i>. * * <p>A linked hash set has two parameters that affect its performance: * <i>initial capacity</i> and <i>load factor</i>. They are defined precisely * as for <tt>HashSet</tt>. Note, however, that the penalty for choosing an * excessively high value for initial capacity is less severe for this class * than for <tt>HashSet</tt>, as iteration times for this class are unaffected * by capacity. * * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access a linked hash set concurrently, and at least * one of the threads modifies the set, it <em>must</em> be synchronized * externally. This is typically accomplished by synchronizing on some * object that naturally encapsulates the set. * * If no such object exists, the set should be "wrapped" using the * {@link Collections#synchronizedSet Collections.synchronizedSet} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the set: <pre> * Set s = Collections.synchronizedSet(new LinkedHashSet(...));</pre> * * <p>The iterators returned by this class's <tt>iterator</tt> method are * <em>fail-fast</em>: if the set is modified at any time after the iterator * is created, in any way except through the iterator's own <tt>remove</tt> * method, the iterator will throw a {@link ConcurrentModificationException}. * Thus, in the face of concurrent modification, the iterator fails quickly * and cleanly, rather than risking arbitrary, non-deterministic behavior at * an undetermined time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <E> the type of elements maintained by this set * * @author Josh Bloch * @see Object#hashCode() * @see Collection * @see Set * @see HashSet * @see TreeSet * @see Hashtable * @since 1.4 */ public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, java.io.Serializable { private static final long serialVersionUID = -2851667679971038690L; /** {@collect.stats} * {@description.open} * Constructs a new, empty linked hash set with the specified initial * capacity and load factor. * {@description.close} * * @param initialCapacity the initial capacity of the linked hash set * @param loadFactor the load factor of the linked hash set * @throws IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive */ public LinkedHashSet(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor, true); } /** {@collect.stats} * {@description.open} * Constructs a new, empty linked hash set with the specified initial * capacity and the default load factor (0.75). * {@description.close} * * @param initialCapacity the initial capacity of the LinkedHashSet * @throws IllegalArgumentException if the initial capacity is less * than zero */ public LinkedHashSet(int initialCapacity) { super(initialCapacity, .75f, true); } /** {@collect.stats} * {@description.open} * Constructs a new, empty linked hash set with the default initial * capacity (16) and load factor (0.75). * {@description.close} */ public LinkedHashSet() { super(16, .75f, true); } /** {@collect.stats} * {@description.open} * Constructs a new linked hash set with the same elements as the * specified collection. The linked hash set is created with an initial * capacity sufficient to hold the elements in the specified collection * and the default load factor (0.75). * {@description.close} * * @param c the collection whose elements are to be placed into * this set * @throws NullPointerException if the specified collection is null */ public LinkedHashSet(Collection<? extends E> c) { super(Math.max(2*c.size(), 11), .75f, true); addAll(c); } }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when the formatter has been closed. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any * method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @since 1.5 */ public class FormatterClosedException extends IllegalStateException { private static final long serialVersionUID = 18111216L; /** {@collect.stats} * {@description.open} * Constructs an instance of this class. * {@description.close} */ public FormatterClosedException() { } }
Java
/* * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * FomattableFlags are passed to the {@link Formattable#formatTo * Formattable.formatTo()} method and modify the output format for {@linkplain * Formattable Formattables}. Implementations of {@link Formattable} are * responsible for interpreting and validating any flags. * {@description.close} * * @since 1.5 */ public class FormattableFlags { // Explicit instantiation of this class is prohibited. private FormattableFlags() {} /** {@collect.stats} * {@description.open} * Left-justifies the output. Spaces (<tt>'&#92;u0020'</tt>) will be added * at the end of the converted value as required to fill the minimum width * of the field. If this flag is not set then the output will be * right-justified. * * <p> This flag corresponds to <tt>'-'</tt> (<tt>'&#92;u002d'</tt>) in * the format specifier. * {@description.close} */ public static final int LEFT_JUSTIFY = 1<<0; // '-' /** {@collect.stats} * {@description.open} * Converts the output to upper case according to the rules of the * {@linkplain java.util.Locale locale} given during creation of the * <tt>formatter</tt> argument of the {@link Formattable#formatTo * formatTo()} method. The output should be equivalent the following * invocation of {@link String#toUpperCase(java.util.Locale)} * * <pre> * out.toUpperCase() </pre> * * <p> This flag corresponds to <tt>'^'</tt> (<tt>'&#92;u005e'</tt>) in * the format specifier. * {@description.close} */ public static final int UPPERCASE = 1<<1; // '^' /** {@collect.stats} * {@description.open} * Requires the output to use an alternate form. The definition of the * form is specified by the <tt>Formattable</tt>. * * <p> This flag corresponds to <tt>'#'</tt> (<tt>'&#92;u0023'</tt>) in * the format specifier. * {@description.close} */ public static final int ALTERNATE = 1<<2; // '#' }
Java
/* * Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * The <code>Dictionary</code> class is the abstract parent of any * class, such as <code>Hashtable</code>, which maps keys to values. * Every key and every value is an object. In any one <tt>Dictionary</tt> * object, every key is associated with at most one value. Given a * <tt>Dictionary</tt> and a key, the associated element can be looked up. * Any non-<code>null</code> object can be used as a key and as a value. * <p> * As a rule, the <code>equals</code> method should be used by * implementations of this class to decide if two keys are the same. * <p> * {@description.close} * {@property.open formal:java.util.Dictionary_Obsolete} * <strong>NOTE: This class is obsolete. New implementations should * implement the Map interface, rather than extending this class.</strong> * {@property.close} * * @author unascribed * @see java.util.Map * @see java.lang.Object#equals(java.lang.Object) * @see java.lang.Object#hashCode() * @see java.util.Hashtable * @since JDK1.0 */ public abstract class Dictionary<K,V> { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ public Dictionary() { } /** {@collect.stats} * {@description.open} * Returns the number of entries (distinct keys) in this dictionary. * {@description.close} * * @return the number of keys in this dictionary. */ abstract public int size(); /** {@collect.stats} * {@description.open} * Tests if this dictionary maps no keys to value. The general contract * for the <tt>isEmpty</tt> method is that the result is true if and only * if this dictionary contains no entries. * {@description.close} * * @return <code>true</code> if this dictionary maps no keys to values; * <code>false</code> otherwise. */ abstract public boolean isEmpty(); /** {@collect.stats} * {@description.open} * Returns an enumeration of the keys in this dictionary. The general * contract for the keys method is that an <tt>Enumeration</tt> object * is returned that will generate all the keys for which this dictionary * contains entries. * {@description.close} * * @return an enumeration of the keys in this dictionary. * @see java.util.Dictionary#elements() * @see java.util.Enumeration */ abstract public Enumeration<K> keys(); /** {@collect.stats} * {@description.open} * Returns an enumeration of the values in this dictionary. The general * contract for the <tt>elements</tt> method is that an * <tt>Enumeration</tt> is returned that will generate all the elements * contained in entries in this dictionary. * {@description.close} * * @return an enumeration of the values in this dictionary. * @see java.util.Dictionary#keys() * @see java.util.Enumeration */ abstract public Enumeration<V> elements(); /** {@collect.stats} * {@description.open} * Returns the value to which the key is mapped in this dictionary. * The general contract for the <tt>isEmpty</tt> method is that if this * dictionary contains an entry for the specified key, the associated * value is returned; otherwise, <tt>null</tt> is returned. * {@description.close} * * @return the value to which the key is mapped in this dictionary; * @param key a key in this dictionary. * <code>null</code> if the key is not mapped to any value in * this dictionary. * @exception NullPointerException if the <tt>key</tt> is <tt>null</tt>. * @see java.util.Dictionary#put(java.lang.Object, java.lang.Object) */ abstract public V get(Object key); /** {@collect.stats} * {@description.open} * Maps the specified <code>key</code> to the specified * <code>value</code> in this dictionary. * {@description.close} * {@property.open formal:java.util.Dictionary_NullKeyOrValue} * Neither the key nor the * value can be <code>null</code>. * {@property.close} * {@description.open} * <p> * If this dictionary already contains an entry for the specified * <tt>key</tt>, the value already in this dictionary for that * <tt>key</tt> is returned, after modifying the entry to contain the * new element. <p>If this dictionary does not already have an entry * for the specified <tt>key</tt>, an entry is created for the * specified <tt>key</tt> and <tt>value</tt>, and <tt>null</tt> is * returned. * <p> * The <code>value</code> can be retrieved by calling the * <code>get</code> method with a <code>key</code> that is equal to * the original <code>key</code>. * {@description.close} * * @param key the hashtable key. * @param value the value. * @return the previous value to which the <code>key</code> was mapped * in this dictionary, or <code>null</code> if the key did not * have a previous mapping. * @exception NullPointerException if the <code>key</code> or * <code>value</code> is <code>null</code>. * @see java.lang.Object#equals(java.lang.Object) * @see java.util.Dictionary#get(java.lang.Object) */ abstract public V put(K key, V value); /** {@collect.stats} * {@description.open} * Removes the <code>key</code> (and its corresponding * <code>value</code>) from this dictionary. This method does nothing * if the <code>key</code> is not in this dictionary. * {@description.close} * * @param key the key that needs to be removed. * @return the value to which the <code>key</code> had been mapped in this * dictionary, or <code>null</code> if the key did not have a * mapping. * @exception NullPointerException if <tt>key</tt> is <tt>null</tt>. */ abstract public V remove(Object key); }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.util.Map.Entry; /** {@collect.stats} * {@description.open} * This class provides a skeletal implementation of the <tt>Map</tt> * interface, to minimize the effort required to implement this interface. * {@description.close} * * {@property.open unknown} * <p>To implement an unmodifiable map, the programmer needs only to extend this * class and provide an implementation for the <tt>entrySet</tt> method, which * returns a set-view of the map's mappings. Typically, the returned set * will, in turn, be implemented atop <tt>AbstractSet</tt>. This set should * not support the <tt>add</tt> or <tt>remove</tt> methods, and its iterator * should not support the <tt>remove</tt> method. * {@property.close} * * {@property.open unknown} * <p>To implement a modifiable map, the programmer must additionally override * this class's <tt>put</tt> method (which otherwise throws an * <tt>UnsupportedOperationException</tt>), and the iterator returned by * <tt>entrySet().iterator()</tt> must additionally implement its * <tt>remove</tt> method. * {@property.close} * * {@property.open formal:java.util.Map_StandardConstructors} * <p>The programmer should generally provide a void (no argument) and map * constructor, as per the recommendation in the <tt>Map</tt> interface * specification. * {@property.close} * * {@description.open} * <p>The documentation for each non-abstract method in this class describes its * implementation in detail. Each of these methods may be overridden if the * map being implemented admits a more efficient implementation. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Josh Bloch * @author Neal Gafter * @see Map * @see Collection * @since 1.2 */ public abstract class AbstractMap<K,V> implements Map<K,V> { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ protected AbstractMap() { } // Query Operations /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation returns <tt>entrySet().size()</tt>. * {@description.close} */ public int size() { return entrySet().size(); } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation returns <tt>size() == 0</tt>. * {@description.close} */ public boolean isEmpty() { return size() == 0; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over <tt>entrySet()</tt> searching * for an entry with the specified value. If such an entry is found, * <tt>true</tt> is returned. If the iteration terminates without * finding such an entry, <tt>false</tt> is returned. Note that this * implementation requires linear time in the size of the map. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public boolean containsValue(Object value) { Iterator<Entry<K,V>> i = entrySet().iterator(); if (value==null) { while (i.hasNext()) { Entry<K,V> e = i.next(); if (e.getValue()==null) return true; } } else { while (i.hasNext()) { Entry<K,V> e = i.next(); if (value.equals(e.getValue())) return true; } } return false; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over <tt>entrySet()</tt> searching * for an entry with the specified key. If such an entry is found, * <tt>true</tt> is returned. If the iteration terminates without * finding such an entry, <tt>false</tt> is returned. Note that this * implementation requires linear time in the size of the map; many * implementations will override this method. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public boolean containsKey(Object key) { Iterator<Map.Entry<K,V>> i = entrySet().iterator(); if (key==null) { while (i.hasNext()) { Entry<K,V> e = i.next(); if (e.getKey()==null) return true; } } else { while (i.hasNext()) { Entry<K,V> e = i.next(); if (key.equals(e.getKey())) return true; } } return false; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over <tt>entrySet()</tt> searching * for an entry with the specified key. If such an entry is found, * the entry's value is returned. If the iteration terminates without * finding such an entry, <tt>null</tt> is returned. Note that this * implementation requires linear time in the size of the map; many * implementations will override this method. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public V get(Object key) { Iterator<Entry<K,V>> i = entrySet().iterator(); if (key==null) { while (i.hasNext()) { Entry<K,V> e = i.next(); if (e.getKey()==null) return e.getValue(); } } else { while (i.hasNext()) { Entry<K,V> e = i.next(); if (key.equals(e.getKey())) return e.getValue(); } } return null; } // Modification Operations /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation always throws an * <tt>UnsupportedOperationException</tt>. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public V put(K key, V value) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over <tt>entrySet()</tt> searching for an * entry with the specified key. If such an entry is found, its value is * obtained with its <tt>getValue</tt> operation, the entry is removed * from the collection (and the backing map) with the iterator's * <tt>remove</tt> operation, and the saved value is returned. If the * iteration terminates without finding such an entry, <tt>null</tt> is * returned. Note that this implementation requires linear time in the * size of the map; many implementations will override this method. * * <p>Note that this implementation throws an * <tt>UnsupportedOperationException</tt> if the <tt>entrySet</tt> * iterator does not support the <tt>remove</tt> method and this map * contains a mapping for the specified key. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public V remove(Object key) { Iterator<Entry<K,V>> i = entrySet().iterator(); Entry<K,V> correctEntry = null; if (key==null) { while (correctEntry==null && i.hasNext()) { Entry<K,V> e = i.next(); if (e.getKey()==null) correctEntry = e; } } else { while (correctEntry==null && i.hasNext()) { Entry<K,V> e = i.next(); if (key.equals(e.getKey())) correctEntry = e; } } V oldValue = null; if (correctEntry !=null) { oldValue = correctEntry.getValue(); i.remove(); } return oldValue; } // Bulk Operations /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over the specified map's * <tt>entrySet()</tt> collection, and calls this map's <tt>put</tt> * operation once for each entry returned by the iteration. * * <p>Note that this implementation throws an * <tt>UnsupportedOperationException</tt> if this map does not support * the <tt>put</tt> operation and the specified map is nonempty. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue()); } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation calls <tt>entrySet().clear()</tt>. * * <p>Note that this implementation throws an * <tt>UnsupportedOperationException</tt> if the <tt>entrySet</tt> * does not support the <tt>clear</tt> operation. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} */ public void clear() { entrySet().clear(); } // Views /** {@collect.stats} * {@description.open} * Each of these fields are initialized to contain an instance of the * appropriate view the first time this view is requested. The views are * stateless, so there's no reason to create more than one of each. * {@description.close} */ transient volatile Set<K> keySet = null; transient volatile Collection<V> values = null; /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation returns a set that subclasses {@link AbstractSet}. * The subclass's iterator method returns a "wrapper object" over this * map's <tt>entrySet()</tt> iterator. The <tt>size</tt> method * delegates to this map's <tt>size</tt> method and the * <tt>contains</tt> method delegates to this map's * <tt>containsKey</tt> method. * * <p>The set is created the first time this method is called, * and returned in response to all subsequent calls. No synchronization * is performed, so there is a slight chance that multiple calls to this * method will not all return the same set. * {@description.close} */ public Set<K> keySet() { if (keySet == null) { keySet = new AbstractSet<K>() { public Iterator<K> iterator() { return new Iterator<K>() { private Iterator<Entry<K,V>> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public K next() { return i.next().getKey(); } public void remove() { i.remove(); } }; } public int size() { return AbstractMap.this.size(); } public boolean isEmpty() { return AbstractMap.this.isEmpty(); } public void clear() { AbstractMap.this.clear(); } public boolean contains(Object k) { return AbstractMap.this.containsKey(k); } }; } return keySet; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation returns a collection that subclasses {@link * AbstractCollection}. The subclass's iterator method returns a * "wrapper object" over this map's <tt>entrySet()</tt> iterator. * The <tt>size</tt> method delegates to this map's <tt>size</tt> * method and the <tt>contains</tt> method delegates to this map's * <tt>containsValue</tt> method. * * <p>The collection is created the first time this method is called, and * returned in response to all subsequent calls. No synchronization is * performed, so there is a slight chance that multiple calls to this * method will not all return the same collection. * {@description.close} */ public Collection<V> values() { if (values == null) { values = new AbstractCollection<V>() { public Iterator<V> iterator() { return new Iterator<V>() { private Iterator<Entry<K,V>> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public V next() { return i.next().getValue(); } public void remove() { i.remove(); } }; } public int size() { return AbstractMap.this.size(); } public boolean isEmpty() { return AbstractMap.this.isEmpty(); } public void clear() { AbstractMap.this.clear(); } public boolean contains(Object v) { return AbstractMap.this.containsValue(v); } }; } return values; } public abstract Set<Entry<K,V>> entrySet(); // Comparison and hashing /** {@collect.stats} * {@description.open} * Compares the specified object with this map for equality. Returns * <tt>true</tt> if the given object is also a map and the two maps * represent the same mappings. More formally, two maps <tt>m1</tt> and * <tt>m2</tt> represent the same mappings if * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the * <tt>equals</tt> method works properly across different implementations * of the <tt>Map</tt> interface. * * <p>This implementation first checks if the specified object is this map; * if so it returns <tt>true</tt>. Then, it checks if the specified * object is a map whose size is identical to the size of this map; if * not, it returns <tt>false</tt>. If so, it iterates over this map's * <tt>entrySet</tt> collection, and checks that the specified map * contains each mapping that this map contains. If the specified map * fails to contain such a mapping, <tt>false</tt> is returned. If the * iteration completes, <tt>true</tt> is returned. * {@description.close} * * @param o object to be compared for equality with this map * @return <tt>true</tt> if the specified object is equal to this map */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Map)) return false; Map<K,V> m = (Map<K,V>) o; if (m.size() != size()) return false; try { Iterator<Entry<K,V>> i = entrySet().iterator(); while (i.hasNext()) { Entry<K,V> e = i.next(); K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(m.get(key)==null && m.containsKey(key))) return false; } else { if (!value.equals(m.get(key))) return false; } } } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } return true; } /** {@collect.stats} * {@description.open} * Returns the hash code value for this map. The hash code of a map is * defined to be the sum of the hash codes of each entry in the map's * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt> * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of * {@link Object#hashCode}. * * <p>This implementation iterates over <tt>entrySet()</tt>, calling * {@link Map.Entry#hashCode hashCode()} on each element (entry) in the * set, and adding up the results. * {@description.close} * * @return the hash code value for this map * @see Map.Entry#hashCode() * @see Object#equals(Object) * @see Set#equals(Object) */ public int hashCode() { int h = 0; Iterator<Entry<K,V>> i = entrySet().iterator(); while (i.hasNext()) h += i.next().hashCode(); return h; } /** {@collect.stats} * {@description.open} * Returns a string representation of this map. The string representation * consists of a list of key-value mappings in the order returned by the * map's <tt>entrySet</tt> view's iterator, enclosed in braces * (<tt>"{}"</tt>). Adjacent mappings are separated by the characters * <tt>", "</tt> (comma and space). Each key-value mapping is rendered as * the key followed by an equals sign (<tt>"="</tt>) followed by the * associated value. Keys and values are converted to strings as by * {@link String#valueOf(Object)}. * {@description.close} * * @return a string representation of this map */ public String toString() { Iterator<Entry<K,V>> i = entrySet().iterator(); if (! i.hasNext()) return "{}"; StringBuilder sb = new StringBuilder(); sb.append('{'); for (;;) { Entry<K,V> e = i.next(); K key = e.getKey(); V value = e.getValue(); sb.append(key == this ? "(this Map)" : key); sb.append('='); sb.append(value == this ? "(this Map)" : value); if (! i.hasNext()) return sb.append('}').toString(); sb.append(", "); } } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this <tt>AbstractMap</tt> instance: the keys * and values themselves are not cloned. * {@description.close} * * @return a shallow copy of this map */ protected Object clone() throws CloneNotSupportedException { AbstractMap<K,V> result = (AbstractMap<K,V>)super.clone(); result.keySet = null; result.values = null; return result; } /** {@collect.stats} * {@description.open} * Utility method for SimpleEntry and SimpleImmutableEntry. * Test for equality, checking for nulls. * {@description.close} */ private static boolean eq(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } // Implementation Note: SimpleEntry and SimpleImmutableEntry // are distinct unrelated classes, even though they share // some code. Since you can't add or subtract final-ness // of a field in a subclass, they can't share representations, // and the amount of duplicated code is too small to warrant // exposing a common abstract class. /** {@collect.stats} * {@description.open} * An Entry maintaining a key and a value. The value may be * changed using the <tt>setValue</tt> method. This class * facilitates the process of building custom map * implementations. For example, it may be convenient to return * arrays of <tt>SimpleEntry</tt> instances in method * <tt>Map.entrySet().toArray</tt>. * {@description.close} * * @since 1.6 */ public static class SimpleEntry<K,V> implements Entry<K,V>, java.io.Serializable { private static final long serialVersionUID = -8499721149061103585L; private final K key; private V value; /** {@collect.stats} * {@description.open} * Creates an entry representing a mapping from the specified * key to the specified value. * {@description.close} * * @param key the key represented by this entry * @param value the value represented by this entry */ public SimpleEntry(K key, V value) { this.key = key; this.value = value; } /** {@collect.stats} * {@description.open} * Creates an entry representing the same mapping as the * specified entry. * {@description.close} * * @param entry the entry to copy */ public SimpleEntry(Entry<? extends K, ? extends V> entry) { this.key = entry.getKey(); this.value = entry.getValue(); } /** {@collect.stats} * {@description.open} * Returns the key corresponding to this entry. * {@description.close} * * @return the key corresponding to this entry */ public K getKey() { return key; } /** {@collect.stats} * {@description.open} * Returns the value corresponding to this entry. * {@description.close} * * @return the value corresponding to this entry */ public V getValue() { return value; } /** {@collect.stats} * {@description.open} * Replaces the value corresponding to this entry with the specified * value. * {@description.close} * * @param value new value to be stored in this entry * @return the old value corresponding to the entry */ public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } /** {@collect.stats} * {@description.open} * Compares the specified object with this entry for equality. * Returns {@code true} if the given object is also a map entry and * the two entries represent the same mapping. More formally, two * entries {@code e1} and {@code e2} represent the same mapping * if<pre> * (e1.getKey()==null ? * e2.getKey()==null : * e1.getKey().equals(e2.getKey())) * &amp;&amp; * (e1.getValue()==null ? * e2.getValue()==null : * e1.getValue().equals(e2.getValue()))</pre> * This ensures that the {@code equals} method works properly across * different implementations of the {@code Map.Entry} interface. * {@description.close} * * @param o object to be compared for equality with this map entry * @return {@code true} if the specified object is equal to this map * entry * @see #hashCode */ public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; return eq(key, e.getKey()) && eq(value, e.getValue()); } /** {@collect.stats} * {@description.open} * Returns the hash code value for this map entry. The hash code * of a map entry {@code e} is defined to be: <pre> * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ * (e.getValue()==null ? 0 : e.getValue().hashCode())</pre> * This ensures that {@code e1.equals(e2)} implies that * {@code e1.hashCode()==e2.hashCode()} for any two Entries * {@code e1} and {@code e2}, as required by the general * contract of {@link Object#hashCode}. * {@description.close} * * @return the hash code value for this map entry * @see #equals */ public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } /** {@collect.stats} * {@description.open} * Returns a String representation of this map entry. This * implementation returns the string representation of this * entry's key followed by the equals character ("<tt>=</tt>") * followed by the string representation of this entry's value. * {@description.close} * * @return a String representation of this map entry */ public String toString() { return key + "=" + value; } } /** {@collect.stats} * {@description.open} * An Entry maintaining an immutable key and value. This class * does not support method <tt>setValue</tt>. This class may be * convenient in methods that return thread-safe snapshots of * key-value mappings. * {@description.close} * * @since 1.6 */ public static class SimpleImmutableEntry<K,V> implements Entry<K,V>, java.io.Serializable { private static final long serialVersionUID = 7138329143949025153L; private final K key; private final V value; /** {@collect.stats} * {@description.open} * Creates an entry representing a mapping from the specified * key to the specified value. * {@description.close} * * @param key the key represented by this entry * @param value the value represented by this entry */ public SimpleImmutableEntry(K key, V value) { this.key = key; this.value = value; } /** {@collect.stats} * {@description.open} * Creates an entry representing the same mapping as the * specified entry. * {@description.close} * * @param entry the entry to copy */ public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) { this.key = entry.getKey(); this.value = entry.getValue(); } /** {@collect.stats} * {@description.open} * Returns the key corresponding to this entry. * {@description.close} * * @return the key corresponding to this entry */ public K getKey() { return key; } /** {@collect.stats} * {@description.open} * Returns the value corresponding to this entry. * {@description.close} * * @return the value corresponding to this entry */ public V getValue() { return value; } /** {@collect.stats} * {@description.open} * Replaces the value corresponding to this entry with the specified * value (optional operation). This implementation simply throws * <tt>UnsupportedOperationException</tt>, as this class implements * an <i>immutable</i> map entry. * {@description.close} * * @param value new value to be stored in this entry * @return (Does not return) * @throws UnsupportedOperationException always */ public V setValue(V value) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Compares the specified object with this entry for equality. * Returns {@code true} if the given object is also a map entry and * the two entries represent the same mapping. More formally, two * entries {@code e1} and {@code e2} represent the same mapping * if<pre> * (e1.getKey()==null ? * e2.getKey()==null : * e1.getKey().equals(e2.getKey())) * &amp;&amp; * (e1.getValue()==null ? * e2.getValue()==null : * e1.getValue().equals(e2.getValue()))</pre> * This ensures that the {@code equals} method works properly across * different implementations of the {@code Map.Entry} interface. * {@description.close} * * @param o object to be compared for equality with this map entry * @return {@code true} if the specified object is equal to this map * entry * @see #hashCode */ public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; return eq(key, e.getKey()) && eq(value, e.getValue()); } /** {@collect.stats} * {@description.open} * Returns the hash code value for this map entry. The hash code * of a map entry {@code e} is defined to be: <pre> * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ * (e.getValue()==null ? 0 : e.getValue().hashCode())</pre> * This ensures that {@code e1.equals(e2)} implies that * {@code e1.hashCode()==e2.hashCode()} for any two Entries * {@code e1} and {@code e2}, as required by the general * contract of {@link Object#hashCode}. * {@description.close} * * @return the hash code value for this map entry * @see #equals */ public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } /** {@collect.stats} * {@description.open} * Returns a String representation of this map entry. This * implementation returns the string representation of this * entry's key followed by the equals character ("<tt>=</tt>") * followed by the string representation of this entry's value. * {@description.close} * * @return a String representation of this map entry */ public String toString() { return key + "=" + value; } } }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when the format width is required. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to anyg * method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @since 1.5 */ public class MissingFormatWidthException extends IllegalFormatException { private static final long serialVersionUID = 15560123L; private String s; /** {@collect.stats} * {@description.open} * Constructs an instance of this class with the specified format * specifier. * {@description.close} * * @param s * The format specifier which does not have a width */ public MissingFormatWidthException(String s) { if (s == null) throw new NullPointerException(); this.s = s; } /** {@collect.stats} * {@description.open} * Returns the format specifier which does not have a width. * {@description.close} * * @return The format specifier which does not have a width */ public String getFormatSpecifier() { return s; } public String getMessage() { return s; } }
Java
/* * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved * * The original version of this source code and documentation * is copyrighted and owned by Taligent, Inc., a wholly-owned * subsidiary of IBM. These materials are provided under terms * of a License Agreement between Taligent and Sun. This technology * is protected by multiple US and International patents. * * This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.util; /** {@collect.stats} * {@description.open} * Signals that a resource is missing. * {@description.close} * @see java.lang.Exception * @see ResourceBundle * @author Mark Davis * @since JDK1.1 */ public class MissingResourceException extends RuntimeException { /** {@collect.stats} * {@description.open} * Constructs a MissingResourceException with the specified information. * A detail message is a String that describes this particular exception. * {@description.close} * @param s the detail message * @param className the name of the resource class * @param key the key for the missing resource. */ public MissingResourceException(String s, String className, String key) { super(s); this.className = className; this.key = key; } /** {@collect.stats} * {@description.open} * Constructs a <code>MissingResourceException</code> with * <code>message</code>, <code>className</code>, <code>key</code>, * and <code>cause</code>. This constructor is package private for * use by <code>ResourceBundle.getBundle</code>. * {@description.close} * * @param message * the detail message * @param className * the name of the resource class * @param key * the key for the missing resource. * @param cause * the cause (which is saved for later retrieval by the * {@link Throwable.getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent * or unknown.) */ MissingResourceException(String message, String className, String key, Throwable cause) { super(message, cause); this.className = className; this.key = key; } /** {@collect.stats} * {@description.open} * Gets parameter passed by constructor. * {@description.close} * * @return the name of the resource class */ public String getClassName() { return className; } /** {@collect.stats} * {@description.open} * Gets parameter passed by constructor. * {@description.close} * * @return the key for the missing resource */ public String getKey() { return key; } //============ privates ============ // serialization compatibility with JDK1.1 private static final long serialVersionUID = -4876345176062000401L; /** {@collect.stats} * {@description.open} * The class name of the resource bundle requested by the user. * {@description.close} * @serial */ private String className; /** {@collect.stats} * {@description.open} * The name of the specific resource requested by the user. * {@description.close} * @serial */ private String key; }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when an illegal combination flags is given. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any * method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @since 1.5 */ public class IllegalFormatFlagsException extends IllegalFormatException { private static final long serialVersionUID = 790824L; private String flags; /** {@collect.stats} * {@description.open} * Constructs an instance of this class with the specified flags. * {@description.close} * * @param f * The set of format flags which contain an illegal combination */ public IllegalFormatFlagsException(String f) { if (f == null) throw new NullPointerException(); this.flags = f; } /** {@collect.stats} * {@description.open} * Returns the set of flags which contains an illegal combination. * {@description.close} * * @return The flags */ public String getFlags() { return flags; } public String getMessage() { return "Flags = '" + flags + "'"; } }
Java
/* * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedWriter; /** {@collect.stats} * {@description.open} * The <code>Properties</code> class represents a persistent set of * properties. The <code>Properties</code> can be saved to a stream * or loaded from a stream. Each key and its corresponding value in * the property list is a string. * <p> * A property list can contain another property list as its * "defaults"; this second property list is searched if * the property key is not found in the original property list. * <p> * Because <code>Properties</code> inherits from <code>Hashtable</code>, the * <code>put</code> and <code>putAll</code> methods can be applied to a * <code>Properties</code> object. Their use is strongly discouraged as they * allow the caller to insert entries whose keys or values are not * <code>Strings</code>. The <code>setProperty</code> method should be used * instead. If the <code>store</code> or <code>save</code> method is called * on a "compromised" <code>Properties</code> object that contains a * non-<code>String</code> key or value, the call will fail. Similarly, * the call to the <code>propertyNames</code> or <code>list</code> method * will fail if it is called on a "compromised" <code>Properties</code> * object that contains a non-<code>String</code> key. * * <p> * The {@link #load(java.io.Reader) load(Reader)} <tt>/</tt> * {@link #store(java.io.Writer, java.lang.String) store(Writer, String)} * methods load and store properties from and to a character based stream * in a simple line-oriented format specified below. * * The {@link #load(java.io.InputStream) load(InputStream)} <tt>/</tt> * {@link #store(java.io.OutputStream, java.lang.String) store(OutputStream, String)} * methods work the same way as the load(Reader)/store(Writer, String) pair, except * the input/output stream is encoded in ISO 8859-1 character encoding. * Characters that cannot be directly represented in this encoding can be written using * <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.3">Unicode escapes</a> * ; only a single 'u' character is allowed in an escape * sequence. The native2ascii tool can be used to convert property files to and * from other character encodings. * * <p> The {@link #loadFromXML(InputStream)} and {@link * #storeToXML(OutputStream, String, String)} methods load and store properties * in a simple XML format. By default the UTF-8 character encoding is used, * however a specific encoding may be specified if required. An XML properties * document has the following DOCTYPE declaration: * * <pre> * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt; * </pre> * Note that the system URI (http://java.sun.com/dtd/properties.dtd) is * <i>not</i> accessed when exporting or importing properties; it merely * serves as a string to uniquely identify the DTD, which is: * <pre> * &lt;?xml version="1.0" encoding="UTF-8"?&gt; * * &lt;!-- DTD for properties --&gt; * * &lt;!ELEMENT properties ( comment?, entry* ) &gt; * * &lt;!ATTLIST properties version CDATA #FIXED "1.0"&gt; * * &lt;!ELEMENT comment (#PCDATA) &gt; * * &lt;!ELEMENT entry (#PCDATA) &gt; * * &lt;!ATTLIST entry key CDATA #REQUIRED&gt; * </pre> * * <p>This class is thread-safe: multiple threads can share a single * <tt>Properties</tt> object without the need for external synchronization. * {@description.close} * * @see <a href="../../../technotes/tools/solaris/native2ascii.html">native2ascii tool for Solaris</a> * @see <a href="../../../technotes/tools/windows/native2ascii.html">native2ascii tool for Windows</a> * * @author Arthur van Hoff * @author Michael McCloskey * @author Xueming Shen * @since JDK1.0 */ public class Properties extends Hashtable<Object,Object> { /** {@collect.stats} * {@description.open} * use serialVersionUID from JDK 1.1.X for interoperability * {@description.close} */ private static final long serialVersionUID = 4112578634029874840L; /** {@collect.stats} * {@description.open} * A property list that contains default values for any keys not * found in this property list. * {@description.close} * * @serial */ protected Properties defaults; /** {@collect.stats} * {@description.open} * Creates an empty property list with no default values. * {@description.close} */ public Properties() { this(null); } /** {@collect.stats} * {@description.open} * Creates an empty property list with the specified defaults. * {@description.close} * * @param defaults the defaults. */ public Properties(Properties defaults) { this.defaults = defaults; } /** {@collect.stats} * {@description.open} * Calls the <tt>Hashtable</tt> method <code>put</code>. Provided for * parallelism with the <tt>getProperty</tt> method. Enforces use of * strings for property keys and values. The value returned is the * result of the <tt>Hashtable</tt> call to <code>put</code>. * {@description.close} * * @param key the key to be placed into this property list. * @param value the value corresponding to <tt>key</tt>. * @return the previous value of the specified key in this property * list, or <code>null</code> if it did not have one. * @see #getProperty * @since 1.2 */ public synchronized Object setProperty(String key, String value) { return put(key, value); } /** {@collect.stats} * {@description.open} * Reads a property list (key and element pairs) from the input * character stream in a simple line-oriented format. * <p> * Properties are processed in terms of lines. There are two * kinds of line, <i>natural lines</i> and <i>logical lines</i>. * A natural line is defined as a line of * characters that is terminated either by a set of line terminator * characters (<code>\n</code> or <code>\r</code> or <code>\r\n</code>) * or by the end of the stream. A natural line may be either a blank line, * a comment line, or hold all or some of a key-element pair. A logical * line holds all the data of a key-element pair, which may be spread * out across several adjacent natural lines by escaping * the line terminator sequence with a backslash character * <code>\</code>. Note that a comment line cannot be extended * in this manner; every natural line that is a comment must have * its own comment indicator, as described below. Lines are read from * input until the end of the stream is reached. * * <p> * A natural line that contains only white space characters is * considered blank and is ignored. A comment line has an ASCII * <code>'#'</code> or <code>'!'</code> as its first non-white * space character; comment lines are also ignored and do not * encode key-element information. In addition to line * terminators, this format considers the characters space * (<code>' '</code>, <code>'&#92;u0020'</code>), tab * (<code>'\t'</code>, <code>'&#92;u0009'</code>), and form feed * (<code>'\f'</code>, <code>'&#92;u000C'</code>) to be white * space. * * <p> * If a logical line is spread across several natural lines, the * backslash escaping the line terminator sequence, the line * terminator sequence, and any white space at the start of the * following line have no affect on the key or element values. * The remainder of the discussion of key and element parsing * (when loading) will assume all the characters constituting * the key and element appear on a single natural line after * line continuation characters have been removed. Note that * it is <i>not</i> sufficient to only examine the character * preceding a line terminator sequence to decide if the line * terminator is escaped; there must be an odd number of * contiguous backslashes for the line terminator to be escaped. * Since the input is processed from left to right, a * non-zero even number of 2<i>n</i> contiguous backslashes * before a line terminator (or elsewhere) encodes <i>n</i> * backslashes after escape processing. * * <p> * The key contains all of the characters in the line starting * with the first non-white space character and up to, but not * including, the first unescaped <code>'='</code>, * <code>':'</code>, or white space character other than a line * terminator. All of these key termination characters may be * included in the key by escaping them with a preceding backslash * character; for example,<p> * * <code>\:\=</code><p> * * would be the two-character key <code>":="</code>. Line * terminator characters can be included using <code>\r</code> and * <code>\n</code> escape sequences. Any white space after the * key is skipped; if the first non-white space character after * the key is <code>'='</code> or <code>':'</code>, then it is * ignored and any white space characters after it are also * skipped. All remaining characters on the line become part of * the associated element string; if there are no remaining * characters, the element is the empty string * <code>&quot;&quot;</code>. Once the raw character sequences * constituting the key and element are identified, escape * processing is performed as described above. * * <p> * As an example, each of the following three lines specifies the key * <code>"Truth"</code> and the associated element value * <code>"Beauty"</code>: * <p> * <pre> * Truth = Beauty * Truth:Beauty * Truth :Beauty * </pre> * As another example, the following three lines specify a single * property: * <p> * <pre> * fruits apple, banana, pear, \ * cantaloupe, watermelon, \ * kiwi, mango * </pre> * The key is <code>"fruits"</code> and the associated element is: * <p> * <pre>"apple, banana, pear, cantaloupe, watermelon, kiwi, mango"</pre> * Note that a space appears before each <code>\</code> so that a space * will appear after each comma in the final result; the <code>\</code>, * line terminator, and leading white space on the continuation line are * merely discarded and are <i>not</i> replaced by one or more other * characters. * <p> * As a third example, the line: * <p> * <pre>cheeses * </pre> * specifies that the key is <code>"cheeses"</code> and the associated * element is the empty string <code>""</code>.<p> * <p> * * <a name="unicodeescapes"></a> * Characters in keys and elements can be represented in escape * sequences similar to those used for character and string literals * (see <a * href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.3">&sect;3.3</a> * and <a * href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.6">&sect;3.10.6</a> * of the <i>Java Language Specification</i>). * * The differences from the character escape sequences and Unicode * escapes used for characters and strings are: * * <ul> * <li> Octal escapes are not recognized. * * <li> The character sequence <code>\b</code> does <i>not</i> * represent a backspace character. * * <li> The method does not treat a backslash character, * <code>\</code>, before a non-valid escape character as an * error; the backslash is silently dropped. For example, in a * Java string the sequence <code>"\z"</code> would cause a * compile time error. In contrast, this method silently drops * the backslash. Therefore, this method treats the two character * sequence <code>"\b"</code> as equivalent to the single * character <code>'b'</code>. * * <li> Escapes are not necessary for single and double quotes; * however, by the rule above, single and double quote characters * preceded by a backslash still yield single and double quote * characters, respectively. * * <li> Only a single 'u' character is allowed in a Uniocde escape * sequence. * * </ul> * <p> * The specified stream remains open after this method returns. * {@description.close} * * @param reader the input character stream. * @throws IOException if an error occurred when reading from the * input stream. * @throws IllegalArgumentException if a malformed Unicode escape * appears in the input. * @since 1.6 */ public synchronized void load(Reader reader) throws IOException { load0(new LineReader(reader)); } /** {@collect.stats} * {@description.open} * Reads a property list (key and element pairs) from the input * byte stream. The input stream is in a simple line-oriented * format as specified in * {@link #load(java.io.Reader) load(Reader)} and is assumed to use * the ISO 8859-1 character encoding; that is each byte is one Latin1 * character. Characters not in Latin1, and certain special characters, * are represented in keys and elements using * <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.3">Unicode escapes</a>. * <p> * The specified stream remains open after this method returns. * {@description.close} * * @param inStream the input stream. * @exception IOException if an error occurred when reading from the * input stream. * @throws IllegalArgumentException if the input stream contains a * malformed Unicode escape sequence. * @since 1.2 */ public synchronized void load(InputStream inStream) throws IOException { load0(new LineReader(inStream)); } private void load0 (LineReader lr) throws IOException { char[] convtBuf = new char[1024]; int limit; int keyLen; int valueStart; char c; boolean hasSep; boolean precedingBackslash; while ((limit = lr.readLine()) >= 0) { c = 0; keyLen = 0; valueStart = limit; hasSep = false; //System.out.println("line=<" + new String(lineBuf, 0, limit) + ">"); precedingBackslash = false; while (keyLen < limit) { c = lr.lineBuf[keyLen]; //need check if escaped. if ((c == '=' || c == ':') && !precedingBackslash) { valueStart = keyLen + 1; hasSep = true; break; } else if ((c == ' ' || c == '\t' || c == '\f') && !precedingBackslash) { valueStart = keyLen + 1; break; } if (c == '\\') { precedingBackslash = !precedingBackslash; } else { precedingBackslash = false; } keyLen++; } while (valueStart < limit) { c = lr.lineBuf[valueStart]; if (c != ' ' && c != '\t' && c != '\f') { if (!hasSep && (c == '=' || c == ':')) { hasSep = true; } else { break; } } valueStart++; } String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf); String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf); put(key, value); } } /* Read in a "logical line" from an InputStream/Reader, skip all comment * and blank lines and filter out those leading whitespace characters * (\u0020, \u0009 and \u000c) from the beginning of a "natural line". * Method returns the char length of the "logical line" and stores * the line in "lineBuf". */ class LineReader { public LineReader(InputStream inStream) { this.inStream = inStream; inByteBuf = new byte[8192]; } public LineReader(Reader reader) { this.reader = reader; inCharBuf = new char[8192]; } byte[] inByteBuf; char[] inCharBuf; char[] lineBuf = new char[1024]; int inLimit = 0; int inOff = 0; InputStream inStream; Reader reader; int readLine() throws IOException { int len = 0; char c = 0; boolean skipWhiteSpace = true; boolean isCommentLine = false; boolean isNewLine = true; boolean appendedLineBegin = false; boolean precedingBackslash = false; boolean skipLF = false; while (true) { if (inOff >= inLimit) { inLimit = (inStream==null)?reader.read(inCharBuf) :inStream.read(inByteBuf); inOff = 0; if (inLimit <= 0) { if (len == 0 || isCommentLine) { return -1; } return len; } } if (inStream != null) { //The line below is equivalent to calling a //ISO8859-1 decoder. c = (char) (0xff & inByteBuf[inOff++]); } else { c = inCharBuf[inOff++]; } if (skipLF) { skipLF = false; if (c == '\n') { continue; } } if (skipWhiteSpace) { if (c == ' ' || c == '\t' || c == '\f') { continue; } if (!appendedLineBegin && (c == '\r' || c == '\n')) { continue; } skipWhiteSpace = false; appendedLineBegin = false; } if (isNewLine) { isNewLine = false; if (c == '#' || c == '!') { isCommentLine = true; continue; } } if (c != '\n' && c != '\r') { lineBuf[len++] = c; if (len == lineBuf.length) { int newLength = lineBuf.length * 2; if (newLength < 0) { newLength = Integer.MAX_VALUE; } char[] buf = new char[newLength]; System.arraycopy(lineBuf, 0, buf, 0, lineBuf.length); lineBuf = buf; } //flip the preceding backslash flag if (c == '\\') { precedingBackslash = !precedingBackslash; } else { precedingBackslash = false; } } else { // reached EOL if (isCommentLine || len == 0) { isCommentLine = false; isNewLine = true; skipWhiteSpace = true; len = 0; continue; } if (inOff >= inLimit) { inLimit = (inStream==null) ?reader.read(inCharBuf) :inStream.read(inByteBuf); inOff = 0; if (inLimit <= 0) { return len; } } if (precedingBackslash) { len -= 1; //skip the leading whitespace characters in following line skipWhiteSpace = true; appendedLineBegin = true; precedingBackslash = false; if (c == '\r') { skipLF = true; } } else { return len; } } } } } /* * Converts encoded &#92;uxxxx to unicode chars * and changes special saved chars to their original forms */ private String loadConvert (char[] in, int off, int len, char[] convtBuf) { if (convtBuf.length < len) { int newLen = len * 2; if (newLen < 0) { newLen = Integer.MAX_VALUE; } convtBuf = new char[newLen]; } char aChar; char[] out = convtBuf; int outLen = 0; int end = off + len; while (off < end) { aChar = in[off++]; if (aChar == '\\') { aChar = in[off++]; if(aChar == 'u') { // Read the xxxx int value=0; for (int i=0; i<4; i++) { aChar = in[off++]; switch (aChar) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': value = (value << 4) + aChar - '0'; break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': value = (value << 4) + 10 + aChar - 'a'; break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': value = (value << 4) + 10 + aChar - 'A'; break; default: throw new IllegalArgumentException( "Malformed \\uxxxx encoding."); } } out[outLen++] = (char)value; } else { if (aChar == 't') aChar = '\t'; else if (aChar == 'r') aChar = '\r'; else if (aChar == 'n') aChar = '\n'; else if (aChar == 'f') aChar = '\f'; out[outLen++] = aChar; } } else { out[outLen++] = aChar; } } return new String (out, 0, outLen); } /* * Converts unicodes to encoded &#92;uxxxx and escapes * special characters with a preceding slash */ private String saveConvert(String theString, boolean escapeSpace, boolean escapeUnicode) { int len = theString.length(); int bufLen = len * 2; if (bufLen < 0) { bufLen = Integer.MAX_VALUE; } StringBuffer outBuffer = new StringBuffer(bufLen); for(int x=0; x<len; x++) { char aChar = theString.charAt(x); // Handle common case first, selecting largest block that // avoids the specials below if ((aChar > 61) && (aChar < 127)) { if (aChar == '\\') { outBuffer.append('\\'); outBuffer.append('\\'); continue; } outBuffer.append(aChar); continue; } switch(aChar) { case ' ': if (x == 0 || escapeSpace) outBuffer.append('\\'); outBuffer.append(' '); break; case '\t':outBuffer.append('\\'); outBuffer.append('t'); break; case '\n':outBuffer.append('\\'); outBuffer.append('n'); break; case '\r':outBuffer.append('\\'); outBuffer.append('r'); break; case '\f':outBuffer.append('\\'); outBuffer.append('f'); break; case '=': // Fall through case ':': // Fall through case '#': // Fall through case '!': outBuffer.append('\\'); outBuffer.append(aChar); break; default: if (((aChar < 0x0020) || (aChar > 0x007e)) & escapeUnicode ) { outBuffer.append('\\'); outBuffer.append('u'); outBuffer.append(toHex((aChar >> 12) & 0xF)); outBuffer.append(toHex((aChar >> 8) & 0xF)); outBuffer.append(toHex((aChar >> 4) & 0xF)); outBuffer.append(toHex( aChar & 0xF)); } else { outBuffer.append(aChar); } } } return outBuffer.toString(); } private static void writeComments(BufferedWriter bw, String comments) throws IOException { bw.write("#"); int len = comments.length(); int current = 0; int last = 0; char[] uu = new char[6]; uu[0] = '\\'; uu[1] = 'u'; while (current < len) { char c = comments.charAt(current); if (c > '\u00ff' || c == '\n' || c == '\r') { if (last != current) bw.write(comments.substring(last, current)); if (c > '\u00ff') { uu[2] = toHex((c >> 12) & 0xf); uu[3] = toHex((c >> 8) & 0xf); uu[4] = toHex((c >> 4) & 0xf); uu[5] = toHex( c & 0xf); bw.write(new String(uu)); } else { bw.newLine(); if (c == '\r' && current != len - 1 && comments.charAt(current + 1) == '\n') { current++; } if (current == len - 1 || (comments.charAt(current + 1) != '#' && comments.charAt(current + 1) != '!')) bw.write("#"); } last = current + 1; } current++; } if (last != current) bw.write(comments.substring(last, current)); bw.newLine(); } /** {@collect.stats} * {@description.open} * Calls the <code>store(OutputStream out, String comments)</code> method * and suppresses IOExceptions that were thrown. * {@description.close} * * @deprecated This method does not throw an IOException if an I/O error * occurs while saving the property list. The preferred way to save a * properties list is via the <code>store(OutputStream out, * String comments)</code> method or the * <code>storeToXML(OutputStream os, String comment)</code> method. * * @param out an output stream. * @param comments a description of the property list. * @exception ClassCastException if this <code>Properties</code> object * contains any keys or values that are not * <code>Strings</code>. */ @Deprecated public synchronized void save(OutputStream out, String comments) { try { store(out, comments); } catch (IOException e) { } } /** {@collect.stats} * {@description.open} * Writes this property list (key and element pairs) in this * <code>Properties</code> table to the output character stream in a * format suitable for using the {@link #load(java.io.Reader) load(Reader)} * method. * <p> * Properties from the defaults table of this <code>Properties</code> * table (if any) are <i>not</i> written out by this method. * <p> * If the comments argument is not null, then an ASCII <code>#</code> * character, the comments string, and a line separator are first written * to the output stream. Thus, the <code>comments</code> can serve as an * identifying comment. Any one of a line feed ('\n'), a carriage * return ('\r'), or a carriage return followed immediately by a line feed * in comments is replaced by a line separator generated by the <code>Writer</code> * and if the next character in comments is not character <code>#</code> or * character <code>!</code> then an ASCII <code>#</code> is written out * after that line separator. * <p> * Next, a comment line is always written, consisting of an ASCII * <code>#</code> character, the current date and time (as if produced * by the <code>toString</code> method of <code>Date</code> for the * current time), and a line separator as generated by the <code>Writer</code>. * <p> * Then every entry in this <code>Properties</code> table is * written out, one per line. For each entry the key string is * written, then an ASCII <code>=</code>, then the associated * element string. For the key, all space characters are * written with a preceding <code>\</code> character. For the * element, leading space characters, but not embedded or trailing * space characters, are written with a preceding <code>\</code> * character. The key and element characters <code>#</code>, * <code>!</code>, <code>=</code>, and <code>:</code> are written * with a preceding backslash to ensure that they are properly loaded. * <p> * After the entries have been written, the output stream is flushed. * The output stream remains open after this method returns. * <p> * {@description.close} * * @param writer an output character stream writer. * @param comments a description of the property list. * @exception IOException if writing this property list to the specified * output stream throws an <tt>IOException</tt>. * @exception ClassCastException if this <code>Properties</code> object * contains any keys or values that are not <code>Strings</code>. * @exception NullPointerException if <code>writer</code> is null. * @since 1.6 */ public void store(Writer writer, String comments) throws IOException { store0((writer instanceof BufferedWriter)?(BufferedWriter)writer : new BufferedWriter(writer), comments, false); } /** {@collect.stats} * {@description.open} * Writes this property list (key and element pairs) in this * <code>Properties</code> table to the output stream in a format suitable * for loading into a <code>Properties</code> table using the * {@link #load(InputStream) load(InputStream)} method. * <p> * Properties from the defaults table of this <code>Properties</code> * table (if any) are <i>not</i> written out by this method. * <p> * This method outputs the comments, properties keys and values in * the same format as specified in * {@link #store(java.io.Writer, java.lang.String) store(Writer)}, * with the following differences: * <ul> * <li>The stream is written using the ISO 8859-1 character encoding. * * <li>Characters not in Latin-1 in the comments are written as * <code>&#92;u</code><i>xxxx</i> for their appropriate unicode * hexadecimal value <i>xxxx</i>. * * <li>Characters less than <code>&#92;u0020</code> and characters greater * than <code>&#92;u007E</code> in property keys or values are written * as <code>&#92;u</code><i>xxxx</i> for the appropriate hexadecimal * value <i>xxxx</i>. * </ul> * <p> * After the entries have been written, the output stream is flushed. * The output stream remains open after this method returns. * <p> * {@description.close} * @param out an output stream. * @param comments a description of the property list. * @exception IOException if writing this property list to the specified * output stream throws an <tt>IOException</tt>. * @exception ClassCastException if this <code>Properties</code> object * contains any keys or values that are not <code>Strings</code>. * @exception NullPointerException if <code>out</code> is null. * @since 1.2 */ public void store(OutputStream out, String comments) throws IOException { store0(new BufferedWriter(new OutputStreamWriter(out, "8859_1")), comments, true); } private void store0(BufferedWriter bw, String comments, boolean escUnicode) throws IOException { if (comments != null) { writeComments(bw, comments); } bw.write("#" + new Date().toString()); bw.newLine(); synchronized (this) { for (Enumeration e = keys(); e.hasMoreElements();) { String key = (String)e.nextElement(); String val = (String)get(key); key = saveConvert(key, true, escUnicode); /* No need to escape embedded and trailing spaces for value, hence * pass false to flag. */ val = saveConvert(val, false, escUnicode); bw.write(key + "=" + val); bw.newLine(); } } bw.flush(); } /** {@collect.stats} * {@description.open} * Loads all of the properties represented by the XML document on the * specified input stream into this properties table. * * <p>The XML document must have the following DOCTYPE declaration: * <pre> * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt; * </pre> * Furthermore, the document must satisfy the properties DTD described * above. * {@description.close} * * {@property.open formal:java.util.Properties_ManipulateAfterLoad} * <p>The specified stream is closed after this method returns. * {@property.close} * * @param in the input stream from which to read the XML document. * @throws IOException if reading from the specified input stream * results in an <tt>IOException</tt>. * @throws InvalidPropertiesFormatException Data on input stream does not * constitute a valid XML document with the mandated document type. * @throws NullPointerException if <code>in</code> is null. * @see #storeToXML(OutputStream, String, String) * @since 1.5 */ public synchronized void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { if (in == null) throw new NullPointerException(); XMLUtils.load(this, in); in.close(); } /** {@collect.stats} * {@description.open} * Emits an XML document representing all of the properties contained * in this table. * * <p> An invocation of this method of the form <tt>props.storeToXML(os, * comment)</tt> behaves in exactly the same way as the invocation * <tt>props.storeToXML(os, comment, "UTF-8");</tt>. * {@description.close} * * @param os the output stream on which to emit the XML document. * @param comment a description of the property list, or <code>null</code> * if no comment is desired. * @throws IOException if writing to the specified output stream * results in an <tt>IOException</tt>. * @throws NullPointerException if <code>os</code> is null. * @throws ClassCastException if this <code>Properties</code> object * contains any keys or values that are not * <code>Strings</code>. * @see #loadFromXML(InputStream) * @since 1.5 */ public synchronized void storeToXML(OutputStream os, String comment) throws IOException { if (os == null) throw new NullPointerException(); storeToXML(os, comment, "UTF-8"); } /** {@collect.stats} * {@description.open} * Emits an XML document representing all of the properties contained * in this table, using the specified encoding. * * <p>The XML document will have the following DOCTYPE declaration: * <pre> * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt; * </pre> * *<p>If the specified comment is <code>null</code> then no comment * will be stored in the document. * * <p>The specified stream remains open after this method returns. * {@description.close} * * @param os the output stream on which to emit the XML document. * @param comment a description of the property list, or <code>null</code> * if no comment is desired. * @throws IOException if writing to the specified output stream * results in an <tt>IOException</tt>. * @throws NullPointerException if <code>os</code> is <code>null</code>, * or if <code>encoding</code> is <code>null</code>. * @throws ClassCastException if this <code>Properties</code> object * contains any keys or values that are not * <code>Strings</code>. * @see #loadFromXML(InputStream) * @since 1.5 */ public synchronized void storeToXML(OutputStream os, String comment, String encoding) throws IOException { if (os == null) throw new NullPointerException(); XMLUtils.save(this, os, comment, encoding); } /** {@collect.stats} * {@description.open} * Searches for the property with the specified key in this property list. * If the key is not found in this property list, the default property list, * and its defaults, recursively, are then checked. The method returns * <code>null</code> if the property is not found. * {@description.close} * * @param key the property key. * @return the value in this property list with the specified key value. * @see #setProperty * @see #defaults */ public String getProperty(String key) { Object oval = super.get(key); String sval = (oval instanceof String) ? (String)oval : null; return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval; } /** {@collect.stats} * {@description.open} * Searches for the property with the specified key in this property list. * If the key is not found in this property list, the default property list, * and its defaults, recursively, are then checked. The method returns the * default value argument if the property is not found. * {@description.close} * * @param key the hashtable key. * @param defaultValue a default value. * * @return the value in this property list with the specified key value. * @see #setProperty * @see #defaults */ public String getProperty(String key, String defaultValue) { String val = getProperty(key); return (val == null) ? defaultValue : val; } /** {@collect.stats} * {@description.open} * Returns an enumeration of all the keys in this property list, * including distinct keys in the default property list if a key * of the same name has not already been found from the main * properties list. * {@description.close} * * @return an enumeration of all the keys in this property list, including * the keys in the default property list. * @throws ClassCastException if any key in this property list * is not a string. * @see java.util.Enumeration * @see java.util.Properties#defaults * @see #stringPropertyNames */ public Enumeration<?> propertyNames() { Hashtable h = new Hashtable(); enumerate(h); return h.keys(); } /** {@collect.stats} * {@description.open} * Returns a set of keys in this property list where * the key and its corresponding value are strings, * including distinct keys in the default property list if a key * of the same name has not already been found from the main * properties list. Properties whose key or value is not * of type <tt>String</tt> are omitted. * <p> * The returned set is not backed by the <tt>Properties</tt> object. * Changes to this <tt>Properties</tt> are not reflected in the set, * or vice versa. * {@description.close} * * @return a set of keys in this property list where * the key and its corresponding value are strings, * including the keys in the default property list. * @see java.util.Properties#defaults * @since 1.6 */ public Set<String> stringPropertyNames() { Hashtable<String, String> h = new Hashtable<String, String>(); enumerateStringProperties(h); return h.keySet(); } /** {@collect.stats} * {@description.open} * Prints this property list out to the specified output stream. * This method is useful for debugging. * {@description.close} * * @param out an output stream. * @throws ClassCastException if any key in this property list * is not a string. */ public void list(PrintStream out) { out.println("-- listing properties --"); Hashtable h = new Hashtable(); enumerate(h); for (Enumeration e = h.keys() ; e.hasMoreElements() ;) { String key = (String)e.nextElement(); String val = (String)h.get(key); if (val.length() > 40) { val = val.substring(0, 37) + "..."; } out.println(key + "=" + val); } } /** {@collect.stats} * {@description.open} * Prints this property list out to the specified output stream. * This method is useful for debugging. * {@description.close} * * @param out an output stream. * @throws ClassCastException if any key in this property list * is not a string. * @since JDK1.1 */ /* * Rather than use an anonymous inner class to share common code, this * method is duplicated in order to ensure that a non-1.1 compiler can * compile this file. */ public void list(PrintWriter out) { out.println("-- listing properties --"); Hashtable h = new Hashtable(); enumerate(h); for (Enumeration e = h.keys() ; e.hasMoreElements() ;) { String key = (String)e.nextElement(); String val = (String)h.get(key); if (val.length() > 40) { val = val.substring(0, 37) + "..."; } out.println(key + "=" + val); } } /** {@collect.stats} * {@description.open} * Enumerates all key/value pairs in the specified hashtable. * {@description.close} * @param h the hashtable * @throws ClassCastException if any of the property keys * is not of String type. */ private synchronized void enumerate(Hashtable h) { if (defaults != null) { defaults.enumerate(h); } for (Enumeration e = keys() ; e.hasMoreElements() ;) { String key = (String)e.nextElement(); h.put(key, get(key)); } } /** {@collect.stats} * {@description.open} * Enumerates all key/value pairs in the specified hashtable * and omits the property if the key or value is not a string. * {@description.close} * @param h the hashtable */ private synchronized void enumerateStringProperties(Hashtable<String, String> h) { if (defaults != null) { defaults.enumerateStringProperties(h); } for (Enumeration e = keys() ; e.hasMoreElements() ;) { Object k = e.nextElement(); Object v = get(k); if (k instanceof String && v instanceof String) { h.put((String) k, (String) v); } } } /** {@collect.stats} * {@description.open} * Convert a nibble to a hex character * {@description.close} * @param nibble the nibble to convert. */ private static char toHex(int nibble) { return hexDigit[(nibble & 0xF)]; } /** {@collect.stats} * {@description.open} * A table of hex digits * {@description.close} */ private static final char[] hexDigit = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' }; }
Java
/* * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * A Red-Black tree based {@link NavigableMap} implementation. * The map is sorted according to the {@linkplain Comparable natural * ordering} of its keys, or by a {@link Comparator} provided at map * creation time, depending on which constructor is used. * * <p>This implementation provides guaranteed log(n) time cost for the * <tt>containsKey</tt>, <tt>get</tt>, <tt>put</tt> and <tt>remove</tt> * operations. Algorithms are adaptations of those in Cormen, Leiserson, and * Rivest's <I>Introduction to Algorithms</I>. * * <p>Note that the ordering maintained by a sorted map (whether or not an * explicit comparator is provided) must be <i>consistent with equals</i> if * this sorted map is to correctly implement the <tt>Map</tt> interface. (See * <tt>Comparable</tt> or <tt>Comparator</tt> for a precise definition of * <i>consistent with equals</i>.) This is so because the <tt>Map</tt> * interface is defined in terms of the equals operation, but a map performs * all key comparisons using its <tt>compareTo</tt> (or <tt>compare</tt>) * method, so two keys that are deemed equal by this method are, from the * standpoint of the sorted map, equal. The behavior of a sorted map * <i>is</i> well-defined even if its ordering is inconsistent with equals; it * just fails to obey the general contract of the <tt>Map</tt> interface. * {@description.close} * * {@property.open formal:java.util.Collections_SynchronizedMap} * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access a map concurrently, and at least one of the * threads modifies the map structurally, it <i>must</i> be synchronized * externally. (A structural modification is any operation that adds or * deletes one or more mappings; merely changing the value associated * with an existing key is not a structural modification.) This is * typically accomplished by synchronizing on some object that naturally * encapsulates the map. * If no such object exists, the map should be "wrapped" using the * {@link Collections#synchronizedSortedMap Collections.synchronizedSortedMap} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the map: <pre> * SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));</pre> * {@property.close} * * {@property.open formal:java.util.Map_UnsafeIterator} * <p>The iterators returned by the <tt>iterator</tt> method of the collections * returned by all of this class's "collection view methods" are * <i>fail-fast</i>: if the map is structurally modified at any time after the * iterator is created, in any way except through the iterator's own * <tt>remove</tt> method, the iterator will throw a {@link * ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * {@property.close} * * {@description.open} * <p>All <tt>Map.Entry</tt> pairs returned by methods in this class * and its views represent snapshots of mappings at the time they were * produced. They do <em>not</em> support the <tt>Entry.setValue</tt> * method. (Note however that it is possible to change mappings in the * associated map using <tt>put</tt>.) * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Josh Bloch and Doug Lea * @see Map * @see HashMap * @see Hashtable * @see Comparable * @see Comparator * @see Collection * @since 1.2 */ public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, java.io.Serializable { /** {@collect.stats} * {@description.open} * The comparator used to maintain order in this tree map, or * null if it uses the natural ordering of its keys. * {@description.close} * * @serial */ private final Comparator<? super K> comparator; private transient Entry<K,V> root = null; /** {@collect.stats} * {@description.open} * The number of entries in the tree * {@description.close} */ private transient int size = 0; /** {@collect.stats} * {@description.open} * The number of structural modifications to the tree. * {@description.close} */ private transient int modCount = 0; /** {@collect.stats} * {@description.open} * Constructs a new, empty tree map, using the natural ordering of its * keys. * {@description.close} * {@property.open formal:java.util.TreeMap_Comparable} * All keys inserted into the map must implement the {@link * Comparable} interface. Furthermore, all such keys must be * <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw * a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and * <tt>k2</tt> in the map. If the user attempts to put a key into the * map that violates this constraint (for example, the user attempts to * put a string key into a map whose keys are integers), the * <tt>put(Object key, Object value)</tt> call will throw a * <tt>ClassCastException</tt>. * {@property.close} */ public TreeMap() { comparator = null; } /** {@collect.stats} * {@description.open} * Constructs a new, empty tree map, ordered according to the given * comparator. * {@description.close} * {@property.open formal:java.util.TreeMap_Comparable} * All keys inserted into the map must be <i>mutually * comparable</i> by the given comparator: <tt>comparator.compare(k1, * k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys * <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts to put * a key into the map that violates this constraint, the <tt>put(Object * key, Object value)</tt> call will throw a * <tt>ClassCastException</tt>. * {@property.close} * * @param comparator the comparator that will be used to order this map. * If <tt>null</tt>, the {@linkplain Comparable natural * ordering} of the keys will be used. */ public TreeMap(Comparator<? super K> comparator) { this.comparator = comparator; } /** {@collect.stats} * {@description.open} * Constructs a new tree map containing the same mappings as the given * map, ordered according to the <i>natural ordering</i> of its keys. * {@description.close} * {@property.open formal:java.util.TreeMap_Comparable} * All keys inserted into the new map must implement the {@link * Comparable} interface. Furthermore, all such keys must be * <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw * a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and * <tt>k2</tt> in the map. * {@property.close} * {@description.open} * This method runs in n*log(n) time. * {@description.close} * * @param m the map whose mappings are to be placed in this map * @throws ClassCastException if the keys in m are not {@link Comparable}, * or are not mutually comparable * @throws NullPointerException if the specified map is null */ public TreeMap(Map<? extends K, ? extends V> m) { comparator = null; putAll(m); } /** {@collect.stats} * {@description.open} * Constructs a new tree map containing the same mappings and * using the same ordering as the specified sorted map. This * method runs in linear time. * {@description.close} * * @param m the sorted map whose mappings are to be placed in this map, * and whose comparator is to be used to sort this map * @throws NullPointerException if the specified map is null */ public TreeMap(SortedMap<K, ? extends V> m) { comparator = m.comparator(); try { buildFromSorted(m.size(), m.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } // Query Operations /** {@collect.stats} * {@description.open} * Returns the number of key-value mappings in this map. * {@description.close} * * @return the number of key-value mappings in this map */ public int size() { return size; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map contains a mapping for the specified * key. * {@description.close} * * @param key key whose presence in this map is to be tested * @return <tt>true</tt> if this map contains a mapping for the * specified key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys */ public boolean containsKey(Object key) { return getEntry(key) != null; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map maps one or more keys to the * specified value. More formally, returns <tt>true</tt> if and only if * this map contains at least one mapping to a value <tt>v</tt> such * that <tt>(value==null ? v==null : value.equals(v))</tt>. This * operation will probably require time linear in the map size for * most implementations. * {@description.close} * * @param value value whose presence in this map is to be tested * @return <tt>true</tt> if a mapping to <tt>value</tt> exists; * <tt>false</tt> otherwise * @since 1.2 */ public boolean containsValue(Object value) { for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) if (valEquals(value, e.value)) return true; return false; } /** {@collect.stats} * {@description.open} * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code key} compares * equal to {@code k} according to the map's ordering, then this * method returns {@code v}; otherwise it returns {@code null}. * (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * {@description.close} * * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys */ public V get(Object key) { Entry<K,V> p = getEntry(key); return (p==null ? null : p.value); } public Comparator<? super K> comparator() { return comparator; } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public K firstKey() { return key(getFirstEntry()); } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public K lastKey() { return key(getLastEntry()); } /** {@collect.stats} * {@description.open} * Copies all of the mappings from the specified map to this map. * These mappings replace any mappings that this map had for any * of the keys currently in the specified map. * {@description.close} * * @param map mappings to be stored in this map * @throws ClassCastException if the class of a key or value in * the specified map prevents it from being stored in this map * @throws NullPointerException if the specified map is null or * the specified map contains a null key and this map does not * permit null keys */ public void putAll(Map<? extends K, ? extends V> map) { int mapSize = map.size(); if (size==0 && mapSize!=0 && map instanceof SortedMap) { Comparator c = ((SortedMap)map).comparator(); if (c == comparator || (c != null && c.equals(comparator))) { ++modCount; try { buildFromSorted(mapSize, map.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return; } } super.putAll(map); } /** {@collect.stats} * {@description.open} * Returns this map's entry for the given key, or <tt>null</tt> if the map * does not contain an entry for the key. * {@description.close} * * @return this map's entry for the given key, or <tt>null</tt> if the map * does not contain an entry for the key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys */ final Entry<K,V> getEntry(Object key) { // Offload comparator-based version for sake of performance if (comparator != null) return getEntryUsingComparator(key); if (key == null) throw new NullPointerException(); Comparable<? super K> k = (Comparable<? super K>) key; Entry<K,V> p = root; while (p != null) { int cmp = k.compareTo(p.key); if (cmp < 0) p = p.left; else if (cmp > 0) p = p.right; else return p; } return null; } /** {@collect.stats} * {@description.open} * Version of getEntry using comparator. Split off from getEntry * for performance. (This is not worth doing for most methods, * that are less dependent on comparator performance, but is * worthwhile here.) * {@description.close} */ final Entry<K,V> getEntryUsingComparator(Object key) { K k = (K) key; Comparator<? super K> cpr = comparator; if (cpr != null) { Entry<K,V> p = root; while (p != null) { int cmp = cpr.compare(k, p.key); if (cmp < 0) p = p.left; else if (cmp > 0) p = p.right; else return p; } } return null; } /** {@collect.stats} * {@description.open} * Gets the entry corresponding to the specified key; if no such entry * exists, returns the entry for the least key greater than the specified * key; if no such entry exists (i.e., the greatest key in the Tree is less * than the specified key), returns <tt>null</tt>. * {@description.close} */ final Entry<K,V> getCeilingEntry(K key) { Entry<K,V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp < 0) { if (p.left != null) p = p.left; else return p; } else if (cmp > 0) { if (p.right != null) { p = p.right; } else { Entry<K,V> parent = p.parent; Entry<K,V> ch = p; while (parent != null && ch == parent.right) { ch = parent; parent = parent.parent; } return parent; } } else return p; } return null; } /** {@collect.stats} * {@description.open} * Gets the entry corresponding to the specified key; if no such entry * exists, returns the entry for the greatest key less than the specified * key; if no such entry exists, returns <tt>null</tt>. * {@description.close} */ final Entry<K,V> getFloorEntry(K key) { Entry<K,V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp > 0) { if (p.right != null) p = p.right; else return p; } else if (cmp < 0) { if (p.left != null) { p = p.left; } else { Entry<K,V> parent = p.parent; Entry<K,V> ch = p; while (parent != null && ch == parent.left) { ch = parent; parent = parent.parent; } return parent; } } else return p; } return null; } /** {@collect.stats} * {@description.open} * Gets the entry for the least key greater than the specified * key; if no such entry exists, returns the entry for the least * key greater than the specified key; if no such entry exists * returns <tt>null</tt>. * {@description.close} */ final Entry<K,V> getHigherEntry(K key) { Entry<K,V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp < 0) { if (p.left != null) p = p.left; else return p; } else { if (p.right != null) { p = p.right; } else { Entry<K,V> parent = p.parent; Entry<K,V> ch = p; while (parent != null && ch == parent.right) { ch = parent; parent = parent.parent; } return parent; } } } return null; } /** {@collect.stats} * {@description.open} * Returns the entry for the greatest key less than the specified key; if * no such entry exists (i.e., the least key in the Tree is greater than * the specified key), returns <tt>null</tt>. * {@description.close} */ final Entry<K,V> getLowerEntry(K key) { Entry<K,V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp > 0) { if (p.right != null) p = p.right; else return p; } else { if (p.left != null) { p = p.left; } else { Entry<K,V> parent = p.parent; Entry<K,V> ch = p; while (parent != null && ch == parent.left) { ch = parent; parent = parent.parent; } return parent; } } } return null; } /** {@collect.stats} * {@description.open} * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * {@description.close} * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys */ public V put(K key, V value) { Entry<K,V> t = root; if (t == null) { // TBD: // 5045147: (coll) Adding null to an empty TreeSet should // throw NullPointerException // // compare(key, key); // type check root = new Entry<K,V>(key, value, null); size = 1; modCount++; return null; } int cmp; Entry<K,V> parent; // split comparator and comparable paths Comparator<? super K> cpr = comparator; if (cpr != null) { do { parent = t; cmp = cpr.compare(key, t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } else { if (key == null) throw new NullPointerException(); Comparable<? super K> k = (Comparable<? super K>) key; do { parent = t; cmp = k.compareTo(t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } Entry<K,V> e = new Entry<K,V>(key, value, parent); if (cmp < 0) parent.left = e; else parent.right = e; fixAfterInsertion(e); size++; modCount++; return null; } /** {@collect.stats} * {@description.open} * Removes the mapping for this key from this TreeMap if present. * {@description.close} * * @param key key for which mapping should be removed * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys */ public V remove(Object key) { Entry<K,V> p = getEntry(key); if (p == null) return null; V oldValue = p.value; deleteEntry(p); return oldValue; } /** {@collect.stats} * {@description.open} * Removes all of the mappings from this map. * The map will be empty after this call returns. * {@description.close} */ public void clear() { modCount++; size = 0; root = null; } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this <tt>TreeMap</tt> instance. (The keys and * values themselves are not cloned.) * {@description.close} * * @return a shallow copy of this map */ public Object clone() { TreeMap<K,V> clone = null; try { clone = (TreeMap<K,V>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } // Put clone into "virgin" state (except for comparator) clone.root = null; clone.size = 0; clone.modCount = 0; clone.entrySet = null; clone.navigableKeySet = null; clone.descendingMap = null; // Initialize clone with our mappings try { clone.buildFromSorted(size, entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return clone; } // NavigableMap API methods /** {@collect.stats} * @since 1.6 */ public Map.Entry<K,V> firstEntry() { return exportEntry(getFirstEntry()); } /** {@collect.stats} * @since 1.6 */ public Map.Entry<K,V> lastEntry() { return exportEntry(getLastEntry()); } /** {@collect.stats} * @since 1.6 */ public Map.Entry<K,V> pollFirstEntry() { Entry<K,V> p = getFirstEntry(); Map.Entry<K,V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } /** {@collect.stats} * @since 1.6 */ public Map.Entry<K,V> pollLastEntry() { Entry<K,V> p = getLastEntry(); Map.Entry<K,V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys * @since 1.6 */ public Map.Entry<K,V> lowerEntry(K key) { return exportEntry(getLowerEntry(key)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys * @since 1.6 */ public K lowerKey(K key) { return keyOrNull(getLowerEntry(key)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys * @since 1.6 */ public Map.Entry<K,V> floorEntry(K key) { return exportEntry(getFloorEntry(key)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys * @since 1.6 */ public K floorKey(K key) { return keyOrNull(getFloorEntry(key)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys * @since 1.6 */ public Map.Entry<K,V> ceilingEntry(K key) { return exportEntry(getCeilingEntry(key)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys * @since 1.6 */ public K ceilingKey(K key) { return keyOrNull(getCeilingEntry(key)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys * @since 1.6 */ public Map.Entry<K,V> higherEntry(K key) { return exportEntry(getHigherEntry(key)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys * @since 1.6 */ public K higherKey(K key) { return keyOrNull(getHigherEntry(key)); } // Views /** {@collect.stats} * {@description.open} * Fields initialized to contain an instance of the entry set view * the first time this view is requested. Views are stateless, so * there's no reason to create more than one. * {@description.close} */ private transient EntrySet entrySet = null; private transient KeySet<K> navigableKeySet = null; private transient NavigableMap<K,V> descendingMap = null; /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the keys contained in this map. * The set's iterator returns the keys in ascending order. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. * {@property.close} */ public Set<K> keySet() { return navigableKeySet(); } /** {@collect.stats} * @since 1.6 */ public NavigableSet<K> navigableKeySet() { KeySet<K> nks = navigableKeySet; return (nks != null) ? nks : (navigableKeySet = new KeySet(this)); } /** {@collect.stats} * @since 1.6 */ public NavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } /** {@collect.stats} * {@description.open} * Returns a {@link Collection} view of the values contained in this map. * The collection's iterator returns the values in ascending order * of the corresponding keys. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is * modified while an iteration over the collection is in progress * (except through the iterator's own <tt>remove</tt> operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Collection.remove</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not * support the <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} */ public Collection<V> values() { Collection<V> vs = values; return (vs != null) ? vs : (values = new Values()); } /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the mappings contained in this map. * The set's iterator returns the entries in ascending key order. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation, or through the * <tt>setValue</tt> operation on a map entry returned by the * iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and * <tt>clear</tt> operations. It does not support the * <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} */ public Set<Map.Entry<K,V>> entrySet() { EntrySet es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } /** {@collect.stats} * @since 1.6 */ public NavigableMap<K, V> descendingMap() { NavigableMap<K, V> km = descendingMap; return (km != null) ? km : (descendingMap = new DescendingSubMap(this, true, null, true, true, null, true)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is * null and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} * @since 1.6 */ public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return new AscendingSubMap(this, false, fromKey, fromInclusive, false, toKey, toInclusive); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if <tt>toKey</tt> is null * and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} * @since 1.6 */ public NavigableMap<K,V> headMap(K toKey, boolean inclusive) { return new AscendingSubMap(this, true, null, true, false, toKey, inclusive); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if <tt>fromKey</tt> is null * and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} * @since 1.6 */ public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) { return new AscendingSubMap(this, false, fromKey, inclusive, true, null, true); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is * null and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} */ public SortedMap<K,V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if <tt>toKey</tt> is null * and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} */ public SortedMap<K,V> headMap(K toKey) { return headMap(toKey, false); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if <tt>fromKey</tt> is null * and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} */ public SortedMap<K,V> tailMap(K fromKey) { return tailMap(fromKey, true); } // View class support class Values extends AbstractCollection<V> { public Iterator<V> iterator() { return new ValueIterator(getFirstEntry()); } public int size() { return TreeMap.this.size(); } public boolean contains(Object o) { return TreeMap.this.containsValue(o); } public boolean remove(Object o) { for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) { if (valEquals(e.getValue(), o)) { deleteEntry(e); return true; } } return false; } public void clear() { TreeMap.this.clear(); } } class EntrySet extends AbstractSet<Map.Entry<K,V>> { public Iterator<Map.Entry<K,V>> iterator() { return new EntryIterator(getFirstEntry()); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K,V> entry = (Map.Entry<K,V>) o; V value = entry.getValue(); Entry<K,V> p = getEntry(entry.getKey()); return p != null && valEquals(p.getValue(), value); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K,V> entry = (Map.Entry<K,V>) o; V value = entry.getValue(); Entry<K,V> p = getEntry(entry.getKey()); if (p != null && valEquals(p.getValue(), value)) { deleteEntry(p); return true; } return false; } public int size() { return TreeMap.this.size(); } public void clear() { TreeMap.this.clear(); } } /* * Unlike Values and EntrySet, the KeySet class is static, * delegating to a NavigableMap to allow use by SubMaps, which * outweighs the ugliness of needing type-tests for the following * Iterator methods that are defined appropriately in main versus * submap classes. */ Iterator<K> keyIterator() { return new KeyIterator(getFirstEntry()); } Iterator<K> descendingKeyIterator() { return new DescendingKeyIterator(getLastEntry()); } static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> { private final NavigableMap<E, Object> m; KeySet(NavigableMap<E,Object> map) { m = map; } public Iterator<E> iterator() { if (m instanceof TreeMap) return ((TreeMap<E,Object>)m).keyIterator(); else return (Iterator<E>)(((TreeMap.NavigableSubMap)m).keyIterator()); } public Iterator<E> descendingIterator() { if (m instanceof TreeMap) return ((TreeMap<E,Object>)m).descendingKeyIterator(); else return (Iterator<E>)(((TreeMap.NavigableSubMap)m).descendingKeyIterator()); } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean contains(Object o) { return m.containsKey(o); } public void clear() { m.clear(); } public E lower(E e) { return m.lowerKey(e); } public E floor(E e) { return m.floorKey(e); } public E ceiling(E e) { return m.ceilingKey(e); } public E higher(E e) { return m.higherKey(e); } public E first() { return m.firstKey(); } public E last() { return m.lastKey(); } public Comparator<? super E> comparator() { return m.comparator(); } public E pollFirst() { Map.Entry<E,Object> e = m.pollFirstEntry(); return e == null? null : e.getKey(); } public E pollLast() { Map.Entry<E,Object> e = m.pollLastEntry(); return e == null? null : e.getKey(); } public boolean remove(Object o) { int oldSize = size(); m.remove(o); return size() != oldSize; } public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new KeySet<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive)); } public NavigableSet<E> headSet(E toElement, boolean inclusive) { return new KeySet<E>(m.headMap(toElement, inclusive)); } public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new KeySet<E>(m.tailMap(fromElement, inclusive)); } public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } public NavigableSet<E> descendingSet() { return new KeySet(m.descendingMap()); } } /** {@collect.stats} * {@description.open} * Base class for TreeMap Iterators * {@description.close} */ abstract class PrivateEntryIterator<T> implements Iterator<T> { Entry<K,V> next; Entry<K,V> lastReturned; int expectedModCount; PrivateEntryIterator(Entry<K,V> first) { expectedModCount = modCount; lastReturned = null; next = first; } public final boolean hasNext() { return next != null; } final Entry<K,V> nextEntry() { Entry<K,V> e = next; if (e == null) throw new NoSuchElementException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); next = successor(e); lastReturned = e; return e; } final Entry<K,V> prevEntry() { Entry<K,V> e = next; if (e == null) throw new NoSuchElementException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); next = predecessor(e); lastReturned = e; return e; } public void remove() { if (lastReturned == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.left != null && lastReturned.right != null) next = lastReturned; deleteEntry(lastReturned); expectedModCount = modCount; lastReturned = null; } } final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> { EntryIterator(Entry<K,V> first) { super(first); } public Map.Entry<K,V> next() { return nextEntry(); } } final class ValueIterator extends PrivateEntryIterator<V> { ValueIterator(Entry<K,V> first) { super(first); } public V next() { return nextEntry().value; } } final class KeyIterator extends PrivateEntryIterator<K> { KeyIterator(Entry<K,V> first) { super(first); } public K next() { return nextEntry().key; } } final class DescendingKeyIterator extends PrivateEntryIterator<K> { DescendingKeyIterator(Entry<K,V> first) { super(first); } public K next() { return prevEntry().key; } } // Little utilities /** {@collect.stats} * {@description.open} * Compares two keys using the correct comparison method for this TreeMap. * {@description.close} */ final int compare(Object k1, Object k2) { return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2) : comparator.compare((K)k1, (K)k2); } /** {@collect.stats} * {@description.open} * Test two values for equality. Differs from o1.equals(o2) only in * that it copes with <tt>null</tt> o1 properly. * {@description.close} */ final static boolean valEquals(Object o1, Object o2) { return (o1==null ? o2==null : o1.equals(o2)); } /** {@collect.stats} * {@description.open} * Return SimpleImmutableEntry for entry, or null if null * {@description.close} */ static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) { return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e); } /** {@collect.stats} * {@description.open} * Return key for entry, or null if null * {@description.close} */ static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) { return e == null? null : e.key; } /** {@collect.stats} * {@description.open} * Returns the key corresponding to the specified Entry. * {@description.close} * @throws NoSuchElementException if the Entry is null */ static <K> K key(Entry<K,?> e) { if (e==null) throw new NoSuchElementException(); return e.key; } // SubMaps /** {@collect.stats} * {@description.open} * Dummy value serving as unmatchable fence key for unbounded * SubMapIterators * {@description.close} */ private static final Object UNBOUNDED = new Object(); /** {@collect.stats} * @serial include */ static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, java.io.Serializable { /** {@collect.stats} * {@description.open} * The backing map. * {@description.close} */ final TreeMap<K,V> m; /** {@collect.stats} * {@description.open} * Endpoints are represented as triples (fromStart, lo, * loInclusive) and (toEnd, hi, hiInclusive). If fromStart is * true, then the low (absolute) bound is the start of the * backing map, and the other values are ignored. Otherwise, * if loInclusive is true, lo is the inclusive bound, else lo * is the exclusive bound. Similarly for the upper bound. * {@description.close} */ final K lo, hi; final boolean fromStart, toEnd; final boolean loInclusive, hiInclusive; NavigableSubMap(TreeMap<K,V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) { if (!fromStart && !toEnd) { if (m.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); } else { if (!fromStart) // type check m.compare(lo, lo); if (!toEnd) m.compare(hi, hi); } this.m = m; this.fromStart = fromStart; this.lo = lo; this.loInclusive = loInclusive; this.toEnd = toEnd; this.hi = hi; this.hiInclusive = hiInclusive; } // internal utilities final boolean tooLow(Object key) { if (!fromStart) { int c = m.compare(key, lo); if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } final boolean tooHigh(Object key) { if (!toEnd) { int c = m.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } final boolean inRange(Object key) { return !tooLow(key) && !tooHigh(key); } final boolean inClosedRange(Object key) { return (fromStart || m.compare(key, lo) >= 0) && (toEnd || m.compare(hi, key) >= 0); } final boolean inRange(Object key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } /* * Absolute versions of relation operations. * Subclasses map to these using like-named "sub" * versions that invert senses for descending maps */ final TreeMap.Entry<K,V> absLowest() { TreeMap.Entry<K,V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo) : m.getHigherEntry(lo))); return (e == null || tooHigh(e.key)) ? null : e; } final TreeMap.Entry<K,V> absHighest() { TreeMap.Entry<K,V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi) : m.getLowerEntry(hi))); return (e == null || tooLow(e.key)) ? null : e; } final TreeMap.Entry<K,V> absCeiling(K key) { if (tooLow(key)) return absLowest(); TreeMap.Entry<K,V> e = m.getCeilingEntry(key); return (e == null || tooHigh(e.key)) ? null : e; } final TreeMap.Entry<K,V> absHigher(K key) { if (tooLow(key)) return absLowest(); TreeMap.Entry<K,V> e = m.getHigherEntry(key); return (e == null || tooHigh(e.key)) ? null : e; } final TreeMap.Entry<K,V> absFloor(K key) { if (tooHigh(key)) return absHighest(); TreeMap.Entry<K,V> e = m.getFloorEntry(key); return (e == null || tooLow(e.key)) ? null : e; } final TreeMap.Entry<K,V> absLower(K key) { if (tooHigh(key)) return absHighest(); TreeMap.Entry<K,V> e = m.getLowerEntry(key); return (e == null || tooLow(e.key)) ? null : e; } /** {@collect.stats} * {@description.open} * Returns the absolute high fence for ascending traversal * {@description.close} */ final TreeMap.Entry<K,V> absHighFence() { return (toEnd ? null : (hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi))); } /** {@collect.stats} * {@description.open} * Return the absolute low fence for descending traversal * {@description.close} */ final TreeMap.Entry<K,V> absLowFence() { return (fromStart ? null : (loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo))); } // Abstract methods defined in ascending vs descending classes // These relay to the appropriate absolute versions abstract TreeMap.Entry<K,V> subLowest(); abstract TreeMap.Entry<K,V> subHighest(); abstract TreeMap.Entry<K,V> subCeiling(K key); abstract TreeMap.Entry<K,V> subHigher(K key); abstract TreeMap.Entry<K,V> subFloor(K key); abstract TreeMap.Entry<K,V> subLower(K key); /** {@collect.stats} * {@description.open} * Returns ascending iterator from the perspective of this submap * {@description.close} */ abstract Iterator<K> keyIterator(); /** {@collect.stats} * {@description.open} * Returns descending iterator from the perspective of this submap * {@description.close} */ abstract Iterator<K> descendingKeyIterator(); // public methods public boolean isEmpty() { return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty(); } public int size() { return (fromStart && toEnd) ? m.size() : entrySet().size(); } public final boolean containsKey(Object key) { return inRange(key) && m.containsKey(key); } public final V put(K key, V value) { if (!inRange(key)) throw new IllegalArgumentException("key out of range"); return m.put(key, value); } public final V get(Object key) { return !inRange(key)? null : m.get(key); } public final V remove(Object key) { return !inRange(key)? null : m.remove(key); } public final Map.Entry<K,V> ceilingEntry(K key) { return exportEntry(subCeiling(key)); } public final K ceilingKey(K key) { return keyOrNull(subCeiling(key)); } public final Map.Entry<K,V> higherEntry(K key) { return exportEntry(subHigher(key)); } public final K higherKey(K key) { return keyOrNull(subHigher(key)); } public final Map.Entry<K,V> floorEntry(K key) { return exportEntry(subFloor(key)); } public final K floorKey(K key) { return keyOrNull(subFloor(key)); } public final Map.Entry<K,V> lowerEntry(K key) { return exportEntry(subLower(key)); } public final K lowerKey(K key) { return keyOrNull(subLower(key)); } public final K firstKey() { return key(subLowest()); } public final K lastKey() { return key(subHighest()); } public final Map.Entry<K,V> firstEntry() { return exportEntry(subLowest()); } public final Map.Entry<K,V> lastEntry() { return exportEntry(subHighest()); } public final Map.Entry<K,V> pollFirstEntry() { TreeMap.Entry<K,V> e = subLowest(); Map.Entry<K,V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } public final Map.Entry<K,V> pollLastEntry() { TreeMap.Entry<K,V> e = subHighest(); Map.Entry<K,V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } // Views transient NavigableMap<K,V> descendingMapView = null; transient EntrySetView entrySetView = null; transient KeySet<K> navigableKeySetView = null; public final NavigableSet<K> navigableKeySet() { KeySet<K> nksv = navigableKeySetView; return (nksv != null) ? nksv : (navigableKeySetView = new TreeMap.KeySet(this)); } public final Set<K> keySet() { return navigableKeySet(); } public NavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } public final SortedMap<K,V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } public final SortedMap<K,V> headMap(K toKey) { return headMap(toKey, false); } public final SortedMap<K,V> tailMap(K fromKey) { return tailMap(fromKey, true); } // View classes abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> { private transient int size = -1, sizeModCount; public int size() { if (fromStart && toEnd) return m.size(); if (size == -1 || sizeModCount != m.modCount) { sizeModCount = m.modCount; size = 0; Iterator i = iterator(); while (i.hasNext()) { size++; i.next(); } } return size; } public boolean isEmpty() { TreeMap.Entry<K,V> n = absLowest(); return n == null || tooHigh(n.key); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K,V> entry = (Map.Entry<K,V>) o; K key = entry.getKey(); if (!inRange(key)) return false; TreeMap.Entry node = m.getEntry(key); return node != null && valEquals(node.getValue(), entry.getValue()); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K,V> entry = (Map.Entry<K,V>) o; K key = entry.getKey(); if (!inRange(key)) return false; TreeMap.Entry<K,V> node = m.getEntry(key); if (node!=null && valEquals(node.getValue(),entry.getValue())){ m.deleteEntry(node); return true; } return false; } } /** {@collect.stats} * {@description.open} * Iterators for SubMaps * {@description.close} */ abstract class SubMapIterator<T> implements Iterator<T> { TreeMap.Entry<K,V> lastReturned; TreeMap.Entry<K,V> next; final Object fenceKey; int expectedModCount; SubMapIterator(TreeMap.Entry<K,V> first, TreeMap.Entry<K,V> fence) { expectedModCount = m.modCount; lastReturned = null; next = first; fenceKey = fence == null ? UNBOUNDED : fence.key; } public final boolean hasNext() { return next != null && next.key != fenceKey; } final TreeMap.Entry<K,V> nextEntry() { TreeMap.Entry<K,V> e = next; if (e == null || e.key == fenceKey) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next = successor(e); lastReturned = e; return e; } final TreeMap.Entry<K,V> prevEntry() { TreeMap.Entry<K,V> e = next; if (e == null || e.key == fenceKey) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next = predecessor(e); lastReturned = e; return e; } final void removeAscending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.left != null && lastReturned.right != null) next = lastReturned; m.deleteEntry(lastReturned); lastReturned = null; expectedModCount = m.modCount; } final void removeDescending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); m.deleteEntry(lastReturned); lastReturned = null; expectedModCount = m.modCount; } } final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> { SubMapEntryIterator(TreeMap.Entry<K,V> first, TreeMap.Entry<K,V> fence) { super(first, fence); } public Map.Entry<K,V> next() { return nextEntry(); } public void remove() { removeAscending(); } } final class SubMapKeyIterator extends SubMapIterator<K> { SubMapKeyIterator(TreeMap.Entry<K,V> first, TreeMap.Entry<K,V> fence) { super(first, fence); } public K next() { return nextEntry().key; } public void remove() { removeAscending(); } } final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> { DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last, TreeMap.Entry<K,V> fence) { super(last, fence); } public Map.Entry<K,V> next() { return prevEntry(); } public void remove() { removeDescending(); } } final class DescendingSubMapKeyIterator extends SubMapIterator<K> { DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last, TreeMap.Entry<K,V> fence) { super(last, fence); } public K next() { return prevEntry().key; } public void remove() { removeDescending(); } } } /** {@collect.stats} * @serial include */ static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> { private static final long serialVersionUID = 912986545866124060L; AscendingSubMap(TreeMap<K,V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return m.comparator(); } public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap(m, false, fromKey, fromInclusive, false, toKey, toInclusive); } public NavigableMap<K,V> headMap(K toKey, boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap(m, fromStart, lo, loInclusive, false, toKey, inclusive); } public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){ if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new AscendingSubMap(m, false, fromKey, inclusive, toEnd, hi, hiInclusive); } public NavigableMap<K,V> descendingMap() { NavigableMap<K,V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new DescendingSubMap(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } Iterator<K> keyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } Iterator<K> descendingKeyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } final class AscendingEntrySetView extends EntrySetView { public Iterator<Map.Entry<K,V>> iterator() { return new SubMapEntryIterator(absLowest(), absHighFence()); } } public Set<Map.Entry<K,V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : new AscendingEntrySetView(); } TreeMap.Entry<K,V> subLowest() { return absLowest(); } TreeMap.Entry<K,V> subHighest() { return absHighest(); } TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); } TreeMap.Entry<K,V> subHigher(K key) { return absHigher(key); } TreeMap.Entry<K,V> subFloor(K key) { return absFloor(key); } TreeMap.Entry<K,V> subLower(K key) { return absLower(key); } } /** {@collect.stats} * @serial include */ static final class DescendingSubMap<K,V> extends NavigableSubMap<K,V> { private static final long serialVersionUID = 912986545866120460L; DescendingSubMap(TreeMap<K,V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator); public Comparator<? super K> comparator() { return reverseComparator; } public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap(m, false, toKey, toInclusive, false, fromKey, fromInclusive); } public NavigableMap<K,V> headMap(K toKey, boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap(m, false, toKey, inclusive, toEnd, hi, hiInclusive); } public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){ if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new DescendingSubMap(m, fromStart, lo, loInclusive, false, fromKey, inclusive); } public NavigableMap<K,V> descendingMap() { NavigableMap<K,V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new AscendingSubMap(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } Iterator<K> keyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } Iterator<K> descendingKeyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } final class DescendingEntrySetView extends EntrySetView { public Iterator<Map.Entry<K,V>> iterator() { return new DescendingSubMapEntryIterator(absHighest(), absLowFence()); } } public Set<Map.Entry<K,V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : new DescendingEntrySetView(); } TreeMap.Entry<K,V> subLowest() { return absHighest(); } TreeMap.Entry<K,V> subHighest() { return absLowest(); } TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); } TreeMap.Entry<K,V> subHigher(K key) { return absLower(key); } TreeMap.Entry<K,V> subFloor(K key) { return absCeiling(key); } TreeMap.Entry<K,V> subLower(K key) { return absHigher(key); } } /** {@collect.stats} * {@description.open} * This class exists solely for the sake of serialization * compatibility with previous releases of TreeMap that did not * support NavigableMap. It translates an old-version SubMap into * a new-version AscendingSubMap. This class is never otherwise * used. * {@description.close} * * @serial include */ private class SubMap extends AbstractMap<K,V> implements SortedMap<K,V>, java.io.Serializable { private static final long serialVersionUID = -6520786458950516097L; private boolean fromStart = false, toEnd = false; private K fromKey, toKey; private Object readResolve() { return new AscendingSubMap(TreeMap.this, fromStart, fromKey, true, toEnd, toKey, false); } public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); } public K lastKey() { throw new InternalError(); } public K firstKey() { throw new InternalError(); } public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); } public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); } public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); } public Comparator<? super K> comparator() { throw new InternalError(); } } // Red-black mechanics private static final boolean RED = false; private static final boolean BLACK = true; /** {@collect.stats} * {@description.open} * Node in the Tree. Doubles as a means to pass key-value pairs back to * user (see Map.Entry). * {@description.close} */ static final class Entry<K,V> implements Map.Entry<K,V> { K key; V value; Entry<K,V> left = null; Entry<K,V> right = null; Entry<K,V> parent; boolean color = BLACK; /** {@collect.stats} * {@description.open} * Make a new cell with given key, value, and parent, and with * <tt>null</tt> child links, and BLACK color. * {@description.close} */ Entry(K key, V value, Entry<K,V> parent) { this.key = key; this.value = value; this.parent = parent; } /** {@collect.stats} * {@description.open} * Returns the key. * {@description.close} * * @return the key */ public K getKey() { return key; } /** {@collect.stats} * {@description.open} * Returns the value associated with the key. * {@description.close} * * @return the value associated with the key */ public V getValue() { return value; } /** {@collect.stats} * {@description.open} * Replaces the value currently associated with the key with the given * value. * {@description.close} * * @return the value associated with the key before this method was * called */ public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; return valEquals(key,e.getKey()) && valEquals(value,e.getValue()); } public int hashCode() { int keyHash = (key==null ? 0 : key.hashCode()); int valueHash = (value==null ? 0 : value.hashCode()); return keyHash ^ valueHash; } public String toString() { return key + "=" + value; } } /** {@collect.stats} * {@description.open} * Returns the first Entry in the TreeMap (according to the TreeMap's * key-sort function). Returns null if the TreeMap is empty. * {@description.close} */ final Entry<K,V> getFirstEntry() { Entry<K,V> p = root; if (p != null) while (p.left != null) p = p.left; return p; } /** {@collect.stats} * {@description.open} * Returns the last Entry in the TreeMap (according to the TreeMap's * key-sort function). Returns null if the TreeMap is empty. * {@description.close} */ final Entry<K,V> getLastEntry() { Entry<K,V> p = root; if (p != null) while (p.right != null) p = p.right; return p; } /** {@collect.stats} * {@description.open} * Returns the successor of the specified Entry, or null if no such. * {@description.close} */ static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) { if (t == null) return null; else if (t.right != null) { Entry<K,V> p = t.right; while (p.left != null) p = p.left; return p; } else { Entry<K,V> p = t.parent; Entry<K,V> ch = t; while (p != null && ch == p.right) { ch = p; p = p.parent; } return p; } } /** {@collect.stats} * {@description.open} * Returns the predecessor of the specified Entry, or null if no such. * {@description.close} */ static <K,V> Entry<K,V> predecessor(Entry<K,V> t) { if (t == null) return null; else if (t.left != null) { Entry<K,V> p = t.left; while (p.right != null) p = p.right; return p; } else { Entry<K,V> p = t.parent; Entry<K,V> ch = t; while (p != null && ch == p.left) { ch = p; p = p.parent; } return p; } } /** {@collect.stats} * {@description.open} * Balancing operations. * * Implementations of rebalancings during insertion and deletion are * slightly different than the CLR version. Rather than using dummy * nilnodes, we use a set of accessors that deal properly with null. They * are used to avoid messiness surrounding nullness checks in the main * algorithms. * {@description.close} */ private static <K,V> boolean colorOf(Entry<K,V> p) { return (p == null ? BLACK : p.color); } private static <K,V> Entry<K,V> parentOf(Entry<K,V> p) { return (p == null ? null: p.parent); } private static <K,V> void setColor(Entry<K,V> p, boolean c) { if (p != null) p.color = c; } private static <K,V> Entry<K,V> leftOf(Entry<K,V> p) { return (p == null) ? null: p.left; } private static <K,V> Entry<K,V> rightOf(Entry<K,V> p) { return (p == null) ? null: p.right; } /** {@collect.stats} * {@description.open} * From CLR * {@description.close} */ private void rotateLeft(Entry<K,V> p) { if (p != null) { Entry<K,V> r = p.right; p.right = r.left; if (r.left != null) r.left.parent = p; r.parent = p.parent; if (p.parent == null) root = r; else if (p.parent.left == p) p.parent.left = r; else p.parent.right = r; r.left = p; p.parent = r; } } /** {@collect.stats} * {@description.open} * From CLR * {@description.close} */ private void rotateRight(Entry<K,V> p) { if (p != null) { Entry<K,V> l = p.left; p.left = l.right; if (l.right != null) l.right.parent = p; l.parent = p.parent; if (p.parent == null) root = l; else if (p.parent.right == p) p.parent.right = l; else p.parent.left = l; l.right = p; p.parent = l; } } /** {@collect.stats} * {@description.open} * From CLR * {@description.close} */ private void fixAfterInsertion(Entry<K,V> x) { x.color = RED; while (x != null && x != root && x.parent.color == RED) { if (parentOf(x) == leftOf(parentOf(parentOf(x)))) { Entry<K,V> y = rightOf(parentOf(parentOf(x))); if (colorOf(y) == RED) { setColor(parentOf(x), BLACK); setColor(y, BLACK); setColor(parentOf(parentOf(x)), RED); x = parentOf(parentOf(x)); } else { if (x == rightOf(parentOf(x))) { x = parentOf(x); rotateLeft(x); } setColor(parentOf(x), BLACK); setColor(parentOf(parentOf(x)), RED); rotateRight(parentOf(parentOf(x))); } } else { Entry<K,V> y = leftOf(parentOf(parentOf(x))); if (colorOf(y) == RED) { setColor(parentOf(x), BLACK); setColor(y, BLACK); setColor(parentOf(parentOf(x)), RED); x = parentOf(parentOf(x)); } else { if (x == leftOf(parentOf(x))) { x = parentOf(x); rotateRight(x); } setColor(parentOf(x), BLACK); setColor(parentOf(parentOf(x)), RED); rotateLeft(parentOf(parentOf(x))); } } } root.color = BLACK; } /** {@collect.stats} * {@description.open} * Delete node p, and then rebalance the tree. * {@description.close} */ private void deleteEntry(Entry<K,V> p) { modCount++; size--; // If strictly internal, copy successor's element to p and then make p // point to successor. if (p.left != null && p.right != null) { Entry<K,V> s = successor (p); p.key = s.key; p.value = s.value; p = s; } // p has 2 children // Start fixup at replacement node, if it exists. Entry<K,V> replacement = (p.left != null ? p.left : p.right); if (replacement != null) { // Link replacement to parent replacement.parent = p.parent; if (p.parent == null) root = replacement; else if (p == p.parent.left) p.parent.left = replacement; else p.parent.right = replacement; // Null out links so they are OK to use by fixAfterDeletion. p.left = p.right = p.parent = null; // Fix replacement if (p.color == BLACK) fixAfterDeletion(replacement); } else if (p.parent == null) { // return if we are the only node. root = null; } else { // No children. Use self as phantom replacement and unlink. if (p.color == BLACK) fixAfterDeletion(p); if (p.parent != null) { if (p == p.parent.left) p.parent.left = null; else if (p == p.parent.right) p.parent.right = null; p.parent = null; } } } /** {@collect.stats} * {@description.open} * From CLR * {@description.close} */ private void fixAfterDeletion(Entry<K,V> x) { while (x != root && colorOf(x) == BLACK) { if (x == leftOf(parentOf(x))) { Entry<K,V> sib = rightOf(parentOf(x)); if (colorOf(sib) == RED) { setColor(sib, BLACK); setColor(parentOf(x), RED); rotateLeft(parentOf(x)); sib = rightOf(parentOf(x)); } if (colorOf(leftOf(sib)) == BLACK && colorOf(rightOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); } else { if (colorOf(rightOf(sib)) == BLACK) { setColor(leftOf(sib), BLACK); setColor(sib, RED); rotateRight(sib); sib = rightOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(rightOf(sib), BLACK); rotateLeft(parentOf(x)); x = root; } } else { // symmetric Entry<K,V> sib = leftOf(parentOf(x)); if (colorOf(sib) == RED) { setColor(sib, BLACK); setColor(parentOf(x), RED); rotateRight(parentOf(x)); sib = leftOf(parentOf(x)); } if (colorOf(rightOf(sib)) == BLACK && colorOf(leftOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); } else { if (colorOf(leftOf(sib)) == BLACK) { setColor(rightOf(sib), BLACK); setColor(sib, RED); rotateLeft(sib); sib = leftOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(leftOf(sib), BLACK); rotateRight(parentOf(x)); x = root; } } } setColor(x, BLACK); } private static final long serialVersionUID = 919286545866124006L; /** {@collect.stats} * {@description.open} * Save the state of the <tt>TreeMap</tt> instance to a stream (i.e., * serialize it). * {@description.close} * * @serialData The <i>size</i> of the TreeMap (the number of key-value * mappings) is emitted (int), followed by the key (Object) * and value (Object) for each key-value mapping represented * by the TreeMap. The key-value mappings are emitted in * key-order (as determined by the TreeMap's Comparator, * or by the keys' natural ordering if the TreeMap has no * Comparator). */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out the Comparator and any hidden stuff s.defaultWriteObject(); // Write out size (number of Mappings) s.writeInt(size); // Write out keys and values (alternating) for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) { Map.Entry<K,V> e = i.next(); s.writeObject(e.getKey()); s.writeObject(e.getValue()); } } /** {@collect.stats} * {@description.open} * Reconstitute the <tt>TreeMap</tt> instance from a stream (i.e., * deserialize it). * {@description.close} */ private void readObject(final java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in the Comparator and any hidden stuff s.defaultReadObject(); // Read in size int size = s.readInt(); buildFromSorted(size, null, s, null); } /** {@collect.stats} * {@description.open} * Intended to be called only from TreeSet.readObject * {@description.close} */ void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal) throws java.io.IOException, ClassNotFoundException { buildFromSorted(size, null, s, defaultVal); } /** {@collect.stats} * {@description.open} * Intended to be called only from TreeSet.addAll * {@description.close} */ void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) { try { buildFromSorted(set.size(), set.iterator(), null, defaultVal); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } /** {@collect.stats} * {@description.open} * Linear time tree building algorithm from sorted data. Can accept keys * and/or values from iterator or stream. This leads to too many * parameters, but seems better than alternatives. The four formats * that this method accepts are: * * 1) An iterator of Map.Entries. (it != null, defaultVal == null). * 2) An iterator of keys. (it != null, defaultVal != null). * 3) A stream of alternating serialized keys and values. * (it == null, defaultVal == null). * 4) A stream of serialized keys. (it == null, defaultVal != null). * * It is assumed that the comparator of the TreeMap is already set prior * to calling this method. * {@description.close} * * @param size the number of keys (or key-value pairs) to be read from * the iterator or stream * @param it If non-null, new entries are created from entries * or keys read from this iterator. * @param str If non-null, new entries are created from keys and * possibly values read from this stream in serialized form. * Exactly one of it and str should be non-null. * @param defaultVal if non-null, this default value is used for * each value in the map. If null, each value is read from * iterator or stream, as described above. * @throws IOException propagated from stream reads. This cannot * occur if str is null. * @throws ClassNotFoundException propagated from readObject. * This cannot occur if str is null. */ private void buildFromSorted(int size, Iterator it, java.io.ObjectInputStream str, V defaultVal) throws java.io.IOException, ClassNotFoundException { this.size = size; root = buildFromSorted(0, 0, size-1, computeRedLevel(size), it, str, defaultVal); } /** {@collect.stats} * {@description.open} * Recursive "helper method" that does the real work of the * previous method. Identically named parameters have * identical definitions. Additional parameters are documented below. * It is assumed that the comparator and size fields of the TreeMap are * already set prior to calling this method. (It ignores both fields.) * {@description.close} * * @param level the current level of tree. Initial call should be 0. * @param lo the first element index of this subtree. Initial should be 0. * @param hi the last element index of this subtree. Initial should be * size-1. * @param redLevel the level at which nodes should be red. * Must be equal to computeRedLevel for tree of this size. */ private final Entry<K,V> buildFromSorted(int level, int lo, int hi, int redLevel, Iterator it, java.io.ObjectInputStream str, V defaultVal) throws java.io.IOException, ClassNotFoundException { /* * Strategy: The root is the middlemost element. To get to it, we * have to first recursively construct the entire left subtree, * so as to grab all of its elements. We can then proceed with right * subtree. * * The lo and hi arguments are the minimum and maximum * indices to pull out of the iterator or stream for current subtree. * They are not actually indexed, we just proceed sequentially, * ensuring that items are extracted in corresponding order. */ if (hi < lo) return null; int mid = (lo + hi) >>> 1; Entry<K,V> left = null; if (lo < mid) left = buildFromSorted(level+1, lo, mid - 1, redLevel, it, str, defaultVal); // extract key and/or value from iterator or stream K key; V value; if (it != null) { if (defaultVal==null) { Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next(); key = entry.getKey(); value = entry.getValue(); } else { key = (K)it.next(); value = defaultVal; } } else { // use stream key = (K) str.readObject(); value = (defaultVal != null ? defaultVal : (V) str.readObject()); } Entry<K,V> middle = new Entry<K,V>(key, value, null); // color nodes in non-full bottommost level red if (level == redLevel) middle.color = RED; if (left != null) { middle.left = left; left.parent = middle; } if (mid < hi) { Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel, it, str, defaultVal); middle.right = right; right.parent = middle; } return middle; } /** {@collect.stats} * {@description.open} * Find the level down to which to assign all nodes BLACK. This is the * last `full' level of the complete binary tree produced by * buildTree. The remaining nodes are colored RED. (This makes a `nice' * set of color assignments wrt future insertions.) This level number is * computed by finding the number of splits needed to reach the zeroeth * node. (The answer is ~lg(N), but in any case must be computed by same * quick O(lg(N)) loop.) * {@description.close} */ private static int computeRedLevel(int sz) { int level = 0; for (int m = sz - 1; m >= 0; m = m / 2 - 1) level++; return level; } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * This class provides a skeletal implementation of the <tt>Collection</tt> * interface, to minimize the effort required to implement this interface. <p> * {@description.close} * * {@property.open unknown} * To implement an unmodifiable collection, the programmer needs only to * extend this class and provide implementations for the <tt>iterator</tt> and * <tt>size</tt> methods. (The iterator returned by the <tt>iterator</tt> * method must implement <tt>hasNext</tt> and <tt>next</tt>.)<p> * {@property.close} * * {@property.open unknown} * To implement a modifiable collection, the programmer must additionally * override this class's <tt>add</tt> method (which otherwise throws an * <tt>UnsupportedOperationException</tt>), and the iterator returned by the * <tt>iterator</tt> method must additionally implement its <tt>remove</tt> * method.<p> * {@property.close} * * {@property.open Property:java.util.Collection_StandardConstructors} * The programmer should generally provide a void (no argument) and * <tt>Collection</tt> constructor, as per the recommendation in the * <tt>Collection</tt> interface specification.<p> * {@property.close} * * {@description.open} * The documentation for each non-abstract method in this class describes its * implementation in detail. Each of these methods may be overridden if * the collection being implemented admits a more efficient implementation.<p> * * This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @author Neal Gafter * @see Collection * @since 1.2 */ public abstract class AbstractCollection<E> implements Collection<E> { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ protected AbstractCollection() { } // Query Operations /** {@collect.stats} * {@description.open} * Returns an iterator over the elements contained in this collection. * {@description.close} * * @return an iterator over the elements contained in this collection */ public abstract Iterator<E> iterator(); public abstract int size(); /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation returns <tt>size() == 0</tt>. * {@description.close} */ public boolean isEmpty() { return size() == 0; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over the elements in the collection, * checking each element in turn for equality with the specified element. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public boolean contains(Object o) { Iterator<E> e = iterator(); if (o==null) { while (e.hasNext()) if (e.next()==null) return true; } else { while (e.hasNext()) if (o.equals(e.next())) return true; } return false; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation returns an array containing all the elements * returned by this collection's iterator, in the same order, stored in * consecutive elements of the array, starting with index {@code 0}. * The length of the returned array is equal to the number of elements * returned by the iterator, even if the size of this collection changes * during iteration, as might happen if the collection permits * concurrent modification during iteration. The {@code size} method is * called only as an optimization hint; the correct result is returned * even if the iterator returns a different number of elements. * * <p>This method is equivalent to: * * <pre> {@code * List<E> list = new ArrayList<E>(size()); * for (E e : this) * list.add(e); * return list.toArray(); * }</pre> * {@description.close} */ public Object[] toArray() { // Estimate size of array; be prepared to see more or fewer elements Object[] r = new Object[size()]; Iterator<E> it = iterator(); for (int i = 0; i < r.length; i++) { if (! it.hasNext()) // fewer elements than expected return Arrays.copyOf(r, i); r[i] = it.next(); } return it.hasNext() ? finishToArray(r, it) : r; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation returns an array containing all the elements * returned by this collection's iterator in the same order, stored in * consecutive elements of the array, starting with index {@code 0}. * If the number of elements returned by the iterator is too large to * fit into the specified array, then the elements are returned in a * newly allocated array with length equal to the number of elements * returned by the iterator, even if the size of this collection * changes during iteration, as might happen if the collection permits * concurrent modification during iteration. The {@code size} method is * called only as an optimization hint; the correct result is returned * even if the iterator returns a different number of elements. * * <p>This method is equivalent to: * * <pre> {@code * List<E> list = new ArrayList<E>(size()); * for (E e : this) * list.add(e); * return list.toArray(a); * }</pre> * {@description.close} * * @throws ArrayStoreException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public <T> T[] toArray(T[] a) { // Estimate size of array; be prepared to see more or fewer elements int size = size(); T[] r = a.length >= size ? a : (T[])java.lang.reflect.Array .newInstance(a.getClass().getComponentType(), size); Iterator<E> it = iterator(); for (int i = 0; i < r.length; i++) { if (! it.hasNext()) { // fewer elements than expected if (a != r) return Arrays.copyOf(r, i); r[i] = null; // null-terminate return r; } r[i] = (T)it.next(); } return it.hasNext() ? finishToArray(r, it) : r; } /** {@collect.stats} * {@description.open} * Reallocates the array being used within toArray when the iterator * returned more elements than expected, and finishes filling it from * the iterator. * {@description.close} * * @param r the array, replete with previously stored elements * @param it the in-progress iterator over this collection * @return array containing the elements in the given array, plus any * further elements returned by the iterator, trimmed to size */ private static <T> T[] finishToArray(T[] r, Iterator<?> it) { int i = r.length; while (it.hasNext()) { int cap = r.length; if (i == cap) { int newCap = ((cap / 2) + 1) * 3; if (newCap <= cap) { // integer overflow if (cap == Integer.MAX_VALUE) throw new OutOfMemoryError ("Required array size too large"); newCap = Integer.MAX_VALUE; } r = Arrays.copyOf(r, newCap); } r[i++] = (T)it.next(); } // trim if overallocated return (i == r.length) ? r : Arrays.copyOf(r, i); } // Modification Operations /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation always throws an * <tt>UnsupportedOperationException</tt>. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} */ public boolean add(E e) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over the collection looking for the * specified element. If it finds the element, it removes the element * from the collection using the iterator's remove method. * * <p>Note that this implementation throws an * <tt>UnsupportedOperationException</tt> if the iterator returned by this * collection's iterator method does not implement the <tt>remove</tt> * method and this collection contains the specified object. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public boolean remove(Object o) { Iterator<E> e = iterator(); if (o==null) { while (e.hasNext()) { if (e.next()==null) { e.remove(); return true; } } } else { while (e.hasNext()) { if (o.equals(e.next())) { e.remove(); return true; } } } return false; } // Bulk Operations /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over the specified collection, * checking each element returned by the iterator in turn to see * if it's contained in this collection. If all elements are so * contained <tt>true</tt> is returned, otherwise <tt>false</tt>. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @see #contains(Object) */ public boolean containsAll(Collection<?> c) { Iterator<?> e = c.iterator(); while (e.hasNext()) if (!contains(e.next())) return false; return true; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over the specified collection, and adds * each object returned by the iterator to this collection, in turn. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> unless <tt>add</tt> is * overridden (assuming the specified collection is non-empty). * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} * * @see #add(Object) */ public boolean addAll(Collection<? extends E> c) { boolean modified = false; Iterator<? extends E> e = c.iterator(); while (e.hasNext()) { if (add(e.next())) modified = true; } return modified; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over this collection, checking each * element returned by the iterator in turn to see if it's contained * in the specified collection. If it's so contained, it's removed from * this collection with the iterator's <tt>remove</tt> method. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> if the iterator returned by the * <tt>iterator</tt> method does not implement the <tt>remove</tt> method * and this collection contains one or more elements in common with the * specified collection. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * * @see #remove(Object) * @see #contains(Object) */ public boolean removeAll(Collection<?> c) { boolean modified = false; Iterator<?> e = iterator(); while (e.hasNext()) { if (c.contains(e.next())) { e.remove(); modified = true; } } return modified; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over this collection, checking each * element returned by the iterator in turn to see if it's contained * in the specified collection. If it's not so contained, it's removed * from this collection with the iterator's <tt>remove</tt> method. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> if the iterator returned by the * <tt>iterator</tt> method does not implement the <tt>remove</tt> method * and this collection contains one or more elements not present in the * specified collection. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * * @see #remove(Object) * @see #contains(Object) */ public boolean retainAll(Collection<?> c) { boolean modified = false; Iterator<E> e = iterator(); while (e.hasNext()) { if (!c.contains(e.next())) { e.remove(); modified = true; } } return modified; } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>This implementation iterates over this collection, removing each * element using the <tt>Iterator.remove</tt> operation. Most * implementations will probably choose to override this method for * efficiency. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> if the iterator returned by this * collection's <tt>iterator</tt> method does not implement the * <tt>remove</tt> method and this collection is non-empty. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} */ public void clear() { Iterator<E> e = iterator(); while (e.hasNext()) { e.next(); e.remove(); } } // String conversion /** {@collect.stats} * {@description.open} * Returns a string representation of this collection. The string * representation consists of a list of the collection's elements in the * order they are returned by its iterator, enclosed in square brackets * (<tt>"[]"</tt>). Adjacent elements are separated by the characters * <tt>", "</tt> (comma and space). Elements are converted to strings as * by {@link String#valueOf(Object)}. * {@description.close} * * @return a string representation of this collection */ public String toString() { Iterator<E> i = iterator(); if (! i.hasNext()) return "[]"; StringBuilder sb = new StringBuilder(); sb.append('['); for (;;) { E e = i.next(); sb.append(e == this ? "(this Collection)" : e); if (! i.hasNext()) return sb.append(']').toString(); sb.append(", "); } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * This exception may be thrown by methods that have detected concurrent * modification of an object when such modification is not permissible. * <p> * {@description.close} * {@property.open formal:java.util.Collection_UnsafeIterator} * For example, it is not generally permissible for one thread to modify a Collection * while another thread is iterating over it. In general, the results of the * iteration are undefined under these circumstances. Some Iterator * implementations (including those of all the general purpose collection implementations * provided by the JRE) may choose to throw this exception if this behavior is * detected. Iterators that do this are known as <i>fail-fast</i> iterators, * as they fail quickly and cleanly, rather that risking arbitrary, * non-deterministic behavior at an undetermined time in the future. * <p> * Note that this exception does not always indicate that an object has * been concurrently modified by a <i>different</i> thread. If a single * thread issues a sequence of method invocations that violates the * contract of an object, the object may throw this exception. For * example, if a thread modifies a collection directly while it is * iterating over the collection with a fail-fast iterator, the iterator * will throw this exception. * * <p>Note that fail-fast behavior cannot be guaranteed as it is, generally * speaking, impossible to make any hard guarantees in the presence of * unsynchronized concurrent modification. Fail-fast operations * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i><tt>ConcurrentModificationException</tt> * should be used only to detect bugs.</i> * {@property.close} * * @author Josh Bloch * @see Collection * @see Iterator * @see ListIterator * @see Vector * @see LinkedList * @see HashSet * @see Hashtable * @see TreeMap * @see AbstractList * @since 1.2 */ public class ConcurrentModificationException extends RuntimeException { /** {@collect.stats} * {@description.open} * Constructs a ConcurrentModificationException with no * detail message. * {@description.close} */ public ConcurrentModificationException() { } /** {@collect.stats} * {@description.open} * Constructs a <tt>ConcurrentModificationException</tt> with the * specified detail message. * {@description.close} * * @param message the detail message pertaining to this exception. */ public ConcurrentModificationException(String message) { super(message); } }
Java
/* * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.security.*; import java.io.IOException; import java.io.UnsupportedEncodingException; /** {@collect.stats} * {@description.open} * A class that represents an immutable universally unique identifier (UUID). * A UUID represents a 128-bit value. * * <p> There exist different variants of these global identifiers. The methods * of this class are for manipulating the Leach-Salz variant, although the * constructors allow the creation of any variant of UUID (described below). * * <p> The layout of a variant 2 (Leach-Salz) UUID is as follows: * * The most significant long consists of the following unsigned fields: * <pre> * 0xFFFFFFFF00000000 time_low * 0x00000000FFFF0000 time_mid * 0x000000000000F000 version * 0x0000000000000FFF time_hi * </pre> * The least significant long consists of the following unsigned fields: * <pre> * 0xC000000000000000 variant * 0x3FFF000000000000 clock_seq * 0x0000FFFFFFFFFFFF node * </pre> * * <p> The variant field contains a value which identifies the layout of the * {@code UUID}. The bit layout described above is valid only for a {@code * UUID} with a variant value of 2, which indicates the Leach-Salz variant. * * <p> The version field holds a value that describes the type of this {@code * UUID}. There are four different basic types of UUIDs: time-based, DCE * security, name-based, and randomly generated UUIDs. These types have a * version value of 1, 2, 3 and 4, respectively. * * <p> For more information including algorithms used to create {@code UUID}s, * see <a href="http://www.ietf.org/rfc/rfc4122.txt"> <i>RFC&nbsp;4122: A * Universally Unique IDentifier (UUID) URN Namespace</i></a>, section 4.2 * &quot;Algorithms for Creating a Time-Based UUID&quot;. * {@description.close} * * @since 1.5 */ public final class UUID implements java.io.Serializable, Comparable<UUID> { /** {@collect.stats} * {@description.open} * Explicit serialVersionUID for interoperability. * {@description.close} */ private static final long serialVersionUID = -4856846361193249489L; /* * The most significant 64 bits of this UUID. * * @serial */ private final long mostSigBits; /* * The least significant 64 bits of this UUID. * * @serial */ private final long leastSigBits; /* * The version number associated with this UUID. Computed on demand. */ private transient int version = -1; /* * The variant number associated with this UUID. Computed on demand. */ private transient int variant = -1; /* * The timestamp associated with this UUID. Computed on demand. */ private transient volatile long timestamp = -1; /* * The clock sequence associated with this UUID. Computed on demand. */ private transient int sequence = -1; /* * The node number associated with this UUID. Computed on demand. */ private transient long node = -1; /* * The hashcode of this UUID. Computed on demand. */ private transient int hashCode = -1; /* * The random number generator used by this class to create random * based UUIDs. */ private static volatile SecureRandom numberGenerator = null; // Constructors and Factories /* * Private constructor which uses a byte array to construct the new UUID. */ private UUID(byte[] data) { long msb = 0; long lsb = 0; assert data.length == 16; for (int i=0; i<8; i++) msb = (msb << 8) | (data[i] & 0xff); for (int i=8; i<16; i++) lsb = (lsb << 8) | (data[i] & 0xff); this.mostSigBits = msb; this.leastSigBits = lsb; } /** {@collect.stats} * {@description.open} * Constructs a new {@code UUID} using the specified data. {@code * mostSigBits} is used for the most significant 64 bits of the {@code * UUID} and {@code leastSigBits} becomes the least significant 64 bits of * the {@code UUID}. * {@description.close} * * @param mostSigBits * The most significant bits of the {@code UUID} * * @param leastSigBits * The least significant bits of the {@code UUID} */ public UUID(long mostSigBits, long leastSigBits) { this.mostSigBits = mostSigBits; this.leastSigBits = leastSigBits; } /** {@collect.stats} * {@description.open} * Static factory to retrieve a type 4 (pseudo randomly generated) UUID. * * The {@code UUID} is generated using a cryptographically strong pseudo * random number generator. * {@description.close} * * @return A randomly generated {@code UUID} */ public static UUID randomUUID() { SecureRandom ng = numberGenerator; if (ng == null) { numberGenerator = ng = new SecureRandom(); } byte[] randomBytes = new byte[16]; ng.nextBytes(randomBytes); randomBytes[6] &= 0x0f; /* clear version */ randomBytes[6] |= 0x40; /* set to version 4 */ randomBytes[8] &= 0x3f; /* clear variant */ randomBytes[8] |= 0x80; /* set to IETF variant */ return new UUID(randomBytes); } /** {@collect.stats} * {@description.open} * Static factory to retrieve a type 3 (name based) {@code UUID} based on * the specified byte array. * {@description.close} * * @param name * A byte array to be used to construct a {@code UUID} * * @return A {@code UUID} generated from the specified array */ public static UUID nameUUIDFromBytes(byte[] name) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { throw new InternalError("MD5 not supported"); } byte[] md5Bytes = md.digest(name); md5Bytes[6] &= 0x0f; /* clear version */ md5Bytes[6] |= 0x30; /* set to version 3 */ md5Bytes[8] &= 0x3f; /* clear variant */ md5Bytes[8] |= 0x80; /* set to IETF variant */ return new UUID(md5Bytes); } /** {@collect.stats} * {@description.open} * Creates a {@code UUID} from the string standard representation as * described in the {@link #toString} method. * {@description.close} * * @param name * A string that specifies a {@code UUID} * * @return A {@code UUID} with the specified value * * @throws IllegalArgumentException * If name does not conform to the string representation as * described in {@link #toString} * */ public static UUID fromString(String name) { String[] components = name.split("-"); if (components.length != 5) throw new IllegalArgumentException("Invalid UUID string: "+name); for (int i=0; i<5; i++) components[i] = "0x"+components[i]; long mostSigBits = Long.decode(components[0]).longValue(); mostSigBits <<= 16; mostSigBits |= Long.decode(components[1]).longValue(); mostSigBits <<= 16; mostSigBits |= Long.decode(components[2]).longValue(); long leastSigBits = Long.decode(components[3]).longValue(); leastSigBits <<= 48; leastSigBits |= Long.decode(components[4]).longValue(); return new UUID(mostSigBits, leastSigBits); } // Field Accessor Methods /** {@collect.stats} * {@description.open} * Returns the least significant 64 bits of this UUID's 128 bit value. * {@description.close} * * @return The least significant 64 bits of this UUID's 128 bit value */ public long getLeastSignificantBits() { return leastSigBits; } /** {@collect.stats} * {@description.open} * Returns the most significant 64 bits of this UUID's 128 bit value. * {@description.close} * * @return The most significant 64 bits of this UUID's 128 bit value */ public long getMostSignificantBits() { return mostSigBits; } /** {@collect.stats} * {@description.open} * The version number associated with this {@code UUID}. The version * number describes how this {@code UUID} was generated. * * The version number has the following meaning: * <p><ul> * <li>1 Time-based UUID * <li>2 DCE security UUID * <li>3 Name-based UUID * <li>4 Randomly generated UUID * </ul> * {@description.close} * * @return The version number of this {@code UUID} */ public int version() { if (version < 0) { // Version is bits masked by 0x000000000000F000 in MS long version = (int)((mostSigBits >> 12) & 0x0f); } return version; } /** {@collect.stats} * {@description.open} * The variant number associated with this {@code UUID}. The variant * number describes the layout of the {@code UUID}. * * The variant number has the following meaning: * <p><ul> * <li>0 Reserved for NCS backward compatibility * <li>2 The Leach-Salz variant (used by this class) * <li>6 Reserved, Microsoft Corporation backward compatibility * <li>7 Reserved for future definition * </ul> * {@description.close} * * @return The variant number of this {@code UUID} */ public int variant() { if (variant < 0) { // This field is composed of a varying number of bits if ((leastSigBits >>> 63) == 0) { variant = 0; } else if ((leastSigBits >>> 62) == 2) { variant = 2; } else { variant = (int)(leastSigBits >>> 61); } } return variant; } /** {@collect.stats} * {@description.open} * The timestamp value associated with this UUID. * * <p> The 60 bit timestamp value is constructed from the time_low, * time_mid, and time_hi fields of this {@code UUID}. The resulting * timestamp is measured in 100-nanosecond units since midnight, * October 15, 1582 UTC. * * <p> The timestamp value is only meaningful in a time-based UUID, which * has version type 1. If this {@code UUID} is not a time-based UUID then * this method throws UnsupportedOperationException. * {@description.close} * * @throws UnsupportedOperationException * If this UUID is not a version 1 UUID */ public long timestamp() { if (version() != 1) { throw new UnsupportedOperationException("Not a time-based UUID"); } long result = timestamp; if (result < 0) { result = (mostSigBits & 0x0000000000000FFFL) << 48; result |= ((mostSigBits >> 16) & 0xFFFFL) << 32; result |= mostSigBits >>> 32; timestamp = result; } return result; } /** {@collect.stats} * {@description.open} * The clock sequence value associated with this UUID. * * <p> The 14 bit clock sequence value is constructed from the clock * sequence field of this UUID. The clock sequence field is used to * guarantee temporal uniqueness in a time-based UUID. * * <p> The {@code clockSequence} value is only meaningful in a time-based * UUID, which has version type 1. If this UUID is not a time-based UUID * then this method throws UnsupportedOperationException. * {@description.close} * * @return The clock sequence of this {@code UUID} * * @throws UnsupportedOperationException * If this UUID is not a version 1 UUID */ public int clockSequence() { if (version() != 1) { throw new UnsupportedOperationException("Not a time-based UUID"); } if (sequence < 0) { sequence = (int)((leastSigBits & 0x3FFF000000000000L) >>> 48); } return sequence; } /** {@collect.stats} * {@description.open} * The node value associated with this UUID. * * <p> The 48 bit node value is constructed from the node field of this * UUID. This field is intended to hold the IEEE 802 address of the machine * that generated this UUID to guarantee spatial uniqueness. * * <p> The node value is only meaningful in a time-based UUID, which has * version type 1. If this UUID is not a time-based UUID then this method * throws UnsupportedOperationException. * {@description.close} * * @return The node value of this {@code UUID} * * @throws UnsupportedOperationException * If this UUID is not a version 1 UUID */ public long node() { if (version() != 1) { throw new UnsupportedOperationException("Not a time-based UUID"); } if (node < 0) { node = leastSigBits & 0x0000FFFFFFFFFFFFL; } return node; } // Object Inherited Methods /** {@collect.stats} * {@description.open} * Returns a {@code String} object representing this {@code UUID}. * * <p> The UUID string representation is as described by this BNF: * <blockquote><pre> * {@code * UUID = <time_low> "-" <time_mid> "-" * <time_high_and_version> "-" * <variant_and_sequence> "-" * <node> * time_low = 4*<hexOctet> * time_mid = 2*<hexOctet> * time_high_and_version = 2*<hexOctet> * variant_and_sequence = 2*<hexOctet> * node = 6*<hexOctet> * hexOctet = <hexDigit><hexDigit> * hexDigit = * "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" * | "a" | "b" | "c" | "d" | "e" | "f" * | "A" | "B" | "C" | "D" | "E" | "F" * }</pre></blockquote> * {@description.close} * * @return A string representation of this {@code UUID} */ public String toString() { return (digits(mostSigBits >> 32, 8) + "-" + digits(mostSigBits >> 16, 4) + "-" + digits(mostSigBits, 4) + "-" + digits(leastSigBits >> 48, 4) + "-" + digits(leastSigBits, 12)); } /** {@collect.stats} * {@description.open} * Returns val represented by the specified number of hex digits. * {@description.close} */ private static String digits(long val, int digits) { long hi = 1L << (digits * 4); return Long.toHexString(hi | (val & (hi - 1))).substring(1); } /** {@collect.stats} * {@description.open} * Returns a hash code for this {@code UUID}. * {@description.close} * * @return A hash code value for this {@code UUID} */ public int hashCode() { if (hashCode == -1) { hashCode = (int)((mostSigBits >> 32) ^ mostSigBits ^ (leastSigBits >> 32) ^ leastSigBits); } return hashCode; } /** {@collect.stats} * {@description.open} * Compares this object to the specified object. The result is {@code * true} if and only if the argument is not {@code null}, is a {@code UUID} * object, has the same variant, and contains the same value, bit for bit, * as this {@code UUID}. * {@description.close} * * @param obj * The object to be compared * * @return {@code true} if the objects are the same; {@code false} * otherwise */ public boolean equals(Object obj) { if (!(obj instanceof UUID)) return false; if (((UUID)obj).variant() != this.variant()) return false; UUID id = (UUID)obj; return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits); } // Comparison Operations /** {@collect.stats} * {@description.open} * Compares this UUID with the specified UUID. * * <p> The first of two UUIDs is greater than the second if the most * significant field in which the UUIDs differ is greater for the first * UUID. * {@description.close} * * @param val * {@code UUID} to which this {@code UUID} is to be compared * * @return -1, 0 or 1 as this {@code UUID} is less than, equal to, or * greater than {@code val} * */ public int compareTo(UUID val) { // The ordering is intentionally set up so that the UUIDs // can simply be numerically compared as two numbers return (this.mostSigBits < val.mostSigBits ? -1 : (this.mostSigBits > val.mostSigBits ? 1 : (this.leastSigBits < val.leastSigBits ? -1 : (this.leastSigBits > val.leastSigBits ? 1 : 0)))); } /** {@collect.stats} * {@description.open} * Reconstitute the {@code UUID} instance from a stream (that is, * deserialize it). This is necessary to set the transient fields to their * correct uninitialized value so they will be recomputed on demand. * {@description.close} */ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); // Set "cached computation" fields to their initial values version = -1; variant = -1; timestamp = -1; sequence = -1; node = -1; hashCode = -1; } }
Java
/* * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.IOException; /** {@collect.stats} * {@description.open} * The <tt>Formattable</tt> interface must be implemented by any class that * needs to perform custom formatting using the <tt>'s'</tt> conversion * specifier of {@link java.util.Formatter}. This interface allows basic * control for formatting arbitrary objects. * * For example, the following class prints out different representations of a * stock's name depending on the flags and length constraints: * * <blockquote><pre> * import java.nio.CharBuffer; * import java.util.Formatter; * import java.util.Formattable; * import java.util.Locale; * import static java.util.FormattableFlags.*; * * ... * * public class StockName implements Formattable { * private String symbol, companyName, frenchCompanyName; * public StockName(String symbol, String companyName, * String frenchCompanyName) { * ... * } * * ... * * public void formatTo(Formatter fmt, int f, int width, int precision) { * StringBuilder sb = new StringBuilder(); * * // decide form of name * String name = companyName; * if (fmt.locale().equals(Locale.FRANCE)) * name = frenchCompanyName; * boolean alternate = (f & ALTERNATE) == ALTERNATE; * boolean usesymbol = alternate || (precision != -1 && precision < 10); * String out = (usesymbol ? symbol : name); * * // apply precision * if (precision == -1 || out.length() < precision) { * // write it all * sb.append(out); * } else { * sb.append(out.substring(0, precision - 1)).append('*'); * } * * // apply width and justification * int len = sb.length(); * if (len < width) * for (int i = 0; i < width - len; i++) * if ((f & LEFT_JUSTIFY) == LEFT_JUSTIFY) * sb.append(' '); * else * sb.insert(0, ' '); * * fmt.format(sb.toString()); * } * * public String toString() { * return String.format("%s - %s", symbol, companyName); * } * } * </pre></blockquote> * * <p> When used in conjunction with the {@link java.util.Formatter}, the above * class produces the following output for various format strings. * * <blockquote><pre> * Formatter fmt = new Formatter(); * StockName sn = new StockName("HUGE", "Huge Fruit, Inc.", * "Fruit Titanesque, Inc."); * fmt.format("%s", sn); // -> "Huge Fruit, Inc." * fmt.format("%s", sn.toString()); // -> "HUGE - Huge Fruit, Inc." * fmt.format("%#s", sn); // -> "HUGE" * fmt.format("%-10.8s", sn); // -> "HUGE " * fmt.format("%.12s", sn); // -> "Huge Fruit,*" * fmt.format(Locale.FRANCE, "%25s", sn); // -> " Fruit Titanesque, Inc." * </pre></blockquote> * * <p> Formattables are not necessarily safe for multithreaded access. Thread * safety is optional and may be enforced by classes that extend and implement * this interface. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to * any method in this interface will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @since 1.5 */ public interface Formattable { /** {@collect.stats} * {@description.open} * Formats the object using the provided {@link Formatter formatter}. * {@description.close} * * @param formatter * The {@link Formatter formatter}. Implementing classes may call * {@link Formatter#out() formatter.out()} or {@link * Formatter#locale() formatter.locale()} to obtain the {@link * Appendable} or {@link Locale} used by this * <tt>formatter</tt> respectively. * * @param flags * The flags modify the output format. The value is interpreted as * a bitmask. Any combination of the following flags may be set: * {@link FormattableFlags#LEFT_JUSTIFY}, {@link * FormattableFlags#UPPERCASE}, and {@link * FormattableFlags#ALTERNATE}. If no flags are set, the default * formatting of the implementing class will apply. * * @param width * The minimum number of characters to be written to the output. * If the length of the converted value is less than the * <tt>width</tt> then the output will be padded by * <tt>'&nbsp;&nbsp;'</tt> until the total number of characters * equals width. The padding is at the beginning by default. If * the {@link FormattableFlags#LEFT_JUSTIFY} flag is set then the * padding will be at the end. If <tt>width</tt> is <tt>-1</tt> * then there is no minimum. * * @param precision * The maximum number of characters to be written to the output. * The precision is applied before the width, thus the output will * be truncated to <tt>precision</tt> characters even if the * <tt>width</tt> is greater than the <tt>precision</tt>. If * <tt>precision</tt> is <tt>-1</tt> then there is no explicit * limit on the number of characters. * * @throws IllegalFormatException * If any of the parameters are invalid. For specification of all * possible formatting errors, see the <a * href="../util/Formatter.html#detail">Details</a> section of the * formatter class specification. */ void formatTo(Formatter formatter, int flags, int width, int precision); }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.FilterInputStream; import java.io.InputStream; import java.io.IOException; import java.io.EOFException; /** {@collect.stats} * {@description.open} * This class implements a stream filter for uncompressing data in the * "deflate" compression format. It is also used as the basis for other * decompression filters, such as GZIPInputStream. * {@description.close} * * @see Inflater * @author David Connelly */ public class InflaterInputStream extends FilterInputStream { /** {@collect.stats} * {@description.open} * Decompressor for this stream. * {@description.close} */ protected Inflater inf; /** {@collect.stats} * {@description.open} * Input buffer for decompression. * {@description.close} */ protected byte[] buf; /** {@collect.stats} * {@description.open} * Length of input buffer. * {@description.close} */ protected int len; private boolean closed = false; // this flag is set to true after EOF has reached private boolean reachEOF = false; /** {@collect.stats} * {@description.open} * Check to make sure that this stream has not been closed * {@description.close} */ private void ensureOpen() throws IOException { if (closed) { throw new IOException("Stream closed"); } } /** {@collect.stats} * {@description.open} * Creates a new input stream with the specified decompressor and * buffer size. * {@description.close} * @param in the input stream * @param inf the decompressor ("inflater") * @param size the input buffer size * @exception IllegalArgumentException if size is <= 0 */ public InflaterInputStream(InputStream in, Inflater inf, int size) { super(in); if (in == null || inf == null) { throw new NullPointerException(); } else if (size <= 0) { throw new IllegalArgumentException("buffer size <= 0"); } this.inf = inf; buf = new byte[size]; } /** {@collect.stats} * {@description.open} * Creates a new input stream with the specified decompressor and a * default buffer size. * {@description.close} * @param in the input stream * @param inf the decompressor ("inflater") */ public InflaterInputStream(InputStream in, Inflater inf) { this(in, inf, 512); } boolean usesDefaultInflater = false; /** {@collect.stats} * {@description.open} * Creates a new input stream with a default decompressor and buffer size. * {@description.close} * @param in the input stream */ public InflaterInputStream(InputStream in) { this(in, new Inflater()); usesDefaultInflater = true; } private byte[] singleByteBuf = new byte[1]; /** {@collect.stats} * {@description.open} * Reads a byte of uncompressed data. This method will block until * enough input is available for decompression. * {@description.close} * @return the byte read, or -1 if end of compressed input is reached * @exception IOException if an I/O error has occurred */ public int read() throws IOException { ensureOpen(); return read(singleByteBuf, 0, 1) == -1 ? -1 : singleByteBuf[0] & 0xff; } /** {@collect.stats} * {@description.open} * Reads uncompressed data into an array of bytes. If <code>len</code> is not * zero, the method will block until some input can be decompressed; otherwise, * no bytes are read and <code>0</code> is returned. * {@description.close} * @param b the buffer into which the data is read * @param off the start offset in the destination array <code>b</code> * @param len the maximum number of bytes read * @return the actual number of bytes read, or -1 if the end of the * compressed input is reached or a preset dictionary is needed * @exception NullPointerException If <code>b</code> is <code>null</code>. * @exception IndexOutOfBoundsException If <code>off</code> is negative, * <code>len</code> is negative, or <code>len</code> is greater than * <code>b.length - off</code> * @exception ZipException if a ZIP format error has occurred * @exception IOException if an I/O error has occurred */ public int read(byte[] b, int off, int len) throws IOException { ensureOpen(); if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } try { int n; while ((n = inf.inflate(b, off, len)) == 0) { if (inf.finished() || inf.needsDictionary()) { reachEOF = true; return -1; } if (inf.needsInput()) { fill(); } } return n; } catch (DataFormatException e) { String s = e.getMessage(); throw new ZipException(s != null ? s : "Invalid ZLIB data format"); } } /** {@collect.stats} * {@description.open} * Returns 0 after EOF has been reached, otherwise always return 1. * <p> * Programs should not count on this method to return the actual number * of bytes that could be read without blocking. * {@description.close} * * @return 1 before EOF and 0 after EOF. * @exception IOException if an I/O error occurs. * */ public int available() throws IOException { ensureOpen(); if (reachEOF) { return 0; } else { return 1; } } private byte[] b = new byte[512]; /** {@collect.stats} * {@description.open} * Skips specified number of bytes of uncompressed data. * {@description.close} * @param n the number of bytes to skip * @return the actual number of bytes skipped. * @exception IOException if an I/O error has occurred * @exception IllegalArgumentException if n < 0 */ public long skip(long n) throws IOException { if (n < 0) { throw new IllegalArgumentException("negative skip length"); } ensureOpen(); int max = (int)Math.min(n, Integer.MAX_VALUE); int total = 0; while (total < max) { int len = max - total; if (len > b.length) { len = b.length; } len = read(b, 0, len); if (len == -1) { reachEOF = true; break; } total += len; } return total; } /** {@collect.stats} * {@description.open} * Closes this input stream and releases any system resources associated * with the stream. * {@description.close} * @exception IOException if an I/O error has occurred */ public void close() throws IOException { if (!closed) { if (usesDefaultInflater) inf.end(); in.close(); closed = true; } } /** {@collect.stats} * {@description.open} * Fills input buffer with more data to decompress. * {@description.close} * @exception IOException if an I/O error has occurred */ protected void fill() throws IOException { ensureOpen(); len = in.read(buf, 0, buf.length); if (len == -1) { throw new EOFException("Unexpected end of ZLIB input stream"); } inf.setInput(buf, 0, len); } /** {@collect.stats} * {@description.open} * Tests if this input stream supports the <code>mark</code> and * <code>reset</code> methods. The <code>markSupported</code> * method of <code>InflaterInputStream</code> returns * <code>false</code>. * {@description.close} * * @return a <code>boolean</code> indicating if this stream type supports * the <code>mark</code> and <code>reset</code> methods. * @see java.io.InputStream#mark(int) * @see java.io.InputStream#reset() */ public boolean markSupported() { return false; } /** {@collect.stats} * {@description.open} * Marks the current position in this input stream. * {@description.close} * * {@property.open} * <p> The <code>mark</code> method of <code>InflaterInputStream</code> * does nothing. * {@property.close} * * @param readlimit the maximum limit of bytes that can be read before * the mark position becomes invalid. * @see java.io.InputStream#reset() */ public synchronized void mark(int readlimit) { } /** {@collect.stats} * {@description.open} * Repositions this stream to the position at the time the * <code>mark</code> method was last called on this input stream. * {@description.close} * * {@property.open} * <p> The method <code>reset</code> for class * <code>InflaterInputStream</code> does nothing except throw an * <code>IOException</code>. * {@property.close} * * @exception IOException if this method is invoked. * @see java.io.InputStream#mark(int) * @see java.io.IOException */ public synchronized void reset() throws IOException { throw new IOException("mark/reset not supported"); } }
Java
/* * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.FilterInputStream; import java.io.InputStream; import java.io.IOException; /** {@collect.stats} * {@description.open} * Implements an input stream filter for compressing data in the "deflate" * compression format. * {@description.close} * * @since 1.6 * @author David R Tribble (david@tribble.com) * * @see DeflaterOutputStream * @see InflaterOutputStream * @see InflaterInputStream */ public class DeflaterInputStream extends FilterInputStream { /** {@collect.stats} * {@description.open} * Compressor for this stream. * {@description.close} */ protected final Deflater def; /** {@collect.stats} * {@description.open} * Input buffer for reading compressed data. * {@description.close} */ protected final byte[] buf; /** {@collect.stats} * {@description.open} * Temporary read buffer. * {@description.close} */ private byte[] rbuf = new byte[1]; /** {@collect.stats} * {@description.open} * Default compressor is used. * {@description.close} */ private boolean usesDefaultDeflater = false; /** {@collect.stats} * {@description.open} * End of the underlying input stream has been reached. * {@description.close} */ private boolean reachEOF = false; /** {@collect.stats} * {@description.open} * Check to make sure that this stream has not been closed. * {@description.close} */ private void ensureOpen() throws IOException { if (in == null) { throw new IOException("Stream closed"); } } /** {@collect.stats} * {@description.open} * Creates a new input stream with a default compressor and buffer * size. * {@description.close} * * @param in input stream to read the uncompressed data to * @throws NullPointerException if {@code in} is null */ public DeflaterInputStream(InputStream in) { this(in, new Deflater()); usesDefaultDeflater = true; } /** {@collect.stats} * {@description.open} * Creates a new input stream with the specified compressor and a * default buffer size. * {@description.close} * * @param in input stream to read the uncompressed data to * @param defl compressor ("deflater") for this stream * @throws NullPointerException if {@code in} or {@code defl} is null */ public DeflaterInputStream(InputStream in, Deflater defl) { this(in, defl, 512); } /** {@collect.stats} * {@description.open} * Creates a new input stream with the specified compressor and buffer * size. * {@description.close} * * @param in input stream to read the uncompressed data to * @param defl compressor ("deflater") for this stream * @param bufLen compression buffer size * @throws IllegalArgumentException if {@code bufLen} is <= 0 * @throws NullPointerException if {@code in} or {@code defl} is null */ public DeflaterInputStream(InputStream in, Deflater defl, int bufLen) { super(in); // Sanity checks if (in == null) throw new NullPointerException("Null input"); if (defl == null) throw new NullPointerException("Null deflater"); if (bufLen < 1) throw new IllegalArgumentException("Buffer size < 1"); // Initialize def = defl; buf = new byte[bufLen]; } /** {@collect.stats} * {@description.open} * Closes this input stream and its underlying input stream, discarding * any pending uncompressed data. * {@description.close} * * @throws IOException if an I/O error occurs */ public void close() throws IOException { if (in != null) { try { // Clean up if (usesDefaultDeflater) { def.end(); } in.close(); } finally { in = null; } } } /** {@collect.stats} * {@description.open} * Reads a single byte of compressed data from the input stream. * This method will block until some input can be read and compressed. * {@description.close} * * @return a single byte of compressed data, or -1 if the end of the * uncompressed input stream is reached * @throws IOException if an I/O error occurs or if this stream is * already closed */ public int read() throws IOException { // Read a single byte of compressed data int len = read(rbuf, 0, 1); if (len <= 0) return -1; return (rbuf[0] & 0xFF); } /** {@collect.stats} * {@description.open} * Reads compressed data into a byte array. * This method will block until some input can be read and compressed. * {@description.close} * * @param b buffer into which the data is read * @param off starting offset of the data within {@code b} * @param len maximum number of compressed bytes to read into {@code b} * @return the actual number of bytes read, or -1 if the end of the * uncompressed input stream is reached * @throws IndexOutOfBoundsException if {@code len} > {@code b.length - * off} * @throws IOException if an I/O error occurs or if this input stream is * already closed */ public int read(byte[] b, int off, int len) throws IOException { // Sanity checks ensureOpen(); if (b == null) { throw new NullPointerException("Null buffer for read"); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } // Read and compress (deflate) input data bytes int cnt = 0; while (len > 0 && !def.finished()) { int n; // Read data from the input stream if (def.needsInput()) { n = in.read(buf, 0, buf.length); if (n < 0) { // End of the input stream reached def.finish(); } else if (n > 0) { def.setInput(buf, 0, n); } } // Compress the input data, filling the read buffer n = def.deflate(b, off, len); cnt += n; off += n; len -= n; } if (cnt == 0 && def.finished()) { reachEOF = true; cnt = -1; } return cnt; } /** {@collect.stats} * {@description.open} * Skips over and discards data from the input stream. * This method may block until the specified number of bytes are read and * skipped. <em>Note:</em> While {@code n} is given as a {@code long}, * the maximum number of bytes which can be skipped is * {@code Integer.MAX_VALUE}. * {@description.close} * * @param n number of bytes to be skipped * @return the actual number of bytes skipped * @throws IOException if an I/O error occurs or if this stream is * already closed */ public long skip(long n) throws IOException { if (n < 0) { throw new IllegalArgumentException("negative skip length"); } ensureOpen(); // Skip bytes by repeatedly decompressing small blocks if (rbuf.length < 512) rbuf = new byte[512]; int total = (int)Math.min(n, Integer.MAX_VALUE); long cnt = 0; while (total > 0) { // Read a small block of uncompressed bytes int len = read(rbuf, 0, (total <= rbuf.length ? total : rbuf.length)); if (len < 0) { break; } cnt += len; total -= len; } return cnt; } /** {@collect.stats} * {@description.open} * Returns 0 after EOF has been reached, otherwise always return 1. * <p> * Programs should not count on this method to return the actual number * of bytes that could be read without blocking * {@description.close} * @return zero after the end of the underlying input stream has been * reached, otherwise always returns 1 * @throws IOException if an I/O error occurs or if this stream is * already closed */ public int available() throws IOException { ensureOpen(); if (reachEOF) { return 0; } return 1; } /** {@collect.stats} * {@description.open} * Always returns {@code false} because this input stream does not support * the {@link #mark mark()} and {@link #reset reset()} methods. * {@description.close} * * @return false, always */ public boolean markSupported() { return false; } /** {@collect.stats} * {@property.open} * <i>This operation is not supported</i>. * {@property.close} * * @param limit maximum bytes that can be read before invalidating the position marker */ public void mark(int limit) { // Operation not supported } /** {@collect.stats} * {@property.open} * <i>This operation is not supported</i>. * {@property.close} * * @throws IOException always thrown */ public void reset() throws IOException { throw new IOException("mark/reset not supported"); } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.SequenceInputStream; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.IOException; import java.io.EOFException; /** {@collect.stats} * {@description.open} * This class implements a stream filter for reading compressed data in * the GZIP file format. * {@description.close} * * @see InflaterInputStream * @author David Connelly * */ public class GZIPInputStream extends InflaterInputStream { /** {@collect.stats} * {@description.open} * CRC-32 for uncompressed data. * {@description.close} */ protected CRC32 crc = new CRC32(); /** {@collect.stats} * {@description.open} * Indicates end of input stream. * {@description.close} */ protected boolean eos; private boolean closed = false; /** {@collect.stats} * {@description.open} * Check to make sure that this stream has not been closed * {@description.close} */ private void ensureOpen() throws IOException { if (closed) { throw new IOException("Stream closed"); } } /** {@collect.stats} * {@description.open} * Creates a new input stream with the specified buffer size. * {@description.close} * @param in the input stream * @param size the input buffer size * @exception IOException if an I/O error has occurred * @exception IllegalArgumentException if size is <= 0 */ public GZIPInputStream(InputStream in, int size) throws IOException { super(in, new Inflater(true), size); usesDefaultInflater = true; readHeader(); crc.reset(); } /** {@collect.stats} * {@description.open} * Creates a new input stream with a default buffer size. * {@description.close} * @param in the input stream * @exception IOException if an I/O error has occurred */ public GZIPInputStream(InputStream in) throws IOException { this(in, 512); } /** {@collect.stats} * {@description.open} * Reads uncompressed data into an array of bytes. If <code>len</code> is not * zero, the method will block until some input can be decompressed; otherwise, * no bytes are read and <code>0</code> is returned. * {@description.close} * @param buf the buffer into which the data is read * @param off the start offset in the destination array <code>b</code> * @param len the maximum number of bytes read * @return the actual number of bytes read, or -1 if the end of the * compressed input stream is reached * @exception NullPointerException If <code>buf</code> is <code>null</code>. * @exception IndexOutOfBoundsException If <code>off</code> is negative, * <code>len</code> is negative, or <code>len</code> is greater than * <code>buf.length - off</code> * @exception IOException if an I/O error has occurred or the compressed * input data is corrupt */ public int read(byte[] buf, int off, int len) throws IOException { ensureOpen(); if (eos) { return -1; } len = super.read(buf, off, len); if (len == -1) { readTrailer(); eos = true; } else { crc.update(buf, off, len); } return len; } /** {@collect.stats} * {@description.open} * Closes this input stream and releases any system resources associated * with the stream. * {@description.close} * @exception IOException if an I/O error has occurred */ public void close() throws IOException { if (!closed) { super.close(); eos = true; closed = true; } } /** {@collect.stats} * {@description.open} * GZIP header magic number. * {@description.close} */ public final static int GZIP_MAGIC = 0x8b1f; /* * File header flags. */ private final static int FTEXT = 1; // Extra text private final static int FHCRC = 2; // Header CRC private final static int FEXTRA = 4; // Extra field private final static int FNAME = 8; // File name private final static int FCOMMENT = 16; // File comment /* * Reads GZIP member header. */ private void readHeader() throws IOException { CheckedInputStream in = new CheckedInputStream(this.in, crc); crc.reset(); // Check header magic if (readUShort(in) != GZIP_MAGIC) { throw new IOException("Not in GZIP format"); } // Check compression method if (readUByte(in) != 8) { throw new IOException("Unsupported compression method"); } // Read flags int flg = readUByte(in); // Skip MTIME, XFL, and OS fields skipBytes(in, 6); // Skip optional extra field if ((flg & FEXTRA) == FEXTRA) { skipBytes(in, readUShort(in)); } // Skip optional file name if ((flg & FNAME) == FNAME) { while (readUByte(in) != 0) ; } // Skip optional file comment if ((flg & FCOMMENT) == FCOMMENT) { while (readUByte(in) != 0) ; } // Check optional header CRC if ((flg & FHCRC) == FHCRC) { int v = (int)crc.getValue() & 0xffff; if (readUShort(in) != v) { throw new IOException("Corrupt GZIP header"); } } } /* * Reads GZIP member trailer. */ private void readTrailer() throws IOException { InputStream in = this.in; int n = inf.getRemaining(); if (n > 0) { in = new SequenceInputStream( new ByteArrayInputStream(buf, len - n, n), in); } // Uses left-to-right evaluation order if ((readUInt(in) != crc.getValue()) || // rfc1952; ISIZE is the input size modulo 2^32 (readUInt(in) != (inf.getBytesWritten() & 0xffffffffL))) throw new IOException("Corrupt GZIP trailer"); } /* * Reads unsigned integer in Intel byte order. */ private long readUInt(InputStream in) throws IOException { long s = readUShort(in); return ((long)readUShort(in) << 16) | s; } /* * Reads unsigned short in Intel byte order. */ private int readUShort(InputStream in) throws IOException { int b = readUByte(in); return ((int)readUByte(in) << 8) | b; } /* * Reads unsigned byte. */ private int readUByte(InputStream in) throws IOException { int b = in.read(); if (b == -1) { throw new EOFException(); } if (b < -1 || b > 255) { // Report on this.in, not argument in; see read{Header, Trailer}. throw new IOException(this.in.getClass().getName() + ".read() returned value out of range -1..255: " + b); } return b; } private byte[] tmpbuf = new byte[128]; /* * Skips bytes of input data blocking until all bytes are skipped. * Does not assume that the input stream is capable of seeking. */ private void skipBytes(InputStream in, int n) throws IOException { while (n > 0) { int len = in.read(tmpbuf, 0, n < tmpbuf.length ? n : tmpbuf.length); if (len == -1) { throw new EOFException(); } n -= len; } } }
Java
/* * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; /** {@collect.stats} * {@description.open} * A class that can be used to compute the CRC-32 of a data stream. * {@description.close} * * @see Checksum * @author David Connelly */ public class CRC32 implements Checksum { private int crc; /** {@collect.stats} * {@description.open} * Creates a new CRC32 object. * {@description.close} */ public CRC32() { } /** {@collect.stats} * {@description.open} * Updates CRC-32 with specified byte. * {@description.close} */ public void update(int b) { crc = update(crc, b); } /** {@collect.stats} * {@description.open} * Updates CRC-32 with specified array of bytes. * {@description.close} */ public void update(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } crc = updateBytes(crc, b, off, len); } /** {@collect.stats} * {@description.open} * Updates checksum with specified array of bytes. * {@description.close} * * @param b the array of bytes to update the checksum with */ public void update(byte[] b) { crc = updateBytes(crc, b, 0, b.length); } /** {@collect.stats} * {@description.open} * Resets CRC-32 to initial value. * {@description.close} */ public void reset() { crc = 0; } /** {@collect.stats} * {@description.open} * Returns CRC-32 value. * {@description.close} */ public long getValue() { return (long)crc & 0xffffffffL; } private native static int update(int crc, int b); private native static int updateBytes(int crc, byte[] b, int off, int len); }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.FilterOutputStream; import java.io.OutputStream; import java.io.InputStream; import java.io.IOException; /** {@collect.stats} * {@description.open} * This class implements an output stream filter for compressing data in * the "deflate" compression format. It is also used as the basis for other * types of compression filters, such as GZIPOutputStream. * {@description.close} * * @see Deflater * @author David Connelly */ public class DeflaterOutputStream extends FilterOutputStream { /** {@collect.stats} * {@description.open} * Compressor for this stream. * {@description.close} */ protected Deflater def; /** {@collect.stats} * {@description.open} * Output buffer for writing compressed data. * {@description.close} */ protected byte[] buf; /** {@collect.stats} * {@description.open} * Indicates that the stream has been closed. * {@description.close} */ private boolean closed = false; /** {@collect.stats} * {@description.open} * Creates a new output stream with the specified compressor and * buffer size. * {@description.close} * @param out the output stream * @param def the compressor ("deflater") * @param size the output buffer size * @exception IllegalArgumentException if size is <= 0 */ public DeflaterOutputStream(OutputStream out, Deflater def, int size) { super(out); if (out == null || def == null) { throw new NullPointerException(); } else if (size <= 0) { throw new IllegalArgumentException("buffer size <= 0"); } this.def = def; buf = new byte[size]; } /** {@collect.stats} * {@description.open} * Creates a new output stream with the specified compressor and * a default buffer size. * {@description.close} * @param out the output stream * @param def the compressor ("deflater") */ public DeflaterOutputStream(OutputStream out, Deflater def) { this(out, def, 512); } boolean usesDefaultDeflater = false; /** {@collect.stats} * {@description.open} * Creates a new output stream with a default compressor and buffer size. * {@description.close} * @param out the output stream */ public DeflaterOutputStream(OutputStream out) { this(out, new Deflater()); usesDefaultDeflater = true; } /** {@collect.stats} * {@description.open} * Writes a byte to the compressed output stream. This method will * block until the byte can be written. * {@description.close} * @param b the byte to be written * @exception IOException if an I/O error has occurred */ public void write(int b) throws IOException { byte[] buf = new byte[1]; buf[0] = (byte)(b & 0xff); write(buf, 0, 1); } /** {@collect.stats} * {@description.open} * Writes an array of bytes to the compressed output stream. This * method will block until all the bytes are written. * {@description.close} * @param b the data to be written * @param off the start offset of the data * @param len the length of the data * @exception IOException if an I/O error has occurred */ public void write(byte[] b, int off, int len) throws IOException { if (def.finished()) { throw new IOException("write beyond end of stream"); } if ((off | len | (off + len) | (b.length - (off + len))) < 0) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (!def.finished()) { // Deflate no more than stride bytes at a time. This avoids // excess copying in deflateBytes (see Deflater.c) int stride = buf.length; for (int i = 0; i < len; i+= stride) { def.setInput(b, off + i, Math.min(stride, len - i)); while (!def.needsInput()) { deflate(); } } } } /** {@collect.stats} * {@description.open} * Finishes writing compressed data to the output stream without closing * the underlying stream. * {@description.close} * {@property.open} * Use this method when applying multiple filters * in succession to the same output stream. * {@property.close} * @exception IOException if an I/O error has occurred */ public void finish() throws IOException { if (!def.finished()) { def.finish(); while (!def.finished()) { deflate(); } } } /** {@collect.stats} * {@description.open} * Writes remaining compressed data to the output stream and closes the * underlying stream. * {@description.close} * @exception IOException if an I/O error has occurred */ public void close() throws IOException { if (!closed) { finish(); if (usesDefaultDeflater) def.end(); out.close(); closed = true; } } /** {@collect.stats} * {@description.open} * Writes next block of compressed data to the output stream. * {@description.close} * @throws IOException if an I/O error has occurred */ protected void deflate() throws IOException { int len = def.deflate(buf, 0, buf.length); if (len > 0) { out.write(buf, 0, len); } } }
Java
/* * Copyright (c) 1996, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; /** {@collect.stats} * {@description.open} * Signals that a data format error has occurred. * {@description.close} * * @author David Connelly */ public class DataFormatException extends Exception { /** {@collect.stats} * {@description.open} * Constructs a DataFormatException with no detail message. * {@description.close} */ public DataFormatException() { super(); } /** {@collect.stats} * {@description.open} * Constructs a DataFormatException with the specified detail message. * A detail message is a String that describes this particular exception. * {@description.close} * @param s the String containing a detail message */ public DataFormatException(String s) { super(s); } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.FilterInputStream; import java.io.InputStream; import java.io.IOException; /** {@collect.stats} * {@description.open} * An input stream that also maintains a checksum of the data being read. * The checksum can then be used to verify the integrity of the input data. * {@description.close} * * @see Checksum * @author David Connelly */ public class CheckedInputStream extends FilterInputStream { private Checksum cksum; /** {@collect.stats} * {@description.open} * Creates an input stream using the specified Checksum. * {@description.close} * @param in the input stream * @param cksum the Checksum */ public CheckedInputStream(InputStream in, Checksum cksum) { super(in); this.cksum = cksum; } /** {@collect.stats} * {@description.open} * Reads a byte. Will block if no input is available. * {@description.close} * @return the byte read, or -1 if the end of the stream is reached. * @exception IOException if an I/O error has occurred */ public int read() throws IOException { int b = in.read(); if (b != -1) { cksum.update(b); } return b; } /** {@collect.stats} * {@description.open} * Reads into an array of bytes. If <code>len</code> is not zero, the method * blocks until some input is available; otherwise, no * bytes are read and <code>0</code> is returned. * {@description.close} * @param buf the buffer into which the data is read * @param off the start offset in the destination array <code>b</code> * @param len the maximum number of bytes read * @return the actual number of bytes read, or -1 if the end * of the stream is reached. * @exception NullPointerException If <code>buf</code> is <code>null</code>. * @exception IndexOutOfBoundsException If <code>off</code> is negative, * <code>len</code> is negative, or <code>len</code> is greater than * <code>buf.length - off</code> * @exception IOException if an I/O error has occurred */ public int read(byte[] buf, int off, int len) throws IOException { len = in.read(buf, off, len); if (len != -1) { cksum.update(buf, off, len); } return len; } /** {@collect.stats} * {@description.open} * Skips specified number of bytes of input. * {@description.close} * @param n the number of bytes to skip * @return the actual number of bytes skipped * @exception IOException if an I/O error has occurred */ public long skip(long n) throws IOException { byte[] buf = new byte[512]; long total = 0; while (total < n) { long len = n - total; len = read(buf, 0, len < buf.length ? (int)len : buf.length); if (len == -1) { return total; } total += len; } return total; } /** {@collect.stats} * {@description.open} * Returns the Checksum for this input stream. * {@description.close} * @return the Checksum value */ public Checksum getChecksum() { return cksum; } }
Java
/* * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; /** {@collect.stats} * {@description.open} * Signals that an unrecoverable error has occurred. * {@description.close} * * @author Dave Bristor * @since 1.6 */ public class ZipError extends InternalError { private static final long serialVersionUID = 853973422266861979L; /** {@collect.stats} * {@description.open} * Constructs a ZipError with the given detail message. * {@description.close} * @param s the {@code String} containing a detail message */ public ZipError(String s) { super(s); } }
Java
/* * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.InputStream; import java.io.IOException; import java.io.EOFException; import java.io.File; import java.util.Vector; import java.util.Enumeration; import java.util.NoSuchElementException; /** {@collect.stats} * {@description.open} * This class is used to read entries from a zip file. * * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor * or method in this class will cause a {@link NullPointerException} to be * thrown. * {@description.close} * * @author David Connelly */ public class ZipFile implements ZipConstants { private long jzfile; // address of jzfile data private String name; // zip file name private int total; // total number of entries private boolean closeRequested; private static final int STORED = ZipEntry.STORED; private static final int DEFLATED = ZipEntry.DEFLATED; /** {@collect.stats} * {@description.open} * Mode flag to open a zip file for reading. * {@description.close} */ public static final int OPEN_READ = 0x1; /** {@collect.stats} * {@description.open} * Mode flag to open a zip file and mark it for deletion. The file will be * deleted some time between the moment that it is opened and the moment * that it is closed, but its contents will remain accessible via the * <tt>ZipFile</tt> object until either the close method is invoked or the * virtual machine exits. * {@description.close} */ public static final int OPEN_DELETE = 0x4; static { /* Zip library is loaded from System.initializeSystemClass */ initIDs(); } private static native void initIDs(); /** {@collect.stats} * {@description.open} * Opens a zip file for reading. * * <p>First, if there is a security * manager, its <code>checkRead</code> method * is called with the <code>name</code> argument * as its argument to ensure the read is allowed. * {@description.close} * * @param name the name of the zip file * @throws ZipException if a ZIP format error has occurred * @throws IOException if an I/O error has occurred * @throws SecurityException if a security manager exists and its * <code>checkRead</code> method doesn't allow read access to the file. * @see SecurityManager#checkRead(java.lang.String) */ public ZipFile(String name) throws IOException { this(new File(name), OPEN_READ); } /** {@collect.stats} * {@description.open} * Opens a new <code>ZipFile</code> to read from the specified * <code>File</code> object in the specified mode. The mode argument * must be either <tt>OPEN_READ</tt> or <tt>OPEN_READ | OPEN_DELETE</tt>. * * <p>First, if there is a security manager, its <code>checkRead</code> * method is called with the <code>name</code> argument as its argument to * ensure the read is allowed. * {@description.close} * * @param file the ZIP file to be opened for reading * @param mode the mode in which the file is to be opened * @throws ZipException if a ZIP format error has occurred * @throws IOException if an I/O error has occurred * @throws SecurityException if a security manager exists and * its <code>checkRead</code> method * doesn't allow read access to the file, * or its <code>checkDelete</code> method doesn't allow deleting * the file when the <tt>OPEN_DELETE</tt> flag is set. * @throws IllegalArgumentException if the <tt>mode</tt> argument is invalid * @see SecurityManager#checkRead(java.lang.String) * @since 1.3 */ public ZipFile(File file, int mode) throws IOException { if (((mode & OPEN_READ) == 0) || ((mode & ~(OPEN_READ | OPEN_DELETE)) != 0)) { throw new IllegalArgumentException("Illegal mode: 0x"+ Integer.toHexString(mode)); } String name = file.getPath(); SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkRead(name); if ((mode & OPEN_DELETE) != 0) { sm.checkDelete(name); } } jzfile = open(name, mode, file.lastModified()); this.name = name; this.total = getTotal(jzfile); } private static native long open(String name, int mode, long lastModified); private static native int getTotal(long jzfile); /** {@collect.stats} * {@description.open} * Opens a ZIP file for reading given the specified File object. * {@description.close} * @param file the ZIP file to be opened for reading * @throws ZipException if a ZIP error has occurred * @throws IOException if an I/O error has occurred */ public ZipFile(File file) throws ZipException, IOException { this(file, OPEN_READ); } /** {@collect.stats} * {@description.open} * Returns the zip file entry for the specified name, or null * if not found. * {@description.close} * * @param name the name of the entry * @return the zip file entry, or null if not found * @throws IllegalStateException if the zip file has been closed */ public ZipEntry getEntry(String name) { if (name == null) { throw new NullPointerException("name"); } long jzentry = 0; synchronized (this) { ensureOpen(); jzentry = getEntry(jzfile, name, true); if (jzentry != 0) { ZipEntry ze = new ZipEntry(name, jzentry); freeEntry(jzfile, jzentry); return ze; } } return null; } private static native long getEntry(long jzfile, String name, boolean addSlash); // freeEntry releases the C jzentry struct. private static native void freeEntry(long jzfile, long jzentry); /** {@collect.stats} * {@description.open} * Returns an input stream for reading the contents of the specified * zip file entry. * {@description.close} * * {@property.open} * <p> Closing this ZIP file will, in turn, close all input * streams that have been returned by invocations of this method. * {@property.close} * * @param entry the zip file entry * @return the input stream for reading the contents of the specified * zip file entry. * @throws ZipException if a ZIP format error has occurred * @throws IOException if an I/O error has occurred * @throws IllegalStateException if the zip file has been closed */ public InputStream getInputStream(ZipEntry entry) throws IOException { return getInputStream(entry.name); } /** {@collect.stats} * {@description.open} * Returns an input stream for reading the contents of the specified * entry, or null if the entry was not found. * {@description.close} * {@property.open} * {@new.open} * <p> Closing this ZIP file will, in turn, close all input * streams that have been returned by invocations of this method. * {@new.close} * {@property.close} */ private InputStream getInputStream(String name) throws IOException { if (name == null) { throw new NullPointerException("name"); } long jzentry = 0; ZipFileInputStream in = null; synchronized (this) { ensureOpen(); jzentry = getEntry(jzfile, name, false); if (jzentry == 0) { return null; } in = new ZipFileInputStream(jzentry); } final ZipFileInputStream zfin = in; switch (getMethod(jzentry)) { case STORED: return zfin; case DEFLATED: // MORE: Compute good size for inflater stream: long size = getSize(jzentry) + 2; // Inflater likes a bit of slack if (size > 65536) size = 8192; if (size <= 0) size = 4096; return new InflaterInputStream(zfin, getInflater(), (int)size) { private boolean isClosed = false; public void close() throws IOException { if (!isClosed) { releaseInflater(inf); this.in.close(); isClosed = true; } } // Override fill() method to provide an extra "dummy" byte // at the end of the input stream. This is required when // using the "nowrap" Inflater option. protected void fill() throws IOException { if (eof) { throw new EOFException( "Unexpected end of ZLIB input stream"); } len = this.in.read(buf, 0, buf.length); if (len == -1) { buf[0] = 0; len = 1; eof = true; } inf.setInput(buf, 0, len); } private boolean eof; public int available() throws IOException { if (isClosed) return 0; long avail = zfin.size() - inf.getBytesWritten(); return avail > (long) Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) avail; } }; default: throw new ZipException("invalid compression method"); } } private static native int getMethod(long jzentry); /* * Gets an inflater from the list of available inflaters or allocates * a new one. */ private Inflater getInflater() { synchronized (inflaters) { int size = inflaters.size(); if (size > 0) { Inflater inf = (Inflater)inflaters.remove(size - 1); inf.reset(); return inf; } else { return new Inflater(true); } } } /* * Releases the specified inflater to the list of available inflaters. */ private void releaseInflater(Inflater inf) { synchronized (inflaters) { inflaters.add(inf); } } // List of available Inflater objects for decompression private Vector inflaters = new Vector(); /** {@collect.stats} * {@description.open} * Returns the path name of the ZIP file. * {@description.close} * @return the path name of the ZIP file */ public String getName() { return name; } /** {@collect.stats} * {@description.open} * Returns an enumeration of the ZIP file entries. * {@description.close} * @return an enumeration of the ZIP file entries * @throws IllegalStateException if the zip file has been closed */ public Enumeration<? extends ZipEntry> entries() { ensureOpen(); return new Enumeration<ZipEntry>() { private int i = 0; public boolean hasMoreElements() { synchronized (ZipFile.this) { ensureOpen(); return i < total; } } public ZipEntry nextElement() throws NoSuchElementException { synchronized (ZipFile.this) { ensureOpen(); if (i >= total) { throw new NoSuchElementException(); } long jzentry = getNextEntry(jzfile, i++); if (jzentry == 0) { String message; if (closeRequested) { message = "ZipFile concurrently closed"; } else { message = getZipMessage(ZipFile.this.jzfile); } throw new ZipError("jzentry == 0" + ",\n jzfile = " + ZipFile.this.jzfile + ",\n total = " + ZipFile.this.total + ",\n name = " + ZipFile.this.name + ",\n i = " + i + ",\n message = " + message ); } ZipEntry ze = new ZipEntry(jzentry); freeEntry(jzfile, jzentry); return ze; } } }; } private static native long getNextEntry(long jzfile, int i); /** {@collect.stats} * {@description.open} * Returns the number of entries in the ZIP file. * {@description.close} * @return the number of entries in the ZIP file * @throws IllegalStateException if the zip file has been closed */ public int size() { ensureOpen(); return total; } /** {@collect.stats} * {@description.open} * Closes the ZIP file. * <p> Closing this ZIP file will close all of the input streams * previously returned by invocations of the {@link #getInputStream * getInputStream} method. * {@description.close} * * @throws IOException if an I/O error has occurred */ public void close() throws IOException { synchronized (this) { closeRequested = true; if (jzfile != 0) { // Close the zip file long zf = this.jzfile; jzfile = 0; close(zf); // Release inflaters synchronized (inflaters) { int size = inflaters.size(); for (int i = 0; i < size; i++) { Inflater inf = (Inflater)inflaters.get(i); inf.end(); } } } } } /** {@collect.stats} * {@description.open} * Ensures that the <code>close</code> method of this ZIP file is * called when there are no more references to it. * * <p> * Since the time when GC would invoke this method is undetermined, * it is strongly recommended that applications invoke the <code>close</code> * method as soon they have finished accessing this <code>ZipFile</code>. * This will prevent holding up system resources for an undetermined * length of time. * {@description.close} * * @throws IOException if an I/O error has occurred * @see java.util.zip.ZipFile#close() */ protected void finalize() throws IOException { close(); } private static native void close(long jzfile); private void ensureOpen() { if (closeRequested) { throw new IllegalStateException("zip file closed"); } if (jzfile == 0) { throw new IllegalStateException("The object is not initialized."); } } private void ensureOpenOrZipException() throws IOException { if (closeRequested) { throw new ZipException("ZipFile closed"); } } /* * Inner class implementing the input stream used to read a * (possibly compressed) zip file entry. */ private class ZipFileInputStream extends InputStream { protected long jzentry; // address of jzentry data private long pos; // current position within entry data protected long rem; // number of remaining bytes within entry protected long size; // uncompressed size of this entry ZipFileInputStream(long jzentry) { pos = 0; rem = getCSize(jzentry); size = getSize(jzentry); this.jzentry = jzentry; } public int read(byte b[], int off, int len) throws IOException { if (rem == 0) { return -1; } if (len <= 0) { return 0; } if (len > rem) { len = (int) rem; } synchronized (ZipFile.this) { ensureOpenOrZipException(); len = ZipFile.read(ZipFile.this.jzfile, jzentry, pos, b, off, len); } if (len > 0) { pos += len; rem -= len; } if (rem == 0) { close(); } return len; } public int read() throws IOException { byte[] b = new byte[1]; if (read(b, 0, 1) == 1) { return b[0] & 0xff; } else { return -1; } } public long skip(long n) { if (n > rem) n = rem; pos += n; rem -= n; if (rem == 0) { close(); } return n; } public int available() { return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem; } public long size() { return size; } public void close() { rem = 0; synchronized (ZipFile.this) { if (jzentry != 0 && ZipFile.this.jzfile != 0) { freeEntry(ZipFile.this.jzfile, jzentry); jzentry = 0; } } } } private static native int read(long jzfile, long jzentry, long pos, byte[] b, int off, int len); private static native long getCSize(long jzentry); private static native long getSize(long jzentry); // Temporary add on for bug troubleshooting private static native String getZipMessage(long jzfile); }
Java
/* * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; /** {@collect.stats} * {@description.open} * This class provides support for general purpose decompression using the * popular ZLIB compression library. The ZLIB compression library was * initially developed as part of the PNG graphics standard and is not * protected by patents. It is fully described in the specifications at * the <a href="package-summary.html#package_description">java.util.zip * package description</a>. * * <p>The following code fragment demonstrates a trivial compression * and decompression of a string using <tt>Deflater</tt> and * <tt>Inflater</tt>. * * <blockquote><pre> * try { * // Encode a String into bytes * String inputString = "blahblahblah\u20AC\u20AC"; * byte[] input = inputString.getBytes("UTF-8"); * * // Compress the bytes * byte[] output = new byte[100]; * Deflater compresser = new Deflater(); * compresser.setInput(input); * compresser.finish(); * int compressedDataLength = compresser.deflate(output); * * // Decompress the bytes * Inflater decompresser = new Inflater(); * decompresser.setInput(output, 0, compressedDataLength); * byte[] result = new byte[100]; * int resultLength = decompresser.inflate(result); * decompresser.end(); * * // Decode the bytes into a String * String outputString = new String(result, 0, resultLength, "UTF-8"); * } catch(java.io.UnsupportedEncodingException ex) { * // handle * } catch (java.util.zip.DataFormatException ex) { * // handle * } * </pre></blockquote> * {@description.close} * * @see Deflater * @author David Connelly * */ public class Inflater { private final ZStreamRef zsRef; private byte[] buf = emptyBuf; private int off, len; private boolean finished; private boolean needDict; private static byte[] emptyBuf = new byte[0]; static { /* Zip library is loaded from System.initializeSystemClass */ initIDs(); } /** {@collect.stats} * {@description.open} * Creates a new decompressor. If the parameter 'nowrap' is true then * the ZLIB header and checksum fields will not be used. This provides * compatibility with the compression format used by both GZIP and PKZIP. * <p> * Note: When using the 'nowrap' option it is also necessary to provide * an extra "dummy" byte as input. This is required by the ZLIB native * library in order to support certain optimizations. * {@description.close} * * @param nowrap if true then support GZIP compatible compression */ public Inflater(boolean nowrap) { zsRef = new ZStreamRef(init(nowrap)); } /** {@collect.stats} * {@description.open} * Creates a new decompressor. * {@description.close} */ public Inflater() { this(false); } /** {@collect.stats} * {@description.open} * Sets input data for decompression. * {@description.close} * {@property.open} * Should be called whenever * needsInput() returns true indicating that more input data is * required. * {@property.close} * @param b the input data bytes * @param off the start offset of the input data * @param len the length of the input data * @see Inflater#needsInput */ public void setInput(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { this.buf = b; this.off = off; this.len = len; } } /** {@collect.stats} * {@description.open} * Sets input data for decompression. * {@description.close} * {@property.open} * Should be called whenever * needsInput() returns true indicating that more input data is * required. * {@property.close} * @param b the input data bytes * @see Inflater#needsInput */ public void setInput(byte[] b) { setInput(b, 0, b.length); } /** {@collect.stats} * {@description.open} * Sets the preset dictionary to the given array of bytes. * {@description.close} * {@property.open} * Should be * called when inflate() returns 0 and needsDictionary() returns true * indicating that a preset dictionary is required. * {@property.close} * {@description.open} * The method getAdler() * can be used to get the Adler-32 value of the dictionary needed. * {@description.close} * @param b the dictionary data bytes * @param off the start offset of the data * @param len the length of the data * @see Inflater#needsDictionary * @see Inflater#getAdler */ public void setDictionary(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { ensureOpen(); setDictionary(zsRef.address(), b, off, len); needDict = false; } } /** {@collect.stats} * {@description.open} * Sets the preset dictionary to the given array of bytes. * {@description.close} * {@property.open} * Should be * called when inflate() returns 0 and needsDictionary() returns true * indicating that a preset dictionary is required. * {@property.close} * {@description.open} * The method getAdler() * can be used to get the Adler-32 value of the dictionary needed. * {@description.close} * @param b the dictionary data bytes * @see Inflater#needsDictionary * @see Inflater#getAdler */ public void setDictionary(byte[] b) { setDictionary(b, 0, b.length); } /** {@collect.stats} * {@description.open} * Returns the total number of bytes remaining in the input buffer. * This can be used to find out what bytes still remain in the input * buffer after decompression has finished. * {@description.close} * @return the total number of bytes remaining in the input buffer */ public int getRemaining() { synchronized (zsRef) { return len; } } /** {@collect.stats} * {@description.open} * Returns true if no data remains in the input buffer. This can * be used to determine if #setInput should be called in order * to provide more input. * {@description.close} * @return true if no data remains in the input buffer */ public boolean needsInput() { synchronized (zsRef) { return len <= 0; } } /** {@collect.stats} * {@description.open} * Returns true if a preset dictionary is needed for decompression. * {@description.close} * @return true if a preset dictionary is needed for decompression * @see Inflater#setDictionary */ public boolean needsDictionary() { synchronized (zsRef) { return needDict; } } /** {@collect.stats} * {@description.open} * Returns true if the end of the compressed data stream has been * reached. * {@description.close} * @return true if the end of the compressed data stream has been * reached */ public boolean finished() { synchronized (zsRef) { return finished; } } /** {@collect.stats} * {@description.open} * Uncompresses bytes into specified buffer. Returns actual number * of bytes uncompressed. A return value of 0 indicates that * needsInput() or needsDictionary() should be called in order to * determine if more input data or a preset dictionary is required. * In the latter case, getAdler() can be used to get the Adler-32 * value of the dictionary required. * {@description.close} * @param b the buffer for the uncompressed data * @param off the start offset of the data * @param len the maximum number of uncompressed bytes * @return the actual number of uncompressed bytes * @exception DataFormatException if the compressed data format is invalid * @see Inflater#needsInput * @see Inflater#needsDictionary */ public int inflate(byte[] b, int off, int len) throws DataFormatException { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { ensureOpen(); return inflateBytes(zsRef.address(), b, off, len); } } /** {@collect.stats} * {@description.open} * Uncompresses bytes into specified buffer. Returns actual number * of bytes uncompressed. A return value of 0 indicates that * needsInput() or needsDictionary() should be called in order to * determine if more input data or a preset dictionary is required. * In the latter case, getAdler() can be used to get the Adler-32 * value of the dictionary required. * {@description.close} * @param b the buffer for the uncompressed data * @return the actual number of uncompressed bytes * @exception DataFormatException if the compressed data format is invalid * @see Inflater#needsInput * @see Inflater#needsDictionary */ public int inflate(byte[] b) throws DataFormatException { return inflate(b, 0, b.length); } /** {@collect.stats} * {@description.open} * Returns the ADLER-32 value of the uncompressed data. * {@description.close} * @return the ADLER-32 value of the uncompressed data */ public int getAdler() { synchronized (zsRef) { ensureOpen(); return getAdler(zsRef.address()); } } /** {@collect.stats} * {@description.open} * Returns the total number of compressed bytes input so far. * * <p>Since the number of bytes may be greater than * Integer.MAX_VALUE, the {@link #getBytesRead()} method is now * the preferred means of obtaining this information.</p> * {@description.close} * * @return the total number of compressed bytes input so far */ public int getTotalIn() { return (int) getBytesRead(); } /** {@collect.stats} * {@description.open} * Returns the total number of compressed bytes input so far.</p> * {@description.close} * * @return the total (non-negative) number of compressed bytes input so far * @since 1.5 */ public long getBytesRead() { synchronized (zsRef) { ensureOpen(); return getBytesRead(zsRef.address()); } } /** {@collect.stats} * {@description.open} * Returns the total number of uncompressed bytes output so far. * * <p>Since the number of bytes may be greater than * Integer.MAX_VALUE, the {@link #getBytesWritten()} method is now * the preferred means of obtaining this information.</p> * {@description.close} * * @return the total number of uncompressed bytes output so far */ public int getTotalOut() { return (int) getBytesWritten(); } /** {@collect.stats} * {@description.open} * Returns the total number of uncompressed bytes output so far.</p> * {@description.close} * * @return the total (non-negative) number of uncompressed bytes output so far * @since 1.5 */ public long getBytesWritten() { synchronized (zsRef) { ensureOpen(); return getBytesWritten(zsRef.address()); } } /** {@collect.stats} * {@description.open} * Resets inflater so that a new set of input data can be processed. * {@description.close} * {@property.open} * {@property.close} */ public void reset() { synchronized (zsRef) { ensureOpen(); reset(zsRef.address()); buf = emptyBuf; finished = false; needDict = false; off = len = 0; } } /** {@collect.stats} * {@description.open} * Closes the decompressor and discards any unprocessed input. * {@description.close} * {@property.open} * This method should be called when the decompressor is no longer * being used, but will also be called automatically by the finalize() * method. Once this method is called, the behavior of the Inflater * object is undefined. * {@property.close} */ public void end() { synchronized (zsRef) { long addr = zsRef.address(); zsRef.clear(); if (addr != 0) { end(addr); buf = null; } } } /** {@collect.stats} * {@description.open} * Closes the decompressor when garbage is collected. * {@description.close} */ protected void finalize() { end(); } private void ensureOpen () { assert Thread.holdsLock(zsRef); if (zsRef.address() == 0) throw new NullPointerException("Inflater has been closed"); } private static class NativeStrm { long strm; } private native static void initIDs(); private native static long init(boolean nowrap); private native static void setDictionary(long addr, byte[] b, int off, int len); private native int inflateBytes(long addr, byte[] b, int off, int len) throws DataFormatException; private native static int getAdler(long addr); private native static long getBytesRead(long addr); private native static long getBytesWritten(long addr); private native static void reset(long addr); private native static void end(long addr); }
Java
/* * Copyright (c) 1995, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.util.Date; /** {@collect.stats} * {@description.open} * This class is used to represent a ZIP file entry. * {@description.close} * * @author David Connelly */ public class ZipEntry implements ZipConstants, Cloneable { String name; // entry name long time = -1; // modification time (in DOS time) long crc = -1; // crc-32 of entry data long size = -1; // uncompressed size of entry data long csize = -1; // compressed size of entry data int method = -1; // compression method byte[] extra; // optional extra field data for entry String comment; // optional comment string for entry /** {@collect.stats} * {@description.open} * Compression method for uncompressed entries. * {@description.close} */ public static final int STORED = 0; /** {@collect.stats} * {@description.open} * Compression method for compressed (deflated) entries. * {@description.close} */ public static final int DEFLATED = 8; static { /* Zip library is loaded from System.initializeSystemClass */ initIDs(); } private static native void initIDs(); /** {@collect.stats} * {@description.open} * Creates a new zip entry with the specified name. * {@description.close} * * @param name the entry name * @exception NullPointerException if the entry name is null * @exception IllegalArgumentException if the entry name is longer than * 0xFFFF bytes */ public ZipEntry(String name) { if (name == null) { throw new NullPointerException(); } if (name.length() > 0xFFFF) { throw new IllegalArgumentException("entry name too long"); } this.name = name; } /** {@collect.stats} * {@description.open} * Creates a new zip entry with fields taken from the specified * zip entry. * {@description.close} * @param e a zip Entry object */ public ZipEntry(ZipEntry e) { name = e.name; time = e.time; crc = e.crc; size = e.size; csize = e.csize; method = e.method; extra = e.extra; comment = e.comment; } /* * Creates a new zip entry for the given name with fields initialized * from the specified jzentry data. */ ZipEntry(String name, long jzentry) { this.name = name; initFields(jzentry); } private native void initFields(long jzentry); /* * Creates a new zip entry with fields initialized from the specified * jzentry data. */ ZipEntry(long jzentry) { initFields(jzentry); } /** {@collect.stats} * {@description.open} * Returns the name of the entry. * {@description.close} * @return the name of the entry */ public String getName() { return name; } /** {@collect.stats} * {@description.open} * Sets the modification time of the entry. * {@description.close} * @param time the entry modification time in number of milliseconds * since the epoch * @see #getTime() */ public void setTime(long time) { this.time = javaToDosTime(time); } /** {@collect.stats} * {@description.open} * Returns the modification time of the entry, or -1 if not specified. * {@description.close} * @return the modification time of the entry, or -1 if not specified * @see #setTime(long) */ public long getTime() { return time != -1 ? dosToJavaTime(time) : -1; } /** {@collect.stats} * {@description.open} * Sets the uncompressed size of the entry data. * {@description.close} * @param size the uncompressed size in bytes * @exception IllegalArgumentException if the specified size is less * than 0 or greater than 0xFFFFFFFF bytes * @see #getSize() */ public void setSize(long size) { if (size < 0 || size > 0xFFFFFFFFL) { throw new IllegalArgumentException("invalid entry size"); } this.size = size; } /** {@collect.stats} * {@description.open} * Returns the uncompressed size of the entry data, or -1 if not known. * {@description.close} * @return the uncompressed size of the entry data, or -1 if not known * @see #setSize(long) */ public long getSize() { return size; } /** {@collect.stats} * {@description.open} * Returns the size of the compressed entry data, or -1 if not known. * In the case of a stored entry, the compressed size will be the same * as the uncompressed size of the entry. * {@description.close} * @return the size of the compressed entry data, or -1 if not known * @see #setCompressedSize(long) */ public long getCompressedSize() { return csize; } /** {@collect.stats} * {@description.open} * Sets the size of the compressed entry data. * {@description.close} * @param csize the compressed size to set to * @see #getCompressedSize() */ public void setCompressedSize(long csize) { this.csize = csize; } /** {@collect.stats} * {@description.open} * Sets the CRC-32 checksum of the uncompressed entry data. * {@description.close} * @param crc the CRC-32 value * @exception IllegalArgumentException if the specified CRC-32 value is * less than 0 or greater than 0xFFFFFFFF * @see #getCrc() */ public void setCrc(long crc) { if (crc < 0 || crc > 0xFFFFFFFFL) { throw new IllegalArgumentException("invalid entry crc-32"); } this.crc = crc; } /** {@collect.stats} * {@description.open} * Returns the CRC-32 checksum of the uncompressed entry data, or -1 if * not known. * {@description.close} * @return the CRC-32 checksum of the uncompressed entry data, or -1 if * not known * @see #setCrc(long) */ public long getCrc() { return crc; } /** {@collect.stats} * {@description.open} * Sets the compression method for the entry. * {@description.close} * @param method the compression method, either STORED or DEFLATED * @exception IllegalArgumentException if the specified compression * method is invalid * @see #getMethod() */ public void setMethod(int method) { if (method != STORED && method != DEFLATED) { throw new IllegalArgumentException("invalid compression method"); } this.method = method; } /** {@collect.stats} * {@description.open} * Returns the compression method of the entry, or -1 if not specified. * {@description.close} * @return the compression method of the entry, or -1 if not specified * @see #setMethod(int) */ public int getMethod() { return method; } /** {@collect.stats} * {@description.open} * Sets the optional extra field data for the entry. * {@description.close} * @param extra the extra field data bytes * @exception IllegalArgumentException if the length of the specified * extra field data is greater than 0xFFFF bytes * @see #getExtra() */ public void setExtra(byte[] extra) { if (extra != null && extra.length > 0xFFFF) { throw new IllegalArgumentException("invalid extra field length"); } this.extra = extra; } /** {@collect.stats} * {@description.open} * Returns the extra field data for the entry, or null if none. * {@description.close} * @return the extra field data for the entry, or null if none * @see #setExtra(byte[]) */ public byte[] getExtra() { return extra; } /** {@collect.stats} * {@description.open} * Sets the optional comment string for the entry. * {@description.close} * @param comment the comment string * @exception IllegalArgumentException if the length of the specified * comment string is greater than 0xFFFF bytes * @see #getComment() */ public void setComment(String comment) { if (comment != null && comment.length() > 0xffff/3 && ZipOutputStream.getUTF8Length(comment) > 0xffff) { throw new IllegalArgumentException("invalid entry comment length"); } this.comment = comment; } /** {@collect.stats} * {@description.open} * Returns the comment string for the entry, or null if none. * {@description.close} * @return the comment string for the entry, or null if none * @see #setComment(String) */ public String getComment() { return comment; } /** {@collect.stats} * {@description.open} * Returns true if this is a directory entry. A directory entry is * defined to be one whose name ends with a '/'. * {@description.close} * @return true if this is a directory entry */ public boolean isDirectory() { return name.endsWith("/"); } /** {@collect.stats} * {@description.open} * Returns a string representation of the ZIP entry. * {@description.close} */ public String toString() { return getName(); } /* * Converts DOS time to Java time (number of milliseconds since epoch). */ private static long dosToJavaTime(long dtime) { Date d = new Date((int)(((dtime >> 25) & 0x7f) + 80), (int)(((dtime >> 21) & 0x0f) - 1), (int)((dtime >> 16) & 0x1f), (int)((dtime >> 11) & 0x1f), (int)((dtime >> 5) & 0x3f), (int)((dtime << 1) & 0x3e)); return d.getTime(); } /* * Converts Java time to DOS time. */ private static long javaToDosTime(long time) { Date d = new Date(time); int year = d.getYear() + 1900; if (year < 1980) { return (1 << 21) | (1 << 16); } return (year - 1980) << 25 | (d.getMonth() + 1) << 21 | d.getDate() << 16 | d.getHours() << 11 | d.getMinutes() << 5 | d.getSeconds() >> 1; } /** {@collect.stats} * {@description.open} * Returns the hash code value for this entry. * {@description.close} */ public int hashCode() { return name.hashCode(); } /** {@collect.stats} * {@description.open} * Returns a copy of this entry. * {@description.close} */ public Object clone() { try { ZipEntry e = (ZipEntry)super.clone(); e.extra = (extra == null) ? null : extra.clone(); return e; } catch (CloneNotSupportedException e) { // This should never happen, since we are Cloneable throw new InternalError(); } } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.OutputStream; import java.io.IOException; import java.util.Vector; import java.util.HashSet; /** {@collect.stats} * {@description.open} * This class implements an output stream filter for writing files in the * ZIP file format. Includes support for both compressed and uncompressed * entries. * {@description.close} * * @author David Connelly */ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstants { private static class XEntry { public final ZipEntry entry; public final long offset; public final int flag; public XEntry(ZipEntry entry, long offset) { this.entry = entry; this.offset = offset; this.flag = (entry.method == DEFLATED && (entry.size == -1 || entry.csize == -1 || entry.crc == -1)) // store size, compressed size, and crc-32 in data descriptor // immediately following the compressed entry data ? 8 // store size, compressed size, and crc-32 in LOC header : 0; } } private XEntry current; private Vector<XEntry> xentries = new Vector<XEntry>(); private HashSet<String> names = new HashSet<String>(); private CRC32 crc = new CRC32(); private long written = 0; private long locoff = 0; private String comment; private int method = DEFLATED; private boolean finished; private boolean closed = false; private static int version(ZipEntry e) throws ZipException { switch (e.method) { case DEFLATED: return 20; case STORED: return 10; default: throw new ZipException("unsupported compression method"); } } /** {@collect.stats} * {@description.open} * Checks to make sure that this stream has not been closed. * {@description.close} */ private void ensureOpen() throws IOException { if (closed) { throw new IOException("Stream closed"); } } /** {@collect.stats} * {@description.open} * Compression method for uncompressed (STORED) entries. * {@description.close} */ public static final int STORED = ZipEntry.STORED; /** {@collect.stats} * {@description.open} * Compression method for compressed (DEFLATED) entries. * {@description.close} */ public static final int DEFLATED = ZipEntry.DEFLATED; /** {@collect.stats} * {@description.open} * Creates a new ZIP output stream. * {@description.close} * @param out the actual output stream */ public ZipOutputStream(OutputStream out) { super(out, new Deflater(Deflater.DEFAULT_COMPRESSION, true)); usesDefaultDeflater = true; } /** {@collect.stats} * {@description.open} * Sets the ZIP file comment. * {@description.close} * @param comment the comment string * @exception IllegalArgumentException if the length of the specified * ZIP file comment is greater than 0xFFFF bytes */ public void setComment(String comment) { if (comment != null && comment.length() > 0xffff/3 && getUTF8Length(comment) > 0xffff) { throw new IllegalArgumentException("ZIP file comment too long."); } this.comment = comment; } /** {@collect.stats} * {@description.open} * Sets the default compression method for subsequent entries. This * default will be used whenever the compression method is not specified * for an individual ZIP file entry, and is initially set to DEFLATED. * {@description.close} * @param method the default compression method * @exception IllegalArgumentException if the specified compression method * is invalid */ public void setMethod(int method) { if (method != DEFLATED && method != STORED) { throw new IllegalArgumentException("invalid compression method"); } this.method = method; } /** {@collect.stats} * {@description.open} * Sets the compression level for subsequent entries which are DEFLATED. * The default setting is DEFAULT_COMPRESSION. * {@description.close} * @param level the compression level (0-9) * @exception IllegalArgumentException if the compression level is invalid */ public void setLevel(int level) { def.setLevel(level); } /** {@collect.stats} * {@description.open} * Begins writing a new ZIP file entry and positions the stream to the * start of the entry data. Closes the current entry if still active. * The default compression method will be used if no compression method * was specified for the entry, and the current time will be used if * the entry has no set modification time. * {@description.close} * @param e the ZIP entry to be written * @exception ZipException if a ZIP format error has occurred * @exception IOException if an I/O error has occurred */ public void putNextEntry(ZipEntry e) throws IOException { ensureOpen(); if (current != null) { closeEntry(); // close previous entry } if (e.time == -1) { e.setTime(System.currentTimeMillis()); } if (e.method == -1) { e.method = method; // use default method } switch (e.method) { case DEFLATED: break; case STORED: // compressed size, uncompressed size, and crc-32 must all be // set for entries using STORED compression method if (e.size == -1) { e.size = e.csize; } else if (e.csize == -1) { e.csize = e.size; } else if (e.size != e.csize) { throw new ZipException( "STORED entry where compressed != uncompressed size"); } if (e.size == -1 || e.crc == -1) { throw new ZipException( "STORED entry missing size, compressed size, or crc-32"); } break; default: throw new ZipException("unsupported compression method"); } if (! names.add(e.name)) { throw new ZipException("duplicate entry: " + e.name); } current = new XEntry(e, written); xentries.add(current); writeLOC(current); } /** {@collect.stats} * {@description.open} * Closes the current ZIP entry and positions the stream for writing * the next entry. * {@description.close} * @exception ZipException if a ZIP format error has occurred * @exception IOException if an I/O error has occurred */ public void closeEntry() throws IOException { ensureOpen(); if (current != null) { ZipEntry e = current.entry; switch (e.method) { case DEFLATED: def.finish(); while (!def.finished()) { deflate(); } if ((current.flag & 8) == 0) { // verify size, compressed size, and crc-32 settings if (e.size != def.getBytesRead()) { throw new ZipException( "invalid entry size (expected " + e.size + " but got " + def.getBytesRead() + " bytes)"); } if (e.csize != def.getBytesWritten()) { throw new ZipException( "invalid entry compressed size (expected " + e.csize + " but got " + def.getBytesWritten() + " bytes)"); } if (e.crc != crc.getValue()) { throw new ZipException( "invalid entry CRC-32 (expected 0x" + Long.toHexString(e.crc) + " but got 0x" + Long.toHexString(crc.getValue()) + ")"); } } else { e.size = def.getBytesRead(); e.csize = def.getBytesWritten(); e.crc = crc.getValue(); writeEXT(e); } def.reset(); written += e.csize; break; case STORED: // we already know that both e.size and e.csize are the same if (e.size != written - locoff) { throw new ZipException( "invalid entry size (expected " + e.size + " but got " + (written - locoff) + " bytes)"); } if (e.crc != crc.getValue()) { throw new ZipException( "invalid entry crc-32 (expected 0x" + Long.toHexString(e.crc) + " but got 0x" + Long.toHexString(crc.getValue()) + ")"); } break; default: throw new ZipException("invalid compression method"); } crc.reset(); current = null; } } /** {@collect.stats} * {@description.open} * Writes an array of bytes to the current ZIP entry data. This method * will block until all the bytes are written. * {@description.close} * @param b the data to be written * @param off the start offset in the data * @param len the number of bytes that are written * @exception ZipException if a ZIP file error has occurred * @exception IOException if an I/O error has occurred */ public synchronized void write(byte[] b, int off, int len) throws IOException { ensureOpen(); if (off < 0 || len < 0 || off > b.length - len) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (current == null) { throw new ZipException("no current ZIP entry"); } ZipEntry entry = current.entry; switch (entry.method) { case DEFLATED: super.write(b, off, len); break; case STORED: written += len; if (written - locoff > entry.size) { throw new ZipException( "attempt to write past end of STORED entry"); } out.write(b, off, len); break; default: throw new ZipException("invalid compression method"); } crc.update(b, off, len); } /** {@collect.stats} * {@description.open} * Finishes writing the contents of the ZIP output stream without closing * the underlying stream. * {@description.close} * {@property.open} * Use this method when applying multiple filters * in succession to the same output stream. * {@property.close} * @exception ZipException if a ZIP file error has occurred * @exception IOException if an I/O exception has occurred */ public void finish() throws IOException { ensureOpen(); if (finished) { return; } if (current != null) { closeEntry(); } if (xentries.size() < 1) { throw new ZipException("ZIP file must have at least one entry"); } // write central directory long off = written; for (XEntry xentry : xentries) writeCEN(xentry); writeEND(off, written - off); finished = true; } /** {@collect.stats} * {@description.open} * Closes the ZIP output stream as well as the stream being filtered. * {@description.close} * @exception ZipException if a ZIP file error has occurred * @exception IOException if an I/O error has occurred */ public void close() throws IOException { if (!closed) { super.close(); closed = true; } } /* * Writes local file (LOC) header for specified entry. */ private void writeLOC(XEntry xentry) throws IOException { ZipEntry e = xentry.entry; int flag = xentry.flag; writeInt(LOCSIG); // LOC header signature writeShort(version(e)); // version needed to extract writeShort(flag); // general purpose bit flag writeShort(e.method); // compression method writeInt(e.time); // last modification time if ((flag & 8) == 8) { // store size, uncompressed size, and crc-32 in data descriptor // immediately following compressed entry data writeInt(0); writeInt(0); writeInt(0); } else { writeInt(e.crc); // crc-32 writeInt(e.csize); // compressed size writeInt(e.size); // uncompressed size } byte[] nameBytes = getUTF8Bytes(e.name); writeShort(nameBytes.length); writeShort(e.extra != null ? e.extra.length : 0); writeBytes(nameBytes, 0, nameBytes.length); if (e.extra != null) { writeBytes(e.extra, 0, e.extra.length); } locoff = written; } /* * Writes extra data descriptor (EXT) for specified entry. */ private void writeEXT(ZipEntry e) throws IOException { writeInt(EXTSIG); // EXT header signature writeInt(e.crc); // crc-32 writeInt(e.csize); // compressed size writeInt(e.size); // uncompressed size } /* * Write central directory (CEN) header for specified entry. * REMIND: add support for file attributes */ private void writeCEN(XEntry xentry) throws IOException { ZipEntry e = xentry.entry; int flag = xentry.flag; int version = version(e); writeInt(CENSIG); // CEN header signature writeShort(version); // version made by writeShort(version); // version needed to extract writeShort(flag); // general purpose bit flag writeShort(e.method); // compression method writeInt(e.time); // last modification time writeInt(e.crc); // crc-32 writeInt(e.csize); // compressed size writeInt(e.size); // uncompressed size byte[] nameBytes = getUTF8Bytes(e.name); writeShort(nameBytes.length); writeShort(e.extra != null ? e.extra.length : 0); byte[] commentBytes; if (e.comment != null) { commentBytes = getUTF8Bytes(e.comment); writeShort(commentBytes.length); } else { commentBytes = null; writeShort(0); } writeShort(0); // starting disk number writeShort(0); // internal file attributes (unused) writeInt(0); // external file attributes (unused) writeInt(xentry.offset); // relative offset of local header writeBytes(nameBytes, 0, nameBytes.length); if (e.extra != null) { writeBytes(e.extra, 0, e.extra.length); } if (commentBytes != null) { writeBytes(commentBytes, 0, commentBytes.length); } } /* * Writes end of central directory (END) header. */ private void writeEND(long off, long len) throws IOException { int count = xentries.size(); writeInt(ENDSIG); // END record signature writeShort(0); // number of this disk writeShort(0); // central directory start disk writeShort(count); // number of directory entries on disk writeShort(count); // total number of directory entries writeInt(len); // length of central directory writeInt(off); // offset of central directory if (comment != null) { // zip file comment byte[] b = getUTF8Bytes(comment); writeShort(b.length); writeBytes(b, 0, b.length); } else { writeShort(0); } } /* * Writes a 16-bit short to the output stream in little-endian byte order. */ private void writeShort(int v) throws IOException { OutputStream out = this.out; out.write((v >>> 0) & 0xff); out.write((v >>> 8) & 0xff); written += 2; } /* * Writes a 32-bit int to the output stream in little-endian byte order. */ private void writeInt(long v) throws IOException { OutputStream out = this.out; out.write((int)((v >>> 0) & 0xff)); out.write((int)((v >>> 8) & 0xff)); out.write((int)((v >>> 16) & 0xff)); out.write((int)((v >>> 24) & 0xff)); written += 4; } /* * Writes an array of bytes to the output stream. */ private void writeBytes(byte[] b, int off, int len) throws IOException { super.out.write(b, off, len); written += len; } /* * Returns the length of String's UTF8 encoding. */ static int getUTF8Length(String s) { int count = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch <= 0x7f) { count++; } else if (ch <= 0x7ff) { count += 2; } else { count += 3; } } return count; } /* * Returns an array of bytes representing the UTF8 encoding * of the specified String. */ private static byte[] getUTF8Bytes(String s) { char[] c = s.toCharArray(); int len = c.length; // Count the number of encoded bytes... int count = 0; for (int i = 0; i < len; i++) { int ch = c[i]; if (ch <= 0x7f) { count++; } else if (ch <= 0x7ff) { count += 2; } else { count += 3; } } // Now return the encoded bytes... byte[] b = new byte[count]; int off = 0; for (int i = 0; i < len; i++) { int ch = c[i]; if (ch <= 0x7f) { b[off++] = (byte)ch; } else if (ch <= 0x7ff) { b[off++] = (byte)((ch >> 6) | 0xc0); b[off++] = (byte)((ch & 0x3f) | 0x80); } else { b[off++] = (byte)((ch >> 12) | 0xe0); b[off++] = (byte)(((ch >> 6) & 0x3f) | 0x80); b[off++] = (byte)((ch & 0x3f) | 0x80); } } return b; } }
Java
/* * Copyright (c) 1995, 1996, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; /* * This interface defines the constants that are used by the classes * which manipulate ZIP files. * * @author David Connelly */ interface ZipConstants { /* * Header signatures */ static long LOCSIG = 0x04034b50L; // "PK\003\004" static long EXTSIG = 0x08074b50L; // "PK\007\008" static long CENSIG = 0x02014b50L; // "PK\001\002" static long ENDSIG = 0x06054b50L; // "PK\005\006" /* * Header sizes in bytes (including signatures) */ static final int LOCHDR = 30; // LOC header size static final int EXTHDR = 16; // EXT header size static final int CENHDR = 46; // CEN header size static final int ENDHDR = 22; // END header size /* * Local file (LOC) header field offsets */ static final int LOCVER = 4; // version needed to extract static final int LOCFLG = 6; // general purpose bit flag static final int LOCHOW = 8; // compression method static final int LOCTIM = 10; // modification time static final int LOCCRC = 14; // uncompressed file crc-32 value static final int LOCSIZ = 18; // compressed size static final int LOCLEN = 22; // uncompressed size static final int LOCNAM = 26; // filename length static final int LOCEXT = 28; // extra field length /* * Extra local (EXT) header field offsets */ static final int EXTCRC = 4; // uncompressed file crc-32 value static final int EXTSIZ = 8; // compressed size static final int EXTLEN = 12; // uncompressed size /* * Central directory (CEN) header field offsets */ static final int CENVEM = 4; // version made by static final int CENVER = 6; // version needed to extract static final int CENFLG = 8; // encrypt, decrypt flags static final int CENHOW = 10; // compression method static final int CENTIM = 12; // modification time static final int CENCRC = 16; // uncompressed file crc-32 value static final int CENSIZ = 20; // compressed size static final int CENLEN = 24; // uncompressed size static final int CENNAM = 28; // filename length static final int CENEXT = 30; // extra field length static final int CENCOM = 32; // comment length static final int CENDSK = 34; // disk number start static final int CENATT = 36; // internal file attributes static final int CENATX = 38; // external file attributes static final int CENOFF = 42; // LOC header offset /* * End of central directory (END) header field offsets */ static final int ENDSUB = 8; // number of entries on this disk static final int ENDTOT = 10; // total number of entries static final int ENDSIZ = 12; // central directory size in bytes static final int ENDOFF = 16; // offset of first CEN header static final int ENDCOM = 20; // zip file comment length }
Java
/* * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** {@collect.stats} * {@description.open} * Implements an output stream filter for uncompressing data stored in the * "deflate" compression format. * {@description.close} * * @since 1.6 * @author David R Tribble (david@tribble.com) * * @see InflaterInputStream * @see DeflaterInputStream * @see DeflaterOutputStream */ public class InflaterOutputStream extends FilterOutputStream { /** {@collect.stats} * {@description.open} * Decompressor for this stream. * {@description.close} */ protected final Inflater inf; /** {@collect.stats} * {@description.open} * Output buffer for writing uncompressed data. * {@description.close} */ protected final byte[] buf; /** {@collect.stats} * {@description.open} * Temporary write buffer. * {@description.close} */ private final byte[] wbuf = new byte[1]; /** {@collect.stats} * {@description.open} * Default decompressor is used. * {@description.close} */ private boolean usesDefaultInflater = false; /** {@collect.stats} * {@description.open} * true iff {@link #close()} has been called. * {@description.close} */ private boolean closed = false; /** {@collect.stats} * {@description.open} * Checks to make sure that this stream has not been closed. * {@description.close} */ private void ensureOpen() throws IOException { if (closed) { throw new IOException("Stream closed"); } } /** {@collect.stats} * {@description.open} * Creates a new output stream with a default decompressor and buffer * size. * {@description.close} * * @param out output stream to write the uncompressed data to * @throws NullPointerException if {@code out} is null */ public InflaterOutputStream(OutputStream out) { this(out, new Inflater()); usesDefaultInflater = true; } /** {@collect.stats} * {@description.open} * Creates a new output stream with the specified decompressor and a * default buffer size. * {@description.close} * * @param out output stream to write the uncompressed data to * @param infl decompressor ("inflater") for this stream * @throws NullPointerException if {@code out} or {@code infl} is null */ public InflaterOutputStream(OutputStream out, Inflater infl) { this(out, infl, 512); } /** {@collect.stats} * {@description.open} * Creates a new output stream with the specified decompressor and * buffer size. * {@description.close} * * @param out output stream to write the uncompressed data to * @param infl decompressor ("inflater") for this stream * @param bufLen decompression buffer size * @throws IllegalArgumentException if {@code bufLen} is <= 0 * @throws NullPointerException if {@code out} or {@code infl} is null */ public InflaterOutputStream(OutputStream out, Inflater infl, int bufLen) { super(out); // Sanity checks if (out == null) throw new NullPointerException("Null output"); if (infl == null) throw new NullPointerException("Null inflater"); if (bufLen <= 0) throw new IllegalArgumentException("Buffer size < 1"); // Initialize inf = infl; buf = new byte[bufLen]; } /** {@collect.stats} * {@description.open} * Writes any remaining uncompressed data to the output stream and closes * the underlying output stream. * {@description.close} * * @throws IOException if an I/O error occurs */ public void close() throws IOException { if (!closed) { // Complete the uncompressed output try { finish(); } finally { out.close(); closed = true; } } } /** {@collect.stats} * {@description.open} * Flushes this output stream, forcing any pending buffered output bytes to be * written. * {@description.close} * * @throws IOException if an I/O error occurs or this stream is already * closed */ public void flush() throws IOException { ensureOpen(); // Finish decompressing and writing pending output data if (!inf.finished()) { try { while (!inf.finished() && !inf.needsInput()) { int n; // Decompress pending output data n = inf.inflate(buf, 0, buf.length); if (n < 1) { break; } // Write the uncompressed output data block out.write(buf, 0, n); } super.flush(); } catch (DataFormatException ex) { // Improperly formatted compressed (ZIP) data String msg = ex.getMessage(); if (msg == null) { msg = "Invalid ZLIB data format"; } throw new ZipException(msg); } } } /** {@collect.stats} * {@description.open} * Finishes writing uncompressed data to the output stream without closing * the underlying stream. * {@description.close} * {@property.open} * Use this method when applying multiple filters in * succession to the same output stream. * {@property.close} * * @throws IOException if an I/O error occurs or this stream is already * closed */ public void finish() throws IOException { ensureOpen(); // Finish decompressing and writing pending output data flush(); if (usesDefaultInflater) { inf.end(); } } /** {@collect.stats} * {@description.open} * Writes a byte to the uncompressed output stream. * {@description.close} * * @param b a single byte of compressed data to decompress and write to * the output stream * @throws IOException if an I/O error occurs or this stream is already * closed * @throws ZipException if a compression (ZIP) format error occurs */ public void write(int b) throws IOException { // Write a single byte of data wbuf[0] = (byte) b; write(wbuf, 0, 1); } /** {@collect.stats} * {@description.open} * Writes an array of bytes to the uncompressed output stream. * {@description.close} * * @param b buffer containing compressed data to decompress and write to * the output stream * @param off starting offset of the compressed data within {@code b} * @param len number of bytes to decompress from {@code b} * @throws IndexOutOfBoundsException if {@code off} < 0, or if * {@code len} < 0, or if {@code len} > {@code b.length - off} * @throws IOException if an I/O error occurs or this stream is already * closed * @throws NullPointerException if {@code b} is null * @throws ZipException if a compression (ZIP) format error occurs */ public void write(byte[] b, int off, int len) throws IOException { // Sanity checks ensureOpen(); if (b == null) { throw new NullPointerException("Null buffer for read"); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } // Write uncompressed data to the output stream try { for (;;) { int n; // Fill the decompressor buffer with output data if (inf.needsInput()) { int part; if (len < 1) { break; } part = (len < 512 ? len : 512); inf.setInput(b, off, part); off += part; len -= part; } // Decompress and write blocks of output data do { n = inf.inflate(buf, 0, buf.length); if (n > 0) { out.write(buf, 0, n); } } while (n > 0); // Check the decompressor if (inf.finished()) { break; } if (inf.needsDictionary()) { throw new ZipException("ZLIB dictionary missing"); } } } catch (DataFormatException ex) { // Improperly formatted compressed (ZIP) data String msg = ex.getMessage(); if (msg == null) { msg = "Invalid ZLIB data format"; } throw new ZipException(msg); } } }
Java
/* * Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.FilterOutputStream; import java.io.OutputStream; import java.io.IOException; /** {@collect.stats} * {@description.open} * An output stream that also maintains a checksum of the data being * written. The checksum can then be used to verify the integrity of * the output data. * {@description.close} * * @see Checksum * @author David Connelly */ public class CheckedOutputStream extends FilterOutputStream { private Checksum cksum; /** {@collect.stats} * {@description.open} * Creates an output stream with the specified Checksum. * {@description.close} * @param out the output stream * @param cksum the checksum */ public CheckedOutputStream(OutputStream out, Checksum cksum) { super(out); this.cksum = cksum; } /** {@collect.stats} * {@description.open} * Writes a byte. Will block until the byte is actually written. * {@description.close} * @param b the byte to be written * @exception IOException if an I/O error has occurred */ public void write(int b) throws IOException { out.write(b); cksum.update(b); } /** {@collect.stats} * {@description.open} * Writes an array of bytes. Will block until the bytes are * actually written. * {@description.close} * @param b the data to be written * @param off the start offset of the data * @param len the number of bytes to be written * @exception IOException if an I/O error has occurred */ public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); cksum.update(b, off, len); } /** {@collect.stats} * {@description.open} * Returns the Checksum for this output stream. * {@description.close} * @return the Checksum */ public Checksum getChecksum() { return cksum; } }
Java
/* * Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; /** {@collect.stats} * {@description.open} * An interface representing a data checksum. * {@description.close} * * @author David Connelly */ public interface Checksum { /** {@collect.stats} * {@description.open} * Updates the current checksum with the specified byte. * {@description.close} * * @param b the byte to update the checksum with */ public void update(int b); /** {@collect.stats} * {@description.open} * Updates the current checksum with the specified array of bytes. * {@description.close} * @param b the byte array to update the checksum with * @param off the start offset of the data * @param len the number of bytes to use for the update */ public void update(byte[] b, int off, int len); /** {@collect.stats} * {@description.open} * Returns the current checksum value. * {@description.close} * @return the current checksum value */ public long getValue(); /** {@collect.stats} * {@description.open} * Resets the checksum to its initial value. * {@description.close} */ public void reset(); }
Java
/* * Copyright (c) 1996, 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.OutputStream; import java.io.IOException; /** {@collect.stats} * {@description.open} * This class implements a stream filter for writing compressed data in * the GZIP file format. * {@description.close} * @author David Connelly * */ public class GZIPOutputStream extends DeflaterOutputStream { /** {@collect.stats} * {@description.open} * CRC-32 of uncompressed data. * {@description.close} */ protected CRC32 crc = new CRC32(); /* * GZIP header magic number. */ private final static int GZIP_MAGIC = 0x8b1f; /* * Trailer size in bytes. * */ private final static int TRAILER_SIZE = 8; /** {@collect.stats} * {@description.open} * Creates a new output stream with the specified buffer size. * {@description.close} * @param out the output stream * @param size the output buffer size * @exception IOException If an I/O error has occurred. * @exception IllegalArgumentException if size is <= 0 */ public GZIPOutputStream(OutputStream out, int size) throws IOException { super(out, new Deflater(Deflater.DEFAULT_COMPRESSION, true), size); usesDefaultDeflater = true; writeHeader(); crc.reset(); } /** {@collect.stats} * {@description.open} * Creates a new output stream with a default buffer size. * {@description.close} * @param out the output stream * @exception IOException If an I/O error has occurred. */ public GZIPOutputStream(OutputStream out) throws IOException { this(out, 512); } /** {@collect.stats} * {@description.open} * Writes array of bytes to the compressed output stream. This method * will block until all the bytes are written. * {@description.close} * @param buf the data to be written * @param off the start offset of the data * @param len the length of the data * @exception IOException If an I/O error has occurred. */ public synchronized void write(byte[] buf, int off, int len) throws IOException { super.write(buf, off, len); crc.update(buf, off, len); } /** {@collect.stats} * {@description.open} * Finishes writing compressed data to the output stream without closing * the underlying stream. * {@description.close} * {@property.open} * Use this method when applying multiple filters * in succession to the same output stream. * {@property.close} * @exception IOException if an I/O error has occurred */ public void finish() throws IOException { if (!def.finished()) { def.finish(); while (!def.finished()) { int len = def.deflate(buf, 0, buf.length); if (def.finished() && len <= buf.length - TRAILER_SIZE) { // last deflater buffer. Fit trailer at the end writeTrailer(buf, len); len = len + TRAILER_SIZE; out.write(buf, 0, len); return; } if (len > 0) out.write(buf, 0, len); } // if we can't fit the trailer at the end of the last // deflater buffer, we write it separately byte[] trailer = new byte[TRAILER_SIZE]; writeTrailer(trailer, 0); out.write(trailer); } } /* * Writes GZIP member header. */ private final static byte[] header = { (byte) GZIP_MAGIC, // Magic number (short) (byte)(GZIP_MAGIC >> 8), // Magic number (short) Deflater.DEFLATED, // Compression method (CM) 0, // Flags (FLG) 0, // Modification time MTIME (int) 0, // Modification time MTIME (int) 0, // Modification time MTIME (int) 0, // Modification time MTIME (int) 0, // Extra flags (XFLG) 0 // Operating system (OS) }; private void writeHeader() throws IOException { out.write(header); } /* * Writes GZIP member trailer to a byte array, starting at a given * offset. */ private void writeTrailer(byte[] buf, int offset) throws IOException { writeInt((int)crc.getValue(), buf, offset); // CRC-32 of uncompr. data writeInt(def.getTotalIn(), buf, offset + 4); // Number of uncompr. bytes } /* * Writes integer in Intel byte order to a byte array, starting at a * given offset. */ private void writeInt(int i, byte[] buf, int offset) throws IOException { writeShort(i & 0xffff, buf, offset); writeShort((i >> 16) & 0xffff, buf, offset + 2); } /* * Writes short integer in Intel byte order to a byte array, starting * at a given offset */ private void writeShort(int s, byte[] buf, int offset) throws IOException { buf[offset] = (byte)(s & 0xff); buf[offset + 1] = (byte)((s >> 8) & 0xff); } }
Java
/* * Copyright (c) 1995, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.IOException; /** {@collect.stats} * {@description.open} * Signals that a Zip exception of some sort has occurred. * {@description.close} * * @author unascribed * @see java.io.IOException * @since JDK1.0 */ public class ZipException extends IOException { /** {@collect.stats} * {@description.open} * Constructs an <code>ZipException</code> with <code>null</code> * as its error detail message. * {@description.close} */ public ZipException() { super(); } /** {@collect.stats} * {@description.open} * Constructs an <code>ZipException</code> with the specified detail * message. * {@description.close} * * @param s the detail message. */ public ZipException(String s) { super(s); } }
Java
/* * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; /** {@collect.stats} * {@description.open} * A class that can be used to compute the Adler-32 checksum of a data * stream. An Adler-32 checksum is almost as reliable as a CRC-32 but * can be computed much faster. * {@description.close} * * @see Checksum * @author David Connelly */ public class Adler32 implements Checksum { private int adler = 1; /** {@collect.stats} * {@description.open} * Creates a new Adler32 object. * {@description.close} */ public Adler32() { } /** {@collect.stats} * {@description.open} * Updates checksum with specified byte. * {@description.close} * * @param b an array of bytes */ public void update(int b) { adler = update(adler, b); } /** {@collect.stats} * {@description.open} * Updates checksum with specified array of bytes. * {@description.close} */ public void update(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } adler = updateBytes(adler, b, off, len); } /** {@collect.stats} * {@description.open} * Updates checksum with specified array of bytes. * {@description.close} */ public void update(byte[] b) { adler = updateBytes(adler, b, 0, b.length); } /** {@collect.stats} * {@description.open} * Resets checksum to initial value. * {@description.close} */ public void reset() { adler = 1; } /** {@collect.stats} * {@description.open} * Returns checksum value. * {@description.close} */ public long getValue() { return (long)adler & 0xffffffffL; } private native static int update(int adler, int b); private native static int updateBytes(int adler, byte[] b, int off, int len); }
Java
/* * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; /** {@collect.stats} * {@description.open} * A reference to the native zlib's z_stream structure. * {@description.close} */ class ZStreamRef { private long address; ZStreamRef (long address) { this.address = address; } long address() { return address; } void clear() { address = 0; } }
Java
/* * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; /** {@collect.stats} * {@description.open} * This class provides support for general purpose compression using the * popular ZLIB compression library. The ZLIB compression library was * initially developed as part of the PNG graphics standard and is not * protected by patents. It is fully described in the specifications at * the <a href="package-summary.html#package_description">java.util.zip * package description</a>. * * <p>The following code fragment demonstrates a trivial compression * and decompression of a string using <tt>Deflater</tt> and * <tt>Inflater</tt>. * * <blockquote><pre> * try { * // Encode a String into bytes * String inputString = "blahblahblah\u20AC\u20AC"; * byte[] input = inputString.getBytes("UTF-8"); * * // Compress the bytes * byte[] output = new byte[100]; * Deflater compresser = new Deflater(); * compresser.setInput(input); * compresser.finish(); * int compressedDataLength = compresser.deflate(output); * * // Decompress the bytes * Inflater decompresser = new Inflater(); * decompresser.setInput(output, 0, compressedDataLength); * byte[] result = new byte[100]; * int resultLength = decompresser.inflate(result); * decompresser.end(); * * // Decode the bytes into a String * String outputString = new String(result, 0, resultLength, "UTF-8"); * } catch(java.io.UnsupportedEncodingException ex) { * // handle * } catch (java.util.zip.DataFormatException ex) { * // handle * } * </pre></blockquote> * {@description.close} * * @see Inflater * @author David Connelly */ public class Deflater { private final ZStreamRef zsRef; private byte[] buf = new byte[0]; private int off, len; private int level, strategy; private boolean setParams; private boolean finish, finished; /** {@collect.stats} * {@description.open} * Compression method for the deflate algorithm (the only one currently * supported). * {@description.close} */ public static final int DEFLATED = 8; /** {@collect.stats} * {@description.open} * Compression level for no compression. * {@description.close} */ public static final int NO_COMPRESSION = 0; /** {@collect.stats} * {@description.open} * Compression level for fastest compression. * {@description.close} */ public static final int BEST_SPEED = 1; /** {@collect.stats} * {@description.open} * Compression level for best compression. * {@description.close} */ public static final int BEST_COMPRESSION = 9; /** {@collect.stats} * {@description.open} * Default compression level. * {@description.close} */ public static final int DEFAULT_COMPRESSION = -1; /** {@collect.stats} * {@description.open} * Compression strategy best used for data consisting mostly of small * values with a somewhat random distribution. Forces more Huffman coding * and less string matching. * {@description.close} */ public static final int FILTERED = 1; /** {@collect.stats} * {@description.open} * Compression strategy for Huffman coding only. * {@description.close} */ public static final int HUFFMAN_ONLY = 2; /** {@collect.stats} * {@description.open} * Default compression strategy. * {@description.close} */ public static final int DEFAULT_STRATEGY = 0; static { /* Zip library is loaded from System.initializeSystemClass */ initIDs(); } /** {@collect.stats} * {@description.open} * Creates a new compressor using the specified compression level. * If 'nowrap' is true then the ZLIB header and checksum fields will * not be used in order to support the compression format used in * both GZIP and PKZIP. * {@description.close} * @param level the compression level (0-9) * @param nowrap if true then use GZIP compatible compression */ public Deflater(int level, boolean nowrap) { this.level = level; this.strategy = DEFAULT_STRATEGY; this.zsRef = new ZStreamRef(init(level, DEFAULT_STRATEGY, nowrap)); } /** {@collect.stats} * {@description.open} * Creates a new compressor using the specified compression level. * Compressed data will be generated in ZLIB format. * {@description.close} * @param level the compression level (0-9) */ public Deflater(int level) { this(level, false); } /** {@collect.stats} * {@description.open} * Creates a new compressor with the default compression level. * Compressed data will be generated in ZLIB format. * {@description.close} */ public Deflater() { this(DEFAULT_COMPRESSION, false); } /** {@collect.stats} * {@description.open} * Sets input data for compression. * {@description.close} * {@property.open} * This should be called whenever * needsInput() returns true indicating that more input data is required. * {@property.close} * @param b the input data bytes * @param off the start offset of the data * @param len the length of the data * @see Deflater#needsInput */ public void setInput(byte[] b, int off, int len) { if (b== null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { this.buf = b; this.off = off; this.len = len; } } /** {@collect.stats} * {@description.open} * Sets input data for compression. * {@description.close} * {@property.open} * This should be called whenever * needsInput() returns true indicating that more input data is required. * {@property.close} * @param b the input data bytes * @see Deflater#needsInput */ public void setInput(byte[] b) { setInput(b, 0, b.length); } /** {@collect.stats} * {@description.open} * Sets preset dictionary for compression. A preset dictionary is used * when the history buffer can be predetermined. When the data is later * uncompressed with Inflater.inflate(), Inflater.getAdler() can be called * in order to get the Adler-32 value of the dictionary required for * decompression. * {@description.close} * @param b the dictionary data bytes * @param off the start offset of the data * @param len the length of the data * @see Inflater#inflate * @see Inflater#getAdler */ public void setDictionary(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { ensureOpen(); setDictionary(zsRef.address(), b, off, len); } } /** {@collect.stats} * {@description.open} * Sets preset dictionary for compression. A preset dictionary is used * when the history buffer can be predetermined. When the data is later * uncompressed with Inflater.inflate(), Inflater.getAdler() can be called * in order to get the Adler-32 value of the dictionary required for * decompression. * {@description.close} * @param b the dictionary data bytes * @see Inflater#inflate * @see Inflater#getAdler */ public void setDictionary(byte[] b) { setDictionary(b, 0, b.length); } /** {@collect.stats} * {@description.open} * Sets the compression strategy to the specified value. * {@description.close} * @param strategy the new compression strategy * @exception IllegalArgumentException if the compression strategy is * invalid */ public void setStrategy(int strategy) { switch (strategy) { case DEFAULT_STRATEGY: case FILTERED: case HUFFMAN_ONLY: break; default: throw new IllegalArgumentException(); } synchronized (zsRef) { if (this.strategy != strategy) { this.strategy = strategy; setParams = true; } } } /** {@collect.stats} * {@description.open} * Sets the current compression level to the specified value. * {@description.close} * @param level the new compression level (0-9) * @exception IllegalArgumentException if the compression level is invalid */ public void setLevel(int level) { if ((level < 0 || level > 9) && level != DEFAULT_COMPRESSION) { throw new IllegalArgumentException("invalid compression level"); } synchronized (zsRef) { if (this.level != level) { this.level = level; setParams = true; } } } /** {@collect.stats} * {@description.open} * Returns true if the input data buffer is empty and setInput() * should be called in order to provide more input. * {@description.close} * @return true if the input data buffer is empty and setInput() * should be called in order to provide more input */ public boolean needsInput() { return len <= 0; } /** {@collect.stats} * {@description.open} * When called, indicates that compression should end with the current * contents of the input buffer. * {@description.close} */ public void finish() { synchronized (zsRef) { finish = true; } } /** {@collect.stats} * {@description.open} * Returns true if the end of the compressed data output stream has * been reached. * {@description.close} * @return true if the end of the compressed data output stream has * been reached */ public boolean finished() { synchronized (zsRef) { return finished; } } /** {@collect.stats} * {@description.open} * Fills specified buffer with compressed data. Returns actual number * of bytes of compressed data. * {@description.close} * {@property.open} * A return value of 0 indicates that * needsInput() should be called in order to determine if more input * data is required. * {@property.close} * @param b the buffer for the compressed data * @param off the start offset of the data * @param len the maximum number of bytes of compressed data * @return the actual number of bytes of compressed data */ public int deflate(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { return deflateBytes(zsRef.address(), b, off, len); } } /** {@collect.stats} * {@description.open} * Fills specified buffer with compressed data. Returns actual number * of bytes of compressed data. * {@description.close} * {@property.open} * A return value of 0 indicates that * needsInput() should be called in order to determine if more input * data is required. * {@property.close} * @param b the buffer for the compressed data * @return the actual number of bytes of compressed data */ public int deflate(byte[] b) { return deflate(b, 0, b.length); } /** {@collect.stats} * {@description.open} * Returns the ADLER-32 value of the uncompressed data. * {@description.close} * @return the ADLER-32 value of the uncompressed data */ public int getAdler() { synchronized (zsRef) { ensureOpen(); return getAdler(zsRef.address()); } } /** {@collect.stats} * {@description.open} * Returns the total number of uncompressed bytes input so far. * * <p>Since the number of bytes may be greater than * Integer.MAX_VALUE, the {@link #getBytesRead()} method is now * the preferred means of obtaining this information.</p> * {@description.close} * * @return the total number of uncompressed bytes input so far */ public int getTotalIn() { return (int) getBytesRead(); } /** {@collect.stats} * {@description.open} * Returns the total number of uncompressed bytes input so far.</p> * {@description.close} * * @return the total (non-negative) number of uncompressed bytes input so far * @since 1.5 */ public long getBytesRead() { synchronized (zsRef) { ensureOpen(); return getBytesRead(zsRef.address()); } } /** {@collect.stats} * {@description.open} * Returns the total number of compressed bytes output so far. * * <p>Since the number of bytes may be greater than * Integer.MAX_VALUE, the {@link #getBytesWritten()} method is now * the preferred means of obtaining this information.</p> * {@description.close} * * @return the total number of compressed bytes output so far */ public int getTotalOut() { return (int) getBytesWritten(); } /** {@collect.stats} * {@description.open} * Returns the total number of compressed bytes output so far.</p> * {@description.close} * * @return the total (non-negative) number of compressed bytes output so far * @since 1.5 */ public long getBytesWritten() { synchronized (zsRef) { ensureOpen(); return getBytesWritten(zsRef.address()); } } /** {@collect.stats} * {@description.open} * Resets deflater so that a new set of input data can be processed. * Keeps current compression level and strategy settings. * {@description.close} * {@property.open} * {@property.close} */ public void reset() { synchronized (zsRef) { ensureOpen(); reset(zsRef.address()); finish = false; finished = false; off = len = 0; } } /** {@collect.stats} * {@description.open} * Closes the compressor and discards any unprocessed input. * {@description.close} * {@property.open} * This method should be called when the compressor is no longer * being used, but will also be called automatically by the * finalize() method. Once this method is called, the behavior * of the Deflater object is undefined. * {@property.close} */ public void end() { synchronized (zsRef) { long addr = zsRef.address(); zsRef.clear(); if (addr != 0) { end(addr); buf = null; } } } /** {@collect.stats} * {@description.open} * Closes the compressor when garbage is collected. * {@description.close} */ protected void finalize() { end(); } private void ensureOpen() { assert Thread.holdsLock(zsRef); if (zsRef.address() == 0) throw new NullPointerException("Deflater has been closed"); } private static native void initIDs(); private native static long init(int level, int strategy, boolean nowrap); private native static void setDictionary(long addr, byte[] b, int off, int len); private native int deflateBytes(long addr, byte[] b, int off, int len); private native static int getAdler(long addr); private native static long getBytesRead(long addr); private native static long getBytesWritten(long addr); private native static void reset(long addr); private native static void end(long addr); }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.zip; import java.io.InputStream; import java.io.IOException; import java.io.EOFException; import java.io.PushbackInputStream; /** {@collect.stats} * {@description.open} * This class implements an input stream filter for reading files in the * ZIP file format. Includes support for both compressed and uncompressed * entries. * {@description.close} * * @author David Connelly */ public class ZipInputStream extends InflaterInputStream implements ZipConstants { private ZipEntry entry; private int flag; private CRC32 crc = new CRC32(); private long remaining; private byte[] tmpbuf = new byte[512]; private static final int STORED = ZipEntry.STORED; private static final int DEFLATED = ZipEntry.DEFLATED; private boolean closed = false; // this flag is set to true after EOF has reached for // one entry private boolean entryEOF = false; /** {@collect.stats} * {@description.open} * Check to make sure that this stream has not been closed * {@description.close} */ private void ensureOpen() throws IOException { if (closed) { throw new IOException("Stream closed"); } } /** {@collect.stats} * {@description.open} * Creates a new ZIP input stream. * {@description.close} * @param in the actual input stream */ public ZipInputStream(InputStream in) { super(new PushbackInputStream(in, 512), new Inflater(true), 512); usesDefaultInflater = true; if(in == null) { throw new NullPointerException("in is null"); } } /** {@collect.stats} * {@description.open} * Reads the next ZIP file entry and positions the stream at the * beginning of the entry data. * {@description.close} * @return the next ZIP file entry, or null if there are no more entries * @exception ZipException if a ZIP file error has occurred * @exception IOException if an I/O error has occurred */ public ZipEntry getNextEntry() throws IOException { ensureOpen(); if (entry != null) { closeEntry(); } crc.reset(); inf.reset(); if ((entry = readLOC()) == null) { return null; } if (entry.method == STORED) { remaining = entry.size; } entryEOF = false; return entry; } /** {@collect.stats} * {@description.open} * Closes the current ZIP entry and positions the stream for reading the * next entry. * {@description.close} * @exception ZipException if a ZIP file error has occurred * @exception IOException if an I/O error has occurred */ public void closeEntry() throws IOException { ensureOpen(); while (read(tmpbuf, 0, tmpbuf.length) != -1) ; entryEOF = true; } /** {@collect.stats} * {@description.open} * Returns 0 after EOF has reached for the current entry data, * otherwise always return 1. * <p> * Programs should not count on this method to return the actual number * of bytes that could be read without blocking. * {@description.close} * * @return 1 before EOF and 0 after EOF has reached for current entry. * @exception IOException if an I/O error occurs. * */ public int available() throws IOException { ensureOpen(); if (entryEOF) { return 0; } else { return 1; } } /** {@collect.stats} * {@description.open} * Reads from the current ZIP entry into an array of bytes. * If <code>len</code> is not zero, the method * blocks until some input is available; otherwise, no * bytes are read and <code>0</code> is returned. * {@description.close} * @param b the buffer into which the data is read * @param off the start offset in the destination array <code>b</code> * @param len the maximum number of bytes read * @return the actual number of bytes read, or -1 if the end of the * entry is reached * @exception NullPointerException If <code>b</code> is <code>null</code>. * @exception IndexOutOfBoundsException If <code>off</code> is negative, * <code>len</code> is negative, or <code>len</code> is greater than * <code>b.length - off</code> * @exception ZipException if a ZIP file error has occurred * @exception IOException if an I/O error has occurred */ public int read(byte[] b, int off, int len) throws IOException { ensureOpen(); if (off < 0 || len < 0 || off > b.length - len) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } if (entry == null) { return -1; } switch (entry.method) { case DEFLATED: len = super.read(b, off, len); if (len == -1) { readEnd(entry); entryEOF = true; entry = null; } else { crc.update(b, off, len); } return len; case STORED: if (remaining <= 0) { entryEOF = true; entry = null; return -1; } if (len > remaining) { len = (int)remaining; } len = in.read(b, off, len); if (len == -1) { throw new ZipException("unexpected EOF"); } crc.update(b, off, len); remaining -= len; if (remaining == 0 && entry.crc != crc.getValue()) { throw new ZipException( "invalid entry CRC (expected 0x" + Long.toHexString(entry.crc) + " but got 0x" + Long.toHexString(crc.getValue()) + ")"); } return len; default: throw new ZipException("invalid compression method"); } } /** {@collect.stats} * {@description.open} * Skips specified number of bytes in the current ZIP entry. * {@description.close} * @param n the number of bytes to skip * @return the actual number of bytes skipped * @exception ZipException if a ZIP file error has occurred * @exception IOException if an I/O error has occurred * @exception IllegalArgumentException if n < 0 */ public long skip(long n) throws IOException { if (n < 0) { throw new IllegalArgumentException("negative skip length"); } ensureOpen(); int max = (int)Math.min(n, Integer.MAX_VALUE); int total = 0; while (total < max) { int len = max - total; if (len > tmpbuf.length) { len = tmpbuf.length; } len = read(tmpbuf, 0, len); if (len == -1) { entryEOF = true; break; } total += len; } return total; } /** {@collect.stats} * {@description.open} * Closes this input stream and releases any system resources associated * with the stream. * {@description.close} * @exception IOException if an I/O error has occurred */ public void close() throws IOException { if (!closed) { super.close(); closed = true; } } private byte[] b = new byte[256]; /* * Reads local file (LOC) header for next entry. */ private ZipEntry readLOC() throws IOException { try { readFully(tmpbuf, 0, LOCHDR); } catch (EOFException e) { return null; } if (get32(tmpbuf, 0) != LOCSIG) { return null; } // get the entry name and create the ZipEntry first int len = get16(tmpbuf, LOCNAM); int blen = b.length; if (len > blen) { do blen = blen * 2; while (len > blen); b = new byte[blen]; } readFully(b, 0, len); ZipEntry e = createZipEntry(getUTF8String(b, 0, len)); // now get the remaining fields for the entry flag = get16(tmpbuf, LOCFLG); if ((flag & 1) == 1) { throw new ZipException("encrypted ZIP entry not supported"); } e.method = get16(tmpbuf, LOCHOW); e.time = get32(tmpbuf, LOCTIM); if ((flag & 8) == 8) { /* "Data Descriptor" present */ if (e.method != DEFLATED) { throw new ZipException( "only DEFLATED entries can have EXT descriptor"); } } else { e.crc = get32(tmpbuf, LOCCRC); e.csize = get32(tmpbuf, LOCSIZ); e.size = get32(tmpbuf, LOCLEN); } len = get16(tmpbuf, LOCEXT); if (len > 0) { byte[] bb = new byte[len]; readFully(bb, 0, len); e.setExtra(bb); } return e; } /* * Fetches a UTF8-encoded String from the specified byte array. */ private static String getUTF8String(byte[] b, int off, int len) { // First, count the number of characters in the sequence int count = 0; int max = off + len; int i = off; while (i < max) { int c = b[i++] & 0xff; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx count++; break; case 12: case 13: // 110xxxxx 10xxxxxx if ((b[i++] & 0xc0) != 0x80) { throw new IllegalArgumentException(); } count++; break; case 14: // 1110xxxx 10xxxxxx 10xxxxxx if (((b[i++] & 0xc0) != 0x80) || ((b[i++] & 0xc0) != 0x80)) { throw new IllegalArgumentException(); } count++; break; default: // 10xxxxxx, 1111xxxx throw new IllegalArgumentException(); } } if (i != max) { throw new IllegalArgumentException(); } // Now decode the characters... char[] cs = new char[count]; i = 0; while (off < max) { int c = b[off++] & 0xff; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx cs[i++] = (char)c; break; case 12: case 13: // 110xxxxx 10xxxxxx cs[i++] = (char)(((c & 0x1f) << 6) | (b[off++] & 0x3f)); break; case 14: // 1110xxxx 10xxxxxx 10xxxxxx int t = (b[off++] & 0x3f) << 6; cs[i++] = (char)(((c & 0x0f) << 12) | t | (b[off++] & 0x3f)); break; default: // 10xxxxxx, 1111xxxx throw new IllegalArgumentException(); } } return new String(cs, 0, count); } /** {@collect.stats} * {@description.open} * Creates a new <code>ZipEntry</code> object for the specified * entry name. * {@description.close} * * @param name the ZIP file entry name * @return the ZipEntry just created */ protected ZipEntry createZipEntry(String name) { return new ZipEntry(name); } /* * Reads end of deflated entry as well as EXT descriptor if present. */ private void readEnd(ZipEntry e) throws IOException { int n = inf.getRemaining(); if (n > 0) { ((PushbackInputStream)in).unread(buf, len - n, n); } if ((flag & 8) == 8) { /* "Data Descriptor" present */ readFully(tmpbuf, 0, EXTHDR); long sig = get32(tmpbuf, 0); if (sig != EXTSIG) { // no EXTSIG present e.crc = sig; e.csize = get32(tmpbuf, EXTSIZ - EXTCRC); e.size = get32(tmpbuf, EXTLEN - EXTCRC); ((PushbackInputStream)in).unread( tmpbuf, EXTHDR - EXTCRC - 1, EXTCRC); } else { e.crc = get32(tmpbuf, EXTCRC); e.csize = get32(tmpbuf, EXTSIZ); e.size = get32(tmpbuf, EXTLEN); } } if (e.size != inf.getBytesWritten()) { throw new ZipException( "invalid entry size (expected " + e.size + " but got " + inf.getBytesWritten() + " bytes)"); } if (e.csize != inf.getBytesRead()) { throw new ZipException( "invalid entry compressed size (expected " + e.csize + " but got " + inf.getBytesRead() + " bytes)"); } if (e.crc != crc.getValue()) { throw new ZipException( "invalid entry CRC (expected 0x" + Long.toHexString(e.crc) + " but got 0x" + Long.toHexString(crc.getValue()) + ")"); } } /* * Reads bytes, blocking until all bytes are read. */ private void readFully(byte[] b, int off, int len) throws IOException { while (len > 0) { int n = in.read(b, off, len); if (n == -1) { throw new EOFException(); } off += n; len -= n; } } /* * Fetches unsigned 16-bit value from byte array at specified offset. * The bytes are assumed to be in Intel (little-endian) byte order. */ private static final int get16(byte b[], int off) { return (b[off] & 0xff) | ((b[off+1] & 0xff) << 8); } /* * Fetches unsigned 32-bit value from byte array at specified offset. * The bytes are assumed to be in Intel (little-endian) byte order. */ private static final long get32(byte b[], int off) { return get16(b, off) | ((long)get16(b, off+2) << 16); } }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** {@collect.stats} * Provides classes for performing arbitrary-precision integer * arithmetic ({@code BigInteger}) and arbitrary-precision decimal * arithmetic ({@code BigDecimal}). {@code BigInteger} is analogous * to the primitive integer types except that it provides arbitrary * precision, hence operations on {@code BigInteger}s do not overflow * or lose precision. In addition to standard arithmetic operations, * {@code BigInteger} provides modular arithmetic, GCD calculation, * primality testing, prime generation, bit manipulation, and a few * other miscellaneous operations. * * {@code BigDecimal} provides arbitrary-precision signed decimal * numbers suitable for currency calculations and the like. {@code * BigDecimal} gives the user complete control over rounding behavior, * allowing the user to choose from a comprehensive set of eight * rounding modes. * * @since JDK1.1 */ package java.math;
Java
/* * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Portions Copyright IBM Corporation, 1997, 2001. All Rights Reserved. */ package java.math; import java.io.*; /** {@collect.stats} * Immutable objects which encapsulate the context settings which * describe certain rules for numerical operators, such as those * implemented by the {@link BigDecimal} class. * * <p>The base-independent settings are: * <ol> * <li>{@code precision}: * the number of digits to be used for an operation; results are * rounded to this precision * * <li>{@code roundingMode}: * a {@link RoundingMode} object which specifies the algorithm to be * used for rounding. * </ol> * * @see BigDecimal * @see RoundingMode * @author Mike Cowlishaw * @author Joseph D. Darcy * @since 1.5 */ public final class MathContext implements Serializable { /* ----- Constants ----- */ // defaults for constructors private static final int DEFAULT_DIGITS = 9; private static final RoundingMode DEFAULT_ROUNDINGMODE = RoundingMode.HALF_UP; // Smallest values for digits (Maximum is Integer.MAX_VALUE) private static final int MIN_DIGITS = 0; // Serialization version private static final long serialVersionUID = 5579720004786848255L; /* ----- Public Properties ----- */ /** {@collect.stats} * A {@code MathContext} object whose settings have the values * required for unlimited precision arithmetic. * The values of the settings are: * <code> * precision=0 roundingMode=HALF_UP * </code> */ public static final MathContext UNLIMITED = new MathContext(0, RoundingMode.HALF_UP); /** {@collect.stats} * A {@code MathContext} object with a precision setting * matching the IEEE 754R Decimal32 format, 7 digits, and a * rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the * IEEE 754R default. */ public static final MathContext DECIMAL32 = new MathContext(7, RoundingMode.HALF_EVEN); /** {@collect.stats} * A {@code MathContext} object with a precision setting * matching the IEEE 754R Decimal64 format, 16 digits, and a * rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the * IEEE 754R default. */ public static final MathContext DECIMAL64 = new MathContext(16, RoundingMode.HALF_EVEN); /** {@collect.stats} * A {@code MathContext} object with a precision setting * matching the IEEE 754R Decimal128 format, 34 digits, and a * rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the * IEEE 754R default. */ public static final MathContext DECIMAL128 = new MathContext(34, RoundingMode.HALF_EVEN); /* ----- Shared Properties ----- */ /** {@collect.stats} * The number of digits to be used for an operation. A value of 0 * indicates that unlimited precision (as many digits as are * required) will be used. Note that leading zeros (in the * coefficient of a number) are never significant. * * <p>{@code precision} will always be non-negative. * * @serial */ final int precision; /** {@collect.stats} * The rounding algorithm to be used for an operation. * * @see RoundingMode * @serial */ final RoundingMode roundingMode; /* ----- Constructors ----- */ /** {@collect.stats} * Constructs a new {@code MathContext} with the specified * precision and the {@link RoundingMode#HALF_UP HALF_UP} rounding * mode. * * @param setPrecision The non-negative {@code int} precision setting. * @throws IllegalArgumentException if the {@code setPrecision} parameter is less * than zero. */ public MathContext(int setPrecision) { this(setPrecision, DEFAULT_ROUNDINGMODE); return; } /** {@collect.stats} * Constructs a new {@code MathContext} with a specified * precision and rounding mode. * * @param setPrecision The non-negative {@code int} precision setting. * @param setRoundingMode The rounding mode to use. * @throws IllegalArgumentException if the {@code setPrecision} parameter is less * than zero. * @throws NullPointerException if the rounding mode argument is {@code null} */ public MathContext(int setPrecision, RoundingMode setRoundingMode) { if (setPrecision < MIN_DIGITS) throw new IllegalArgumentException("Digits < 0"); if (setRoundingMode == null) throw new NullPointerException("null RoundingMode"); precision = setPrecision; roundingMode = setRoundingMode; return; } /** {@collect.stats} * Constructs a new {@code MathContext} from a string. * * The string must be in the same format as that produced by the * {@link #toString} method. * * <p>An {@code IllegalArgumentException} is thrown if the precision * section of the string is out of range ({@code < 0}) or the string is * not in the format created by the {@link #toString} method. * * @param val The string to be parsed * @throws IllegalArgumentException if the precision section is out of range * or of incorrect format * @throws NullPointerException if the argument is {@code null} */ public MathContext(String val) { boolean bad = false; int setPrecision; if (val == null) throw new NullPointerException("null String"); try { // any error here is a string format problem if (!val.startsWith("precision=")) throw new RuntimeException(); int fence = val.indexOf(' '); // could be -1 int off = 10; // where value starts setPrecision = Integer.parseInt(val.substring(10, fence)); if (!val.startsWith("roundingMode=", fence+1)) throw new RuntimeException(); off = fence + 1 + 13; String str = val.substring(off, val.length()); roundingMode = RoundingMode.valueOf(str); } catch (RuntimeException re) { throw new IllegalArgumentException("bad string format"); } if (setPrecision < MIN_DIGITS) throw new IllegalArgumentException("Digits < 0"); // the other parameters cannot be invalid if we got here precision = setPrecision; } /** {@collect.stats} * Returns the {@code precision} setting. * This value is always non-negative. * * @return an {@code int} which is the value of the {@code precision} * setting */ public int getPrecision() { return precision; } /** {@collect.stats} * Returns the roundingMode setting. * This will be one of * {@link RoundingMode#CEILING}, * {@link RoundingMode#DOWN}, * {@link RoundingMode#FLOOR}, * {@link RoundingMode#HALF_DOWN}, * {@link RoundingMode#HALF_EVEN}, * {@link RoundingMode#HALF_UP}, * {@link RoundingMode#UNNECESSARY}, or * {@link RoundingMode#UP}. * * @return a {@code RoundingMode} object which is the value of the * {@code roundingMode} setting */ public RoundingMode getRoundingMode() { return roundingMode; } /** {@collect.stats} * Compares this {@code MathContext} with the specified * {@code Object} for equality. * * @param x {@code Object} to which this {@code MathContext} is to * be compared. * @return {@code true} if and only if the specified {@code Object} is * a {@code MathContext} object which has exactly the same * settings as this object */ public boolean equals(Object x){ MathContext mc; if (!(x instanceof MathContext)) return false; mc = (MathContext) x; return mc.precision == this.precision && mc.roundingMode == this.roundingMode; // no need for .equals() } /** {@collect.stats} * Returns the hash code for this {@code MathContext}. * * @return hash code for this {@code MathContext} */ public int hashCode() { return this.precision + roundingMode.hashCode() * 59; } /** {@collect.stats} * Returns the string representation of this {@code MathContext}. * The {@code String} returned represents the settings of the * {@code MathContext} object as two space-delimited words * (separated by a single space character, <tt>'&#92;u0020'</tt>, * and with no leading or trailing white space), as follows: * <ol> * <li> * The string {@code "precision="}, immediately followed * by the value of the precision setting as a numeric string as if * generated by the {@link Integer#toString(int) Integer.toString} * method. * * <li> * The string {@code "roundingMode="}, immediately * followed by the value of the {@code roundingMode} setting as a * word. This word will be the same as the name of the * corresponding public constant in the {@link RoundingMode} * enum. * </ol> * <p> * For example: * <pre> * precision=9 roundingMode=HALF_UP * </pre> * * Additional words may be appended to the result of * {@code toString} in the future if more properties are added to * this class. * * @return a {@code String} representing the context settings */ public java.lang.String toString() { return "precision=" + precision + " " + "roundingMode=" + roundingMode.toString(); } // Private methods /** {@collect.stats} * Reconstitute the {@code MathContext} instance from a stream (that is, * deserialize it). * * @param s the stream being read. */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); // read in all fields // validate possibly bad fields if (precision < MIN_DIGITS) { String message = "MathContext: invalid digits in stream"; throw new java.io.StreamCorruptedException(message); } if (roundingMode == null) { String message = "MathContext: null roundingMode in stream"; throw new java.io.StreamCorruptedException(message); } } }
Java
/* * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.math; /** {@collect.stats} * A simple bit sieve used for finding prime number candidates. Allows setting * and clearing of bits in a storage array. The size of the sieve is assumed to * be constant to reduce overhead. All the bits of a new bitSieve are zero, and * bits are removed from it by setting them. * * To reduce storage space and increase efficiency, no even numbers are * represented in the sieve (each bit in the sieve represents an odd number). * The relationship between the index of a bit and the number it represents is * given by * N = offset + (2*index + 1); * Where N is the integer represented by a bit in the sieve, offset is some * even integer offset indicating where the sieve begins, and index is the * index of a bit in the sieve array. * * @see BigInteger * @author Michael McCloskey * @since 1.3 */ class BitSieve { /** {@collect.stats} * Stores the bits in this bitSieve. */ private long bits[]; /** {@collect.stats} * Length is how many bits this sieve holds. */ private int length; /** {@collect.stats} * A small sieve used to filter out multiples of small primes in a search * sieve. */ private static BitSieve smallSieve = new BitSieve(); /** {@collect.stats} * Construct a "small sieve" with a base of 0. This constructor is * used internally to generate the set of "small primes" whose multiples * are excluded from sieves generated by the main (package private) * constructor, BitSieve(BigInteger base, int searchLen). The length * of the sieve generated by this constructor was chosen for performance; * it controls a tradeoff between how much time is spent constructing * other sieves, and how much time is wasted testing composite candidates * for primality. The length was chosen experimentally to yield good * performance. */ private BitSieve() { length = 150 * 64; bits = new long[(unitIndex(length - 1) + 1)]; // Mark 1 as composite set(0); int nextIndex = 1; int nextPrime = 3; // Find primes and remove their multiples from sieve do { sieveSingle(length, nextIndex + nextPrime, nextPrime); nextIndex = sieveSearch(length, nextIndex + 1); nextPrime = 2*nextIndex + 1; } while((nextIndex > 0) && (nextPrime < length)); } /** {@collect.stats} * Construct a bit sieve of searchLen bits used for finding prime number * candidates. The new sieve begins at the specified base, which must * be even. */ BitSieve(BigInteger base, int searchLen) { /* * Candidates are indicated by clear bits in the sieve. As a candidates * nonprimality is calculated, a bit is set in the sieve to eliminate * it. To reduce storage space and increase efficiency, no even numbers * are represented in the sieve (each bit in the sieve represents an * odd number). */ bits = new long[(unitIndex(searchLen-1) + 1)]; length = searchLen; int start = 0; int step = smallSieve.sieveSearch(smallSieve.length, start); int convertedStep = (step *2) + 1; // Construct the large sieve at an even offset specified by base MutableBigInteger b = new MutableBigInteger(base); MutableBigInteger q = new MutableBigInteger(); do { // Calculate base mod convertedStep start = b.divideOneWord(convertedStep, q); // Take each multiple of step out of sieve start = convertedStep - start; if (start%2 == 0) start += convertedStep; sieveSingle(searchLen, (start-1)/2, convertedStep); // Find next prime from small sieve step = smallSieve.sieveSearch(smallSieve.length, step+1); convertedStep = (step *2) + 1; } while (step > 0); } /** {@collect.stats} * Given a bit index return unit index containing it. */ private static int unitIndex(int bitIndex) { return bitIndex >>> 6; } /** {@collect.stats} * Return a unit that masks the specified bit in its unit. */ private static long bit(int bitIndex) { return 1L << (bitIndex & ((1<<6) - 1)); } /** {@collect.stats} * Get the value of the bit at the specified index. */ private boolean get(int bitIndex) { int unitIndex = unitIndex(bitIndex); return ((bits[unitIndex] & bit(bitIndex)) != 0); } /** {@collect.stats} * Set the bit at the specified index. */ private void set(int bitIndex) { int unitIndex = unitIndex(bitIndex); bits[unitIndex] |= bit(bitIndex); } /** {@collect.stats} * This method returns the index of the first clear bit in the search * array that occurs at or after start. It will not search past the * specified limit. It returns -1 if there is no such clear bit. */ private int sieveSearch(int limit, int start) { if (start >= limit) return -1; int index = start; do { if (!get(index)) return index; index++; } while(index < limit-1); return -1; } /** {@collect.stats} * Sieve a single set of multiples out of the sieve. Begin to remove * multiples of the specified step starting at the specified start index, * up to the specified limit. */ private void sieveSingle(int limit, int start, int step) { while(start < limit) { set(start); start += step; } } /** {@collect.stats} * Test probable primes in the sieve and return successful candidates. */ BigInteger retrieve(BigInteger initValue, int certainty, java.util.Random random) { // Examine the sieve one long at a time to find possible primes int offset = 1; for (int i=0; i<bits.length; i++) { long nextLong = ~bits[i]; for (int j=0; j<64; j++) { if ((nextLong & 1) == 1) { BigInteger candidate = initValue.add( BigInteger.valueOf(offset)); if (candidate.primeToCertainty(certainty, random)) return candidate; } nextLong >>>= 1; offset+=2; } } return null; } }
Java
/* * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Portions Copyright (c) 1995 Colin Plumb. All rights reserved. */ package java.math; import java.util.Random; import java.io.*; /** {@collect.stats} * Immutable arbitrary-precision integers. All operations behave as if * BigIntegers were represented in two's-complement notation (like Java's * primitive integer types). BigInteger provides analogues to all of Java's * primitive integer operators, and all relevant methods from java.lang.Math. * Additionally, BigInteger provides operations for modular arithmetic, GCD * calculation, primality testing, prime generation, bit manipulation, * and a few other miscellaneous operations. * * <p>Semantics of arithmetic operations exactly mimic those of Java's integer * arithmetic operators, as defined in <i>The Java Language Specification</i>. * For example, division by zero throws an {@code ArithmeticException}, and * division of a negative by a positive yields a negative (or zero) remainder. * All of the details in the Spec concerning overflow are ignored, as * BigIntegers are made as large as necessary to accommodate the results of an * operation. * * <p>Semantics of shift operations extend those of Java's shift operators * to allow for negative shift distances. A right-shift with a negative * shift distance results in a left shift, and vice-versa. The unsigned * right shift operator ({@code >>>}) is omitted, as this operation makes * little sense in combination with the "infinite word size" abstraction * provided by this class. * * <p>Semantics of bitwise logical operations exactly mimic those of Java's * bitwise integer operators. The binary operators ({@code and}, * {@code or}, {@code xor}) implicitly perform sign extension on the shorter * of the two operands prior to performing the operation. * * <p>Comparison operations perform signed integer comparisons, analogous to * those performed by Java's relational and equality operators. * * <p>Modular arithmetic operations are provided to compute residues, perform * exponentiation, and compute multiplicative inverses. These methods always * return a non-negative result, between {@code 0} and {@code (modulus - 1)}, * inclusive. * * <p>Bit operations operate on a single bit of the two's-complement * representation of their operand. If necessary, the operand is sign- * extended so that it contains the designated bit. None of the single-bit * operations can produce a BigInteger with a different sign from the * BigInteger being operated on, as they affect only a single bit, and the * "infinite word size" abstraction provided by this class ensures that there * are infinitely many "virtual sign bits" preceding each BigInteger. * * <p>For the sake of brevity and clarity, pseudo-code is used throughout the * descriptions of BigInteger methods. The pseudo-code expression * {@code (i + j)} is shorthand for "a BigInteger whose value is * that of the BigInteger {@code i} plus that of the BigInteger {@code j}." * The pseudo-code expression {@code (i == j)} is shorthand for * "{@code true} if and only if the BigInteger {@code i} represents the same * value as the BigInteger {@code j}." Other pseudo-code expressions are * interpreted similarly. * * <p>All methods and constructors in this class throw * {@code NullPointerException} when passed * a null object reference for any input parameter. * * @see BigDecimal * @author Josh Bloch * @author Michael McCloskey * @since JDK1.1 */ public class BigInteger extends Number implements Comparable<BigInteger> { /** {@collect.stats} * The signum of this BigInteger: -1 for negative, 0 for zero, or * 1 for positive. Note that the BigInteger zero <i>must</i> have * a signum of 0. This is necessary to ensures that there is exactly one * representation for each BigInteger value. * * @serial */ final int signum; /** {@collect.stats} * The magnitude of this BigInteger, in <i>big-endian</i> order: the * zeroth element of this array is the most-significant int of the * magnitude. The magnitude must be "minimal" in that the most-significant * int ({@code mag[0]}) must be non-zero. This is necessary to * ensure that there is exactly one representation for each BigInteger * value. Note that this implies that the BigInteger zero has a * zero-length mag array. */ final int[] mag; // These "redundant fields" are initialized with recognizable nonsense // values, and cached the first time they are needed (or never, if they // aren't needed). /** {@collect.stats} * One plus the bitCount of this BigInteger. Zeros means unitialized. * * @serial * @see #bitCount * @deprecated Deprecated since logical value is offset from stored * value and correction factor is applied in accessor method. */ @Deprecated private int bitCount; /** {@collect.stats} * One plus the bitLength of this BigInteger. Zeros means unitialized. * (either value is acceptable). * * @serial * @see #bitLength() * @deprecated Deprecated since logical value is offset from stored * value and correction factor is applied in accessor method. */ @Deprecated private int bitLength; /** {@collect.stats} * Two plus the lowest set bit of this BigInteger, as returned by * getLowestSetBit(). * * @serial * @see #getLowestSetBit * @deprecated Deprecated since logical value is offset from stored * value and correction factor is applied in accessor method. */ @Deprecated private int lowestSetBit; /** {@collect.stats} * Two plus the index of the lowest-order int in the magnitude of this * BigInteger that contains a nonzero int, or -2 (either value is acceptable). * The least significant int has int-number 0, the next int in order of * increasing significance has int-number 1, and so forth. * @deprecated Deprecated since logical value is offset from stored * value and correction factor is applied in accessor method. */ @Deprecated private int firstNonzeroIntNum; /** {@collect.stats} * This mask is used to obtain the value of an int as if it were unsigned. */ final static long LONG_MASK = 0xffffffffL; //Constructors /** {@collect.stats} * Translates a byte array containing the two's-complement binary * representation of a BigInteger into a BigInteger. The input array is * assumed to be in <i>big-endian</i> byte-order: the most significant * byte is in the zeroth element. * * @param val big-endian two's-complement binary representation of * BigInteger. * @throws NumberFormatException {@code val} is zero bytes long. */ public BigInteger(byte[] val) { if (val.length == 0) throw new NumberFormatException("Zero length BigInteger"); if (val[0] < 0) { mag = makePositive(val); signum = -1; } else { mag = stripLeadingZeroBytes(val); signum = (mag.length == 0 ? 0 : 1); } } /** {@collect.stats} * This private constructor translates an int array containing the * two's-complement binary representation of a BigInteger into a * BigInteger. The input array is assumed to be in <i>big-endian</i> * int-order: the most significant int is in the zeroth element. */ private BigInteger(int[] val) { if (val.length == 0) throw new NumberFormatException("Zero length BigInteger"); if (val[0] < 0) { mag = makePositive(val); signum = -1; } else { mag = trustedStripLeadingZeroInts(val); signum = (mag.length == 0 ? 0 : 1); } } /** {@collect.stats} * Translates the sign-magnitude representation of a BigInteger into a * BigInteger. The sign is represented as an integer signum value: -1 for * negative, 0 for zero, or 1 for positive. The magnitude is a byte array * in <i>big-endian</i> byte-order: the most significant byte is in the * zeroth element. A zero-length magnitude array is permissible, and will * result in a BigInteger value of 0, whether signum is -1, 0 or 1. * * @param signum signum of the number (-1 for negative, 0 for zero, 1 * for positive). * @param magnitude big-endian binary representation of the magnitude of * the number. * @throws NumberFormatException {@code signum} is not one of the three * legal values (-1, 0, and 1), or {@code signum} is 0 and * {@code magnitude} contains one or more non-zero bytes. */ public BigInteger(int signum, byte[] magnitude) { this.mag = stripLeadingZeroBytes(magnitude); if (signum < -1 || signum > 1) throw(new NumberFormatException("Invalid signum value")); if (this.mag.length==0) { this.signum = 0; } else { if (signum == 0) throw(new NumberFormatException("signum-magnitude mismatch")); this.signum = signum; } } /** {@collect.stats} * A constructor for internal use that translates the sign-magnitude * representation of a BigInteger into a BigInteger. It checks the * arguments and copies the magnitude so this constructor would be * safe for external use. */ private BigInteger(int signum, int[] magnitude) { this.mag = stripLeadingZeroInts(magnitude); if (signum < -1 || signum > 1) throw(new NumberFormatException("Invalid signum value")); if (this.mag.length==0) { this.signum = 0; } else { if (signum == 0) throw(new NumberFormatException("signum-magnitude mismatch")); this.signum = signum; } } /** {@collect.stats} * Translates the String representation of a BigInteger in the * specified radix into a BigInteger. The String representation * consists of an optional minus followed by a sequence of one or * more digits in the specified radix. The character-to-digit * mapping is provided by {@code Character.digit}. The String may * not contain any extraneous characters (whitespace, for * example). * * @param val String representation of BigInteger. * @param radix radix to be used in interpreting {@code val}. * @throws NumberFormatException {@code val} is not a valid representation * of a BigInteger in the specified radix, or {@code radix} is * outside the range from {@link Character#MIN_RADIX} to * {@link Character#MAX_RADIX}, inclusive. * @see Character#digit */ public BigInteger(String val, int radix) { int cursor = 0, numDigits; int len = val.length(); if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) throw new NumberFormatException("Radix out of range"); if (val.length() == 0) throw new NumberFormatException("Zero length BigInteger"); // Check for at most one leading sign int sign = 1; int index = val.lastIndexOf('-'); if (index != -1) { if (index == 0 ) { if (val.length() == 1) throw new NumberFormatException("Zero length BigInteger"); sign = -1; cursor = 1; } else { throw new NumberFormatException("Illegal embedded sign character"); } } // Skip leading zeros and compute number of digits in magnitude while (cursor < len && Character.digit(val.charAt(cursor), radix) == 0) cursor++; if (cursor == len) { signum = 0; mag = ZERO.mag; return; } numDigits = len - cursor; signum = sign; // Pre-allocate array of expected size. May be too large but can // never be too small. Typically exact. int numBits = (int)(((numDigits * bitsPerDigit[radix]) >>> 10) + 1); int numWords = (numBits + 31) >>> 5; int[] magnitude = new int[numWords]; // Process first (potentially short) digit group int firstGroupLen = numDigits % digitsPerInt[radix]; if (firstGroupLen == 0) firstGroupLen = digitsPerInt[radix]; String group = val.substring(cursor, cursor += firstGroupLen); magnitude[numWords - 1] = Integer.parseInt(group, radix); if (magnitude[numWords - 1] < 0) throw new NumberFormatException("Illegal digit"); // Process remaining digit groups int superRadix = intRadix[radix]; int groupVal = 0; while (cursor < val.length()) { group = val.substring(cursor, cursor += digitsPerInt[radix]); groupVal = Integer.parseInt(group, radix); if (groupVal < 0) throw new NumberFormatException("Illegal digit"); destructiveMulAdd(magnitude, superRadix, groupVal); } // Required for cases where the array was overallocated. mag = trustedStripLeadingZeroInts(magnitude); } // Constructs a new BigInteger using a char array with radix=10 BigInteger(char[] val) { int cursor = 0, numDigits; int len = val.length; // Check for leading minus sign int sign = 1; if (val[0] == '-') { if (len == 1) throw new NumberFormatException("Zero length BigInteger"); sign = -1; cursor = 1; } // Skip leading zeros and compute number of digits in magnitude while (cursor < len && Character.digit(val[cursor], 10) == 0) cursor++; if (cursor == len) { signum = 0; mag = ZERO.mag; return; } numDigits = len - cursor; signum = sign; // Pre-allocate array of expected size int numWords; if (len < 10) { numWords = 1; } else { int numBits = (int)(((numDigits * bitsPerDigit[10]) >>> 10) + 1); numWords = (numBits + 31) >>> 5; } int[] magnitude = new int[numWords]; // Process first (potentially short) digit group int firstGroupLen = numDigits % digitsPerInt[10]; if (firstGroupLen == 0) firstGroupLen = digitsPerInt[10]; magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen); // Process remaining digit groups while (cursor < len) { int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]); destructiveMulAdd(magnitude, intRadix[10], groupVal); } mag = trustedStripLeadingZeroInts(magnitude); } // Create an integer with the digits between the two indexes // Assumes start < end. The result may be negative, but it // is to be treated as an unsigned value. private int parseInt(char[] source, int start, int end) { int result = Character.digit(source[start++], 10); if (result == -1) throw new NumberFormatException(new String(source)); for (int index = start; index<end; index++) { int nextVal = Character.digit(source[index], 10); if (nextVal == -1) throw new NumberFormatException(new String(source)); result = 10*result + nextVal; } return result; } // bitsPerDigit in the given radix times 1024 // Rounded up to avoid underallocation. private static long bitsPerDigit[] = { 0, 0, 1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672, 3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633, 4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210, 5253, 5295}; // Multiply x array times word y in place, and add word z private static void destructiveMulAdd(int[] x, int y, int z) { // Perform the multiplication word by word long ylong = y & LONG_MASK; long zlong = z & LONG_MASK; int len = x.length; long product = 0; long carry = 0; for (int i = len-1; i >= 0; i--) { product = ylong * (x[i] & LONG_MASK) + carry; x[i] = (int)product; carry = product >>> 32; } // Perform the addition long sum = (x[len-1] & LONG_MASK) + zlong; x[len-1] = (int)sum; carry = sum >>> 32; for (int i = len-2; i >= 0; i--) { sum = (x[i] & LONG_MASK) + carry; x[i] = (int)sum; carry = sum >>> 32; } } /** {@collect.stats} * Translates the decimal String representation of a BigInteger into a * BigInteger. The String representation consists of an optional minus * sign followed by a sequence of one or more decimal digits. The * character-to-digit mapping is provided by {@code Character.digit}. * The String may not contain any extraneous characters (whitespace, for * example). * * @param val decimal String representation of BigInteger. * @throws NumberFormatException {@code val} is not a valid representation * of a BigInteger. * @see Character#digit */ public BigInteger(String val) { this(val, 10); } /** {@collect.stats} * Constructs a randomly generated BigInteger, uniformly distributed over * the range {@code 0} to (2<sup>{@code numBits}</sup> - 1), inclusive. * The uniformity of the distribution assumes that a fair source of random * bits is provided in {@code rnd}. Note that this constructor always * constructs a non-negative BigInteger. * * @param numBits maximum bitLength of the new BigInteger. * @param rnd source of randomness to be used in computing the new * BigInteger. * @throws IllegalArgumentException {@code numBits} is negative. * @see #bitLength() */ public BigInteger(int numBits, Random rnd) { this(1, randomBits(numBits, rnd)); } private static byte[] randomBits(int numBits, Random rnd) { if (numBits < 0) throw new IllegalArgumentException("numBits must be non-negative"); int numBytes = (int)(((long)numBits+7)/8); // avoid overflow byte[] randomBits = new byte[numBytes]; // Generate random bytes and mask out any excess bits if (numBytes > 0) { rnd.nextBytes(randomBits); int excessBits = 8*numBytes - numBits; randomBits[0] &= (1 << (8-excessBits)) - 1; } return randomBits; } /** {@collect.stats} * Constructs a randomly generated positive BigInteger that is probably * prime, with the specified bitLength. * * <p>It is recommended that the {@link #probablePrime probablePrime} * method be used in preference to this constructor unless there * is a compelling need to specify a certainty. * * @param bitLength bitLength of the returned BigInteger. * @param certainty a measure of the uncertainty that the caller is * willing to tolerate. The probability that the new BigInteger * represents a prime number will exceed * (1 - 1/2<sup>{@code certainty}</sup>). The execution time of * this constructor is proportional to the value of this parameter. * @param rnd source of random bits used to select candidates to be * tested for primality. * @throws ArithmeticException {@code bitLength < 2}. * @see #bitLength() */ public BigInteger(int bitLength, int certainty, Random rnd) { BigInteger prime; if (bitLength < 2) throw new ArithmeticException("bitLength < 2"); // The cutoff of 95 was chosen empirically for best performance prime = (bitLength < 95 ? smallPrime(bitLength, certainty, rnd) : largePrime(bitLength, certainty, rnd)); signum = 1; mag = prime.mag; } // Minimum size in bits that the requested prime number has // before we use the large prime number generating algorithms private static final int SMALL_PRIME_THRESHOLD = 95; // Certainty required to meet the spec of probablePrime private static final int DEFAULT_PRIME_CERTAINTY = 100; /** {@collect.stats} * Returns a positive BigInteger that is probably prime, with the * specified bitLength. The probability that a BigInteger returned * by this method is composite does not exceed 2<sup>-100</sup>. * * @param bitLength bitLength of the returned BigInteger. * @param rnd source of random bits used to select candidates to be * tested for primality. * @return a BigInteger of {@code bitLength} bits that is probably prime * @throws ArithmeticException {@code bitLength < 2}. * @see #bitLength() * @since 1.4 */ public static BigInteger probablePrime(int bitLength, Random rnd) { if (bitLength < 2) throw new ArithmeticException("bitLength < 2"); // The cutoff of 95 was chosen empirically for best performance return (bitLength < SMALL_PRIME_THRESHOLD ? smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) : largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd)); } /** {@collect.stats} * Find a random number of the specified bitLength that is probably prime. * This method is used for smaller primes, its performance degrades on * larger bitlengths. * * This method assumes bitLength > 1. */ private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) { int magLen = (bitLength + 31) >>> 5; int temp[] = new int[magLen]; int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int int highMask = (highBit << 1) - 1; // Bits to keep in high int while(true) { // Construct a candidate for (int i=0; i<magLen; i++) temp[i] = rnd.nextInt(); temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length if (bitLength > 2) temp[magLen-1] |= 1; // Make odd if bitlen > 2 BigInteger p = new BigInteger(temp, 1); // Do cheap "pre-test" if applicable if (bitLength > 6) { long r = p.remainder(SMALL_PRIME_PRODUCT).longValue(); if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) || (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) || (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) continue; // Candidate is composite; try another } // All candidates of bitLength 2 and 3 are prime by this point if (bitLength < 4) return p; // Do expensive test if we survive pre-test (or it's inapplicable) if (p.primeToCertainty(certainty, rnd)) return p; } } private static final BigInteger SMALL_PRIME_PRODUCT = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41); /** {@collect.stats} * Find a random number of the specified bitLength that is probably prime. * This method is more appropriate for larger bitlengths since it uses * a sieve to eliminate most composites before using a more expensive * test. */ private static BigInteger largePrime(int bitLength, int certainty, Random rnd) { BigInteger p; p = new BigInteger(bitLength, rnd).setBit(bitLength-1); p.mag[p.mag.length-1] &= 0xfffffffe; // Use a sieve length likely to contain the next prime number int searchLen = (bitLength / 20) * 64; BitSieve searchSieve = new BitSieve(p, searchLen); BigInteger candidate = searchSieve.retrieve(p, certainty, rnd); while ((candidate == null) || (candidate.bitLength() != bitLength)) { p = p.add(BigInteger.valueOf(2*searchLen)); if (p.bitLength() != bitLength) p = new BigInteger(bitLength, rnd).setBit(bitLength-1); p.mag[p.mag.length-1] &= 0xfffffffe; searchSieve = new BitSieve(p, searchLen); candidate = searchSieve.retrieve(p, certainty, rnd); } return candidate; } /** {@collect.stats} * Returns the first integer greater than this {@code BigInteger} that * is probably prime. The probability that the number returned by this * method is composite does not exceed 2<sup>-100</sup>. This method will * never skip over a prime when searching: if it returns {@code p}, there * is no prime {@code q} such that {@code this < q < p}. * * @return the first integer greater than this {@code BigInteger} that * is probably prime. * @throws ArithmeticException {@code this < 0}. * @since 1.5 */ public BigInteger nextProbablePrime() { if (this.signum < 0) throw new ArithmeticException("start < 0: " + this); // Handle trivial cases if ((this.signum == 0) || this.equals(ONE)) return TWO; BigInteger result = this.add(ONE); // Fastpath for small numbers if (result.bitLength() < SMALL_PRIME_THRESHOLD) { // Ensure an odd number if (!result.testBit(0)) result = result.add(ONE); while(true) { // Do cheap "pre-test" if applicable if (result.bitLength() > 6) { long r = result.remainder(SMALL_PRIME_PRODUCT).longValue(); if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) || (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) || (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) { result = result.add(TWO); continue; // Candidate is composite; try another } } // All candidates of bitLength 2 and 3 are prime by this point if (result.bitLength() < 4) return result; // The expensive test if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null)) return result; result = result.add(TWO); } } // Start at previous even number if (result.testBit(0)) result = result.subtract(ONE); // Looking for the next large prime int searchLen = (result.bitLength() / 20) * 64; while(true) { BitSieve searchSieve = new BitSieve(result, searchLen); BigInteger candidate = searchSieve.retrieve(result, DEFAULT_PRIME_CERTAINTY, null); if (candidate != null) return candidate; result = result.add(BigInteger.valueOf(2 * searchLen)); } } /** {@collect.stats} * Returns {@code true} if this BigInteger is probably prime, * {@code false} if it's definitely composite. * * This method assumes bitLength > 2. * * @param certainty a measure of the uncertainty that the caller is * willing to tolerate: if the call returns {@code true} * the probability that this BigInteger is prime exceeds * {@code (1 - 1/2<sup>certainty</sup>)}. The execution time of * this method is proportional to the value of this parameter. * @return {@code true} if this BigInteger is probably prime, * {@code false} if it's definitely composite. */ boolean primeToCertainty(int certainty, Random random) { int rounds = 0; int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2; // The relationship between the certainty and the number of rounds // we perform is given in the draft standard ANSI X9.80, "PRIME // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES". int sizeInBits = this.bitLength(); if (sizeInBits < 100) { rounds = 50; rounds = n < rounds ? n : rounds; return passesMillerRabin(rounds, random); } if (sizeInBits < 256) { rounds = 27; } else if (sizeInBits < 512) { rounds = 15; } else if (sizeInBits < 768) { rounds = 8; } else if (sizeInBits < 1024) { rounds = 4; } else { rounds = 2; } rounds = n < rounds ? n : rounds; return passesMillerRabin(rounds, random) && passesLucasLehmer(); } /** {@collect.stats} * Returns true iff this BigInteger is a Lucas-Lehmer probable prime. * * The following assumptions are made: * This BigInteger is a positive, odd number. */ private boolean passesLucasLehmer() { BigInteger thisPlusOne = this.add(ONE); // Step 1 int d = 5; while (jacobiSymbol(d, this) != -1) { // 5, -7, 9, -11, ... d = (d<0) ? Math.abs(d)+2 : -(d+2); } // Step 2 BigInteger u = lucasLehmerSequence(d, thisPlusOne, this); // Step 3 return u.mod(this).equals(ZERO); } /** {@collect.stats} * Computes Jacobi(p,n). * Assumes n positive, odd, n>=3. */ private static int jacobiSymbol(int p, BigInteger n) { if (p == 0) return 0; // Algorithm and comments adapted from Colin Plumb's C library. int j = 1; int u = n.mag[n.mag.length-1]; // Make p positive if (p < 0) { p = -p; int n8 = u & 7; if ((n8 == 3) || (n8 == 7)) j = -j; // 3 (011) or 7 (111) mod 8 } // Get rid of factors of 2 in p while ((p & 3) == 0) p >>= 2; if ((p & 1) == 0) { p >>= 1; if (((u ^ (u>>1)) & 2) != 0) j = -j; // 3 (011) or 5 (101) mod 8 } if (p == 1) return j; // Then, apply quadratic reciprocity if ((p & u & 2) != 0) // p = u = 3 (mod 4)? j = -j; // And reduce u mod p u = n.mod(BigInteger.valueOf(p)).intValue(); // Now compute Jacobi(u,p), u < p while (u != 0) { while ((u & 3) == 0) u >>= 2; if ((u & 1) == 0) { u >>= 1; if (((p ^ (p>>1)) & 2) != 0) j = -j; // 3 (011) or 5 (101) mod 8 } if (u == 1) return j; // Now both u and p are odd, so use quadratic reciprocity assert (u < p); int t = u; u = p; p = t; if ((u & p & 2) != 0) // u = p = 3 (mod 4)? j = -j; // Now u >= p, so it can be reduced u %= p; } return 0; } private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) { BigInteger d = BigInteger.valueOf(z); BigInteger u = ONE; BigInteger u2; BigInteger v = ONE; BigInteger v2; for (int i=k.bitLength()-2; i>=0; i--) { u2 = u.multiply(v).mod(n); v2 = v.square().add(d.multiply(u.square())).mod(n); if (v2.testBit(0)) v2 = v2.subtract(n); v2 = v2.shiftRight(1); u = u2; v = v2; if (k.testBit(i)) { u2 = u.add(v).mod(n); if (u2.testBit(0)) u2 = u2.subtract(n); u2 = u2.shiftRight(1); v2 = v.add(d.multiply(u)).mod(n); if (v2.testBit(0)) v2 = v2.subtract(n); v2 = v2.shiftRight(1); u = u2; v = v2; } } return u; } private static volatile Random staticRandom; private static Random getSecureRandom() { if (staticRandom == null) { staticRandom = new java.security.SecureRandom(); } return staticRandom; } /** {@collect.stats} * Returns true iff this BigInteger passes the specified number of * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS * 186-2). * * The following assumptions are made: * This BigInteger is a positive, odd number greater than 2. * iterations<=50. */ private boolean passesMillerRabin(int iterations, Random rnd) { // Find a and m such that m is odd and this == 1 + 2**a * m BigInteger thisMinusOne = this.subtract(ONE); BigInteger m = thisMinusOne; int a = m.getLowestSetBit(); m = m.shiftRight(a); // Do the tests if (rnd == null) { rnd = getSecureRandom(); } for (int i=0; i<iterations; i++) { // Generate a uniform random on (1, this) BigInteger b; do { b = new BigInteger(this.bitLength(), rnd); } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0); int j = 0; BigInteger z = b.modPow(m, this); while(!((j==0 && z.equals(ONE)) || z.equals(thisMinusOne))) { if (j>0 && z.equals(ONE) || ++j==a) return false; z = z.modPow(TWO, this); } } return true; } /** {@collect.stats} * This internal constructor differs from its public cousin * with the arguments reversed in two ways: it assumes that its * arguments are correct, and it doesn't copy the magnitude array. */ BigInteger(int[] magnitude, int signum) { this.signum = (magnitude.length==0 ? 0 : signum); this.mag = magnitude; } /** {@collect.stats} * This private constructor is for internal use and assumes that its * arguments are correct. */ private BigInteger(byte[] magnitude, int signum) { this.signum = (magnitude.length==0 ? 0 : signum); this.mag = stripLeadingZeroBytes(magnitude); } //Static Factory Methods /** {@collect.stats} * Returns a BigInteger whose value is equal to that of the * specified {@code long}. This "static factory method" is * provided in preference to a ({@code long}) constructor * because it allows for reuse of frequently used BigIntegers. * * @param val value of the BigInteger to return. * @return a BigInteger with the specified value. */ public static BigInteger valueOf(long val) { // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant if (val == 0) return ZERO; if (val > 0 && val <= MAX_CONSTANT) return posConst[(int) val]; else if (val < 0 && val >= -MAX_CONSTANT) return negConst[(int) -val]; return new BigInteger(val); } /** {@collect.stats} * Constructs a BigInteger with the specified value, which may not be zero. */ private BigInteger(long val) { if (val < 0) { val = -val; signum = -1; } else { signum = 1; } int highWord = (int)(val >>> 32); if (highWord==0) { mag = new int[1]; mag[0] = (int)val; } else { mag = new int[2]; mag[0] = highWord; mag[1] = (int)val; } } /** {@collect.stats} * Returns a BigInteger with the given two's complement representation. * Assumes that the input array will not be modified (the returned * BigInteger will reference the input array if feasible). */ private static BigInteger valueOf(int val[]) { return (val[0]>0 ? new BigInteger(val, 1) : new BigInteger(val)); } // Constants /** {@collect.stats} * Initialize static constant array when class is loaded. */ private final static int MAX_CONSTANT = 16; private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1]; private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1]; static { for (int i = 1; i <= MAX_CONSTANT; i++) { int[] magnitude = new int[1]; magnitude[0] = i; posConst[i] = new BigInteger(magnitude, 1); negConst[i] = new BigInteger(magnitude, -1); } } /** {@collect.stats} * The BigInteger constant zero. * * @since 1.2 */ public static final BigInteger ZERO = new BigInteger(new int[0], 0); /** {@collect.stats} * The BigInteger constant one. * * @since 1.2 */ public static final BigInteger ONE = valueOf(1); /** {@collect.stats} * The BigInteger constant two. (Not exported.) */ private static final BigInteger TWO = valueOf(2); /** {@collect.stats} * The BigInteger constant ten. * * @since 1.5 */ public static final BigInteger TEN = valueOf(10); // Arithmetic Operations /** {@collect.stats} * Returns a BigInteger whose value is {@code (this + val)}. * * @param val value to be added to this BigInteger. * @return {@code this + val} */ public BigInteger add(BigInteger val) { if (val.signum == 0) return this; if (signum == 0) return val; if (val.signum == signum) return new BigInteger(add(mag, val.mag), signum); int cmp = compareMagnitude(val); if (cmp == 0) return ZERO; int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) : subtract(val.mag, mag)); resultMag = trustedStripLeadingZeroInts(resultMag); return new BigInteger(resultMag, cmp == signum ? 1 : -1); } /** {@collect.stats} * Adds the contents of the int arrays x and y. This method allocates * a new int array to hold the answer and returns a reference to that * array. */ private static int[] add(int[] x, int[] y) { // If x is shorter, swap the two arrays if (x.length < y.length) { int[] tmp = x; x = y; y = tmp; } int xIndex = x.length; int yIndex = y.length; int result[] = new int[xIndex]; long sum = 0; // Add common parts of both numbers while(yIndex > 0) { sum = (x[--xIndex] & LONG_MASK) + (y[--yIndex] & LONG_MASK) + (sum >>> 32); result[xIndex] = (int)sum; } // Copy remainder of longer number while carry propagation is required boolean carry = (sum >>> 32 != 0); while (xIndex > 0 && carry) carry = ((result[--xIndex] = x[xIndex] + 1) == 0); // Copy remainder of longer number while (xIndex > 0) result[--xIndex] = x[xIndex]; // Grow result if necessary if (carry) { int bigger[] = new int[result.length + 1]; System.arraycopy(result, 0, bigger, 1, result.length); bigger[0] = 0x01; return bigger; } return result; } /** {@collect.stats} * Returns a BigInteger whose value is {@code (this - val)}. * * @param val value to be subtracted from this BigInteger. * @return {@code this - val} */ public BigInteger subtract(BigInteger val) { if (val.signum == 0) return this; if (signum == 0) return val.negate(); if (val.signum != signum) return new BigInteger(add(mag, val.mag), signum); int cmp = compareMagnitude(val); if (cmp == 0) return ZERO; int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) : subtract(val.mag, mag)); resultMag = trustedStripLeadingZeroInts(resultMag); return new BigInteger(resultMag, cmp == signum ? 1 : -1); } /** {@collect.stats} * Subtracts the contents of the second int arrays (little) from the * first (big). The first int array (big) must represent a larger number * than the second. This method allocates the space necessary to hold the * answer. */ private static int[] subtract(int[] big, int[] little) { int bigIndex = big.length; int result[] = new int[bigIndex]; int littleIndex = little.length; long difference = 0; // Subtract common parts of both numbers while(littleIndex > 0) { difference = (big[--bigIndex] & LONG_MASK) - (little[--littleIndex] & LONG_MASK) + (difference >> 32); result[bigIndex] = (int)difference; } // Subtract remainder of longer number while borrow propagates boolean borrow = (difference >> 32 != 0); while (bigIndex > 0 && borrow) borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1); // Copy remainder of longer number while (bigIndex > 0) result[--bigIndex] = big[bigIndex]; return result; } /** {@collect.stats} * Returns a BigInteger whose value is {@code (this * val)}. * * @param val value to be multiplied by this BigInteger. * @return {@code this * val} */ public BigInteger multiply(BigInteger val) { if (val.signum == 0 || signum == 0) return ZERO; int[] result = multiplyToLen(mag, mag.length, val.mag, val.mag.length, null); result = trustedStripLeadingZeroInts(result); return new BigInteger(result, signum == val.signum ? 1 : -1); } /** {@collect.stats} * Package private methods used by BigDecimal code to multiply a BigInteger * with a long. Assumes v is not equal to INFLATED. */ BigInteger multiply(long v) { if (v == 0 || signum == 0) return ZERO; if (v == BigDecimal.INFLATED) return multiply(BigInteger.valueOf(v)); int rsign = (v > 0 ? signum : -signum); if (v < 0) v = -v; long dh = v >>> 32; // higher order bits long dl = v & LONG_MASK; // lower order bits int xlen = mag.length; int[] value = mag; int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]); long carry = 0; int rstart = rmag.length - 1; for (int i = xlen - 1; i >= 0; i--) { long product = (value[i] & LONG_MASK) * dl + carry; rmag[rstart--] = (int)product; carry = product >>> 32; } rmag[rstart] = (int)carry; if (dh != 0L) { carry = 0; rstart = rmag.length - 2; for (int i = xlen - 1; i >= 0; i--) { long product = (value[i] & LONG_MASK) * dh + (rmag[rstart] & LONG_MASK) + carry; rmag[rstart--] = (int)product; carry = product >>> 32; } rmag[0] = (int)carry; } if (carry == 0L) rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length); return new BigInteger(rmag, rsign); } /** {@collect.stats} * Multiplies int arrays x and y to the specified lengths and places * the result into z. There will be no leading zeros in the resultant array. */ private int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) { int xstart = xlen - 1; int ystart = ylen - 1; if (z == null || z.length < (xlen+ ylen)) z = new int[xlen+ylen]; long carry = 0; for (int j=ystart, k=ystart+1+xstart; j>=0; j--, k--) { long product = (y[j] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry; z[k] = (int)product; carry = product >>> 32; } z[xstart] = (int)carry; for (int i = xstart-1; i >= 0; i--) { carry = 0; for (int j=ystart, k=ystart+1+i; j>=0; j--, k--) { long product = (y[j] & LONG_MASK) * (x[i] & LONG_MASK) + (z[k] & LONG_MASK) + carry; z[k] = (int)product; carry = product >>> 32; } z[i] = (int)carry; } return z; } /** {@collect.stats} * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}. * * @return {@code this<sup>2</sup>} */ private BigInteger square() { if (signum == 0) return ZERO; int[] z = squareToLen(mag, mag.length, null); return new BigInteger(trustedStripLeadingZeroInts(z), 1); } /** {@collect.stats} * Squares the contents of the int array x. The result is placed into the * int array z. The contents of x are not changed. */ private static final int[] squareToLen(int[] x, int len, int[] z) { /* * The algorithm used here is adapted from Colin Plumb's C library. * Technique: Consider the partial products in the multiplication * of "abcde" by itself: * * a b c d e * * a b c d e * ================== * ae be ce de ee * ad bd cd dd de * ac bc cc cd ce * ab bb bc bd be * aa ab ac ad ae * * Note that everything above the main diagonal: * ae be ce de = (abcd) * e * ad bd cd = (abc) * d * ac bc = (ab) * c * ab = (a) * b * * is a copy of everything below the main diagonal: * de * cd ce * bc bd be * ab ac ad ae * * Thus, the sum is 2 * (off the diagonal) + diagonal. * * This is accumulated beginning with the diagonal (which * consist of the squares of the digits of the input), which is then * divided by two, the off-diagonal added, and multiplied by two * again. The low bit is simply a copy of the low bit of the * input, so it doesn't need special care. */ int zlen = len << 1; if (z == null || z.length < zlen) z = new int[zlen]; // Store the squares, right shifted one bit (i.e., divided by 2) int lastProductLowWord = 0; for (int j=0, i=0; j<len; j++) { long piece = (x[j] & LONG_MASK); long product = piece * piece; z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33); z[i++] = (int)(product >>> 1); lastProductLowWord = (int)product; } // Add in off-diagonal sums for (int i=len, offset=1; i>0; i--, offset+=2) { int t = x[i-1]; t = mulAdd(z, x, offset, i-1, t); addOne(z, offset-1, i, t); } // Shift back up and set low bit primitiveLeftShift(z, zlen, 1); z[zlen-1] |= x[len-1] & 1; return z; } /** {@collect.stats} * Returns a BigInteger whose value is {@code (this / val)}. * * @param val value by which this BigInteger is to be divided. * @return {@code this / val} * @throws ArithmeticException {@code val==0} */ public BigInteger divide(BigInteger val) { MutableBigInteger q = new MutableBigInteger(), a = new MutableBigInteger(this.mag), b = new MutableBigInteger(val.mag); a.divide(b, q); return q.toBigInteger(this.signum == val.signum ? 1 : -1); } /** {@collect.stats} * Returns an array of two BigIntegers containing {@code (this / val)} * followed by {@code (this % val)}. * * @param val value by which this BigInteger is to be divided, and the * remainder computed. * @return an array of two BigIntegers: the quotient {@code (this / val)} * is the initial element, and the remainder {@code (this % val)} * is the final element. * @throws ArithmeticException {@code val==0} */ public BigInteger[] divideAndRemainder(BigInteger val) { BigInteger[] result = new BigInteger[2]; MutableBigInteger q = new MutableBigInteger(), a = new MutableBigInteger(this.mag), b = new MutableBigInteger(val.mag); MutableBigInteger r = a.divide(b, q); result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1); result[1] = r.toBigInteger(this.signum); return result; } /** {@collect.stats} * Returns a BigInteger whose value is {@code (this % val)}. * * @param val value by which this BigInteger is to be divided, and the * remainder computed. * @return {@code this % val} * @throws ArithmeticException {@code val==0} */ public BigInteger remainder(BigInteger val) { MutableBigInteger q = new MutableBigInteger(), a = new MutableBigInteger(this.mag), b = new MutableBigInteger(val.mag); return a.divide(b, q).toBigInteger(this.signum); } /** {@collect.stats} * Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>. * Note that {@code exponent} is an integer rather than a BigInteger. * * @param exponent exponent to which this BigInteger is to be raised. * @return <tt>this<sup>exponent</sup></tt> * @throws ArithmeticException {@code exponent} is negative. (This would * cause the operation to yield a non-integer value.) */ public BigInteger pow(int exponent) { if (exponent < 0) throw new ArithmeticException("Negative exponent"); if (signum==0) return (exponent==0 ? ONE : this); // Perform exponentiation using repeated squaring trick int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1); int[] baseToPow2 = this.mag; int[] result = {1}; while (exponent != 0) { if ((exponent & 1)==1) { result = multiplyToLen(result, result.length, baseToPow2, baseToPow2.length, null); result = trustedStripLeadingZeroInts(result); } if ((exponent >>>= 1) != 0) { baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null); baseToPow2 = trustedStripLeadingZeroInts(baseToPow2); } } return new BigInteger(result, newSign); } /** {@collect.stats} * Returns a BigInteger whose value is the greatest common divisor of * {@code abs(this)} and {@code abs(val)}. Returns 0 if * {@code this==0 && val==0}. * * @param val value with which the GCD is to be computed. * @return {@code GCD(abs(this), abs(val))} */ public BigInteger gcd(BigInteger val) { if (val.signum == 0) return this.abs(); else if (this.signum == 0) return val.abs(); MutableBigInteger a = new MutableBigInteger(this); MutableBigInteger b = new MutableBigInteger(val); MutableBigInteger result = a.hybridGCD(b); return result.toBigInteger(1); } /** {@collect.stats} * Package private method to return bit length for an integer. */ static int bitLengthForInt(int n) { return 32 - Integer.numberOfLeadingZeros(n); } /** {@collect.stats} * Left shift int array a up to len by n bits. Returns the array that * results from the shift since space may have to be reallocated. */ private static int[] leftShift(int[] a, int len, int n) { int nInts = n >>> 5; int nBits = n&0x1F; int bitsInHighWord = bitLengthForInt(a[0]); // If shift can be done without recopy, do so if (n <= (32-bitsInHighWord)) { primitiveLeftShift(a, len, nBits); return a; } else { // Array must be resized if (nBits <= (32-bitsInHighWord)) { int result[] = new int[nInts+len]; for (int i=0; i<len; i++) result[i] = a[i]; primitiveLeftShift(result, result.length, nBits); return result; } else { int result[] = new int[nInts+len+1]; for (int i=0; i<len; i++) result[i] = a[i]; primitiveRightShift(result, result.length, 32 - nBits); return result; } } } // shifts a up to len right n bits assumes no leading zeros, 0<n<32 static void primitiveRightShift(int[] a, int len, int n) { int n2 = 32 - n; for (int i=len-1, c=a[i]; i>0; i--) { int b = c; c = a[i-1]; a[i] = (c << n2) | (b >>> n); } a[0] >>>= n; } // shifts a up to len left n bits assumes no leading zeros, 0<=n<32 static void primitiveLeftShift(int[] a, int len, int n) { if (len == 0 || n == 0) return; int n2 = 32 - n; for (int i=0, c=a[i], m=i+len-1; i<m; i++) { int b = c; c = a[i+1]; a[i] = (b << n) | (c >>> n2); } a[len-1] <<= n; } /** {@collect.stats} * Calculate bitlength of contents of the first len elements an int array, * assuming there are no leading zero ints. */ private static int bitLength(int[] val, int len) { if (len == 0) return 0; return ((len - 1) << 5) + bitLengthForInt(val[0]); } /** {@collect.stats} * Returns a BigInteger whose value is the absolute value of this * BigInteger. * * @return {@code abs(this)} */ public BigInteger abs() { return (signum >= 0 ? this : this.negate()); } /** {@collect.stats} * Returns a BigInteger whose value is {@code (-this)}. * * @return {@code -this} */ public BigInteger negate() { return new BigInteger(this.mag, -this.signum); } /** {@collect.stats} * Returns the signum function of this BigInteger. * * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or * positive. */ public int signum() { return this.signum; } // Modular Arithmetic Operations /** {@collect.stats} * Returns a BigInteger whose value is {@code (this mod m}). This method * differs from {@code remainder} in that it always returns a * <i>non-negative</i> BigInteger. * * @param m the modulus. * @return {@code this mod m} * @throws ArithmeticException {@code m <= 0} * @see #remainder */ public BigInteger mod(BigInteger m) { if (m.signum <= 0) throw new ArithmeticException("BigInteger: modulus not positive"); BigInteger result = this.remainder(m); return (result.signum >= 0 ? result : result.add(m)); } /** {@collect.stats} * Returns a BigInteger whose value is * <tt>(this<sup>exponent</sup> mod m)</tt>. (Unlike {@code pow}, this * method permits negative exponents.) * * @param exponent the exponent. * @param m the modulus. * @return <tt>this<sup>exponent</sup> mod m</tt> * @throws ArithmeticException {@code m <= 0} * @see #modInverse */ public BigInteger modPow(BigInteger exponent, BigInteger m) { if (m.signum <= 0) throw new ArithmeticException("BigInteger: modulus not positive"); // Trivial cases if (exponent.signum == 0) return (m.equals(ONE) ? ZERO : ONE); if (this.equals(ONE)) return (m.equals(ONE) ? ZERO : ONE); if (this.equals(ZERO) && exponent.signum >= 0) return ZERO; if (this.equals(negConst[1]) && (!exponent.testBit(0))) return (m.equals(ONE) ? ZERO : ONE); boolean invertResult; if ((invertResult = (exponent.signum < 0))) exponent = exponent.negate(); BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0 ? this.mod(m) : this); BigInteger result; if (m.testBit(0)) { // odd modulus result = base.oddModPow(exponent, m); } else { /* * Even modulus. Tear it into an "odd part" (m1) and power of two * (m2), exponentiate mod m1, manually exponentiate mod m2, and * use Chinese Remainder Theorem to combine results. */ // Tear m apart into odd part (m1) and power of 2 (m2) int p = m.getLowestSetBit(); // Max pow of 2 that divides m BigInteger m1 = m.shiftRight(p); // m/2**p BigInteger m2 = ONE.shiftLeft(p); // 2**p // Calculate new base from m1 BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0 ? this.mod(m1) : this); // Caculate (base ** exponent) mod m1. BigInteger a1 = (m1.equals(ONE) ? ZERO : base2.oddModPow(exponent, m1)); // Calculate (this ** exponent) mod m2 BigInteger a2 = base.modPow2(exponent, p); // Combine results using Chinese Remainder Theorem BigInteger y1 = m2.modInverse(m1); BigInteger y2 = m1.modInverse(m2); result = a1.multiply(m2).multiply(y1).add (a2.multiply(m1).multiply(y2)).mod(m); } return (invertResult ? result.modInverse(m) : result); } static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793, Integer.MAX_VALUE}; // Sentinel /** {@collect.stats} * Returns a BigInteger whose value is x to the power of y mod z. * Assumes: z is odd && x < z. */ private BigInteger oddModPow(BigInteger y, BigInteger z) { /* * The algorithm is adapted from Colin Plumb's C library. * * The window algorithm: * The idea is to keep a running product of b1 = n^(high-order bits of exp) * and then keep appending exponent bits to it. The following patterns * apply to a 3-bit window (k = 3): * To append 0: square * To append 1: square, multiply by n^1 * To append 10: square, multiply by n^1, square * To append 11: square, square, multiply by n^3 * To append 100: square, multiply by n^1, square, square * To append 101: square, square, square, multiply by n^5 * To append 110: square, square, multiply by n^3, square * To append 111: square, square, square, multiply by n^7 * * Since each pattern involves only one multiply, the longer the pattern * the better, except that a 0 (no multiplies) can be appended directly. * We precompute a table of odd powers of n, up to 2^k, and can then * multiply k bits of exponent at a time. Actually, assuming random * exponents, there is on average one zero bit between needs to * multiply (1/2 of the time there's none, 1/4 of the time there's 1, * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so * you have to do one multiply per k+1 bits of exponent. * * The loop walks down the exponent, squaring the result buffer as * it goes. There is a wbits+1 bit lookahead buffer, buf, that is * filled with the upcoming exponent bits. (What is read after the * end of the exponent is unimportant, but it is filled with zero here.) * When the most-significant bit of this buffer becomes set, i.e. * (buf & tblmask) != 0, we have to decide what pattern to multiply * by, and when to do it. We decide, remember to do it in future * after a suitable number of squarings have passed (e.g. a pattern * of "100" in the buffer requires that we multiply by n^1 immediately; * a pattern of "110" calls for multiplying by n^3 after one more * squaring), clear the buffer, and continue. * * When we start, there is one more optimization: the result buffer * is implcitly one, so squaring it or multiplying by it can be * optimized away. Further, if we start with a pattern like "100" * in the lookahead window, rather than placing n into the buffer * and then starting to square it, we have already computed n^2 * to compute the odd-powers table, so we can place that into * the buffer and save a squaring. * * This means that if you have a k-bit window, to compute n^z, * where z is the high k bits of the exponent, 1/2 of the time * it requires no squarings. 1/4 of the time, it requires 1 * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings. * And the remaining 1/2^(k-1) of the time, the top k bits are a * 1 followed by k-1 0 bits, so it again only requires k-2 * squarings, not k-1. The average of these is 1. Add that * to the one squaring we have to do to compute the table, * and you'll see that a k-bit window saves k-2 squarings * as well as reducing the multiplies. (It actually doesn't * hurt in the case k = 1, either.) */ // Special case for exponent of one if (y.equals(ONE)) return this; // Special case for base of zero if (signum==0) return ZERO; int[] base = mag.clone(); int[] exp = y.mag; int[] mod = z.mag; int modLen = mod.length; // Select an appropriate window size int wbits = 0; int ebits = bitLength(exp, exp.length); // if exponent is 65537 (0x10001), use minimum window size if ((ebits != 17) || (exp[0] != 65537)) { while (ebits > bnExpModThreshTable[wbits]) { wbits++; } } // Calculate appropriate table size int tblmask = 1 << wbits; // Allocate table for precomputed odd powers of base in Montgomery form int[][] table = new int[tblmask][]; for (int i=0; i<tblmask; i++) table[i] = new int[modLen]; // Compute the modular inverse int inv = -MutableBigInteger.inverseMod32(mod[modLen-1]); // Convert base to Montgomery form int[] a = leftShift(base, base.length, modLen << 5); MutableBigInteger q = new MutableBigInteger(), a2 = new MutableBigInteger(a), b2 = new MutableBigInteger(mod); MutableBigInteger r= a2.divide(b2, q); table[0] = r.toIntArray(); // Pad table[0] with leading zeros so its length is at least modLen if (table[0].length < modLen) { int offset = modLen - table[0].length; int[] t2 = new int[modLen]; for (int i=0; i<table[0].length; i++) t2[i+offset] = table[0][i]; table[0] = t2; } // Set b to the square of the base int[] b = squareToLen(table[0], modLen, null); b = montReduce(b, mod, modLen, inv); // Set t to high half of b int[] t = new int[modLen]; for(int i=0; i<modLen; i++) t[i] = b[i]; // Fill in the table with odd powers of the base for (int i=1; i<tblmask; i++) { int[] prod = multiplyToLen(t, modLen, table[i-1], modLen, null); table[i] = montReduce(prod, mod, modLen, inv); } // Pre load the window that slides over the exponent int bitpos = 1 << ((ebits-1) & (32-1)); int buf = 0; int elen = exp.length; int eIndex = 0; for (int i = 0; i <= wbits; i++) { buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0); bitpos >>>= 1; if (bitpos == 0) { eIndex++; bitpos = 1 << (32-1); elen--; } } int multpos = ebits; // The first iteration, which is hoisted out of the main loop ebits--; boolean isone = true; multpos = ebits - wbits; while ((buf & 1) == 0) { buf >>>= 1; multpos++; } int[] mult = table[buf >>> 1]; buf = 0; if (multpos == ebits) isone = false; // The main loop while(true) { ebits--; // Advance the window buf <<= 1; if (elen != 0) { buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0; bitpos >>>= 1; if (bitpos == 0) { eIndex++; bitpos = 1 << (32-1); elen--; } } // Examine the window for pending multiplies if ((buf & tblmask) != 0) { multpos = ebits - wbits; while ((buf & 1) == 0) { buf >>>= 1; multpos++; } mult = table[buf >>> 1]; buf = 0; } // Perform multiply if (ebits == multpos) { if (isone) { b = mult.clone(); isone = false; } else { t = b; a = multiplyToLen(t, modLen, mult, modLen, a); a = montReduce(a, mod, modLen, inv); t = a; a = b; b = t; } } // Check if done if (ebits == 0) break; // Square the input if (!isone) { t = b; a = squareToLen(t, modLen, a); a = montReduce(a, mod, modLen, inv); t = a; a = b; b = t; } } // Convert result out of Montgomery form and return int[] t2 = new int[2*modLen]; for(int i=0; i<modLen; i++) t2[i+modLen] = b[i]; b = montReduce(t2, mod, modLen, inv); t2 = new int[modLen]; for(int i=0; i<modLen; i++) t2[i] = b[i]; return new BigInteger(1, t2); } /** {@collect.stats} * Montgomery reduce n, modulo mod. This reduces modulo mod and divides * by 2^(32*mlen). Adapted from Colin Plumb's C library. */ private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) { int c=0; int len = mlen; int offset=0; do { int nEnd = n[n.length-1-offset]; int carry = mulAdd(n, mod, offset, mlen, inv * nEnd); c += addOne(n, offset, mlen, carry); offset++; } while(--len > 0); while(c>0) c += subN(n, mod, mlen); while (intArrayCmpToLen(n, mod, mlen) >= 0) subN(n, mod, mlen); return n; } /* * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than, * equal to, or greater than arg2 up to length len. */ private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) { for (int i=0; i<len; i++) { long b1 = arg1[i] & LONG_MASK; long b2 = arg2[i] & LONG_MASK; if (b1 < b2) return -1; if (b1 > b2) return 1; } return 0; } /** {@collect.stats} * Subtracts two numbers of same length, returning borrow. */ private static int subN(int[] a, int[] b, int len) { long sum = 0; while(--len >= 0) { sum = (a[len] & LONG_MASK) - (b[len] & LONG_MASK) + (sum >> 32); a[len] = (int)sum; } return (int)(sum >> 32); } /** {@collect.stats} * Multiply an array by one word k and add to result, return the carry */ static int mulAdd(int[] out, int[] in, int offset, int len, int k) { long kLong = k & LONG_MASK; long carry = 0; offset = out.length-offset - 1; for (int j=len-1; j >= 0; j--) { long product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry; out[offset--] = (int)product; carry = product >>> 32; } return (int)carry; } /** {@collect.stats} * Add one word to the number a mlen words into a. Return the resulting * carry. */ static int addOne(int[] a, int offset, int mlen, int carry) { offset = a.length-1-mlen-offset; long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK); a[offset] = (int)t; if ((t >>> 32) == 0) return 0; while (--mlen >= 0) { if (--offset < 0) { // Carry out of number return 1; } else { a[offset]++; if (a[offset] != 0) return 0; } } return 1; } /** {@collect.stats} * Returns a BigInteger whose value is (this ** exponent) mod (2**p) */ private BigInteger modPow2(BigInteger exponent, int p) { /* * Perform exponentiation using repeated squaring trick, chopping off * high order bits as indicated by modulus. */ BigInteger result = valueOf(1); BigInteger baseToPow2 = this.mod2(p); int expOffset = 0; int limit = exponent.bitLength(); if (this.testBit(0)) limit = (p-1) < limit ? (p-1) : limit; while (expOffset < limit) { if (exponent.testBit(expOffset)) result = result.multiply(baseToPow2).mod2(p); expOffset++; if (expOffset < limit) baseToPow2 = baseToPow2.square().mod2(p); } return result; } /** {@collect.stats} * Returns a BigInteger whose value is this mod(2**p). * Assumes that this {@code BigInteger >= 0} and {@code p > 0}. */ private BigInteger mod2(int p) { if (bitLength() <= p) return this; // Copy remaining ints of mag int numInts = (p + 31) >>> 5; int[] mag = new int[numInts]; for (int i=0; i<numInts; i++) mag[i] = this.mag[i + (this.mag.length - numInts)]; // Mask out any excess bits int excessBits = (numInts << 5) - p; mag[0] &= (1L << (32-excessBits)) - 1; return (mag[0]==0 ? new BigInteger(1, mag) : new BigInteger(mag, 1)); } /** {@collect.stats} * Returns a BigInteger whose value is {@code (this}<sup>-1</sup> {@code mod m)}. * * @param m the modulus. * @return {@code this}<sup>-1</sup> {@code mod m}. * @throws ArithmeticException {@code m <= 0}, or this BigInteger * has no multiplicative inverse mod m (that is, this BigInteger * is not <i>relatively prime</i> to m). */ public BigInteger modInverse(BigInteger m) { if (m.signum != 1) throw new ArithmeticException("BigInteger: modulus not positive"); if (m.equals(ONE)) return ZERO; // Calculate (this mod m) BigInteger modVal = this; if (signum < 0 || (this.compareMagnitude(m) >= 0)) modVal = this.mod(m); if (modVal.equals(ONE)) return ONE; MutableBigInteger a = new MutableBigInteger(modVal); MutableBigInteger b = new MutableBigInteger(m); MutableBigInteger result = a.mutableModInverse(b); return result.toBigInteger(1); } // Shift Operations /** {@collect.stats} * Returns a BigInteger whose value is {@code (this << n)}. * The shift distance, {@code n}, may be negative, in which case * this method performs a right shift. * (Computes <tt>floor(this * 2<sup>n</sup>)</tt>.) * * @param n shift distance, in bits. * @return {@code this << n} * @see #shiftRight */ public BigInteger shiftLeft(int n) { if (signum == 0) return ZERO; if (n==0) return this; if (n<0) return shiftRight(-n); int nInts = n >>> 5; int nBits = n & 0x1f; int magLen = mag.length; int newMag[] = null; if (nBits == 0) { newMag = new int[magLen + nInts]; for (int i=0; i<magLen; i++) newMag[i] = mag[i]; } else { int i = 0; int nBits2 = 32 - nBits; int highBits = mag[0] >>> nBits2; if (highBits != 0) { newMag = new int[magLen + nInts + 1]; newMag[i++] = highBits; } else { newMag = new int[magLen + nInts]; } int j=0; while (j < magLen-1) newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2; newMag[i] = mag[j] << nBits; } return new BigInteger(newMag, signum); } /** {@collect.stats} * Returns a BigInteger whose value is {@code (this >> n)}. Sign * extension is performed. The shift distance, {@code n}, may be * negative, in which case this method performs a left shift. * (Computes <tt>floor(this / 2<sup>n</sup>)</tt>.) * * @param n shift distance, in bits. * @return {@code this >> n} * @see #shiftLeft */ public BigInteger shiftRight(int n) { if (n==0) return this; if (n<0) return shiftLeft(-n); int nInts = n >>> 5; int nBits = n & 0x1f; int magLen = mag.length; int newMag[] = null; // Special case: entire contents shifted off the end if (nInts >= magLen) return (signum >= 0 ? ZERO : negConst[1]); if (nBits == 0) { int newMagLen = magLen - nInts; newMag = new int[newMagLen]; for (int i=0; i<newMagLen; i++) newMag[i] = mag[i]; } else { int i = 0; int highBits = mag[0] >>> nBits; if (highBits != 0) { newMag = new int[magLen - nInts]; newMag[i++] = highBits; } else { newMag = new int[magLen - nInts -1]; } int nBits2 = 32 - nBits; int j=0; while (j < magLen - nInts - 1) newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits); } if (signum < 0) { // Find out whether any one-bits were shifted off the end. boolean onesLost = false; for (int i=magLen-1, j=magLen-nInts; i>=j && !onesLost; i--) onesLost = (mag[i] != 0); if (!onesLost && nBits != 0) onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0); if (onesLost) newMag = javaIncrement(newMag); } return new BigInteger(newMag, signum); } int[] javaIncrement(int[] val) { int lastSum = 0; for (int i=val.length-1; i >= 0 && lastSum == 0; i--) lastSum = (val[i] += 1); if (lastSum == 0) { val = new int[val.length+1]; val[0] = 1; } return val; } // Bitwise Operations /** {@collect.stats} * Returns a BigInteger whose value is {@code (this & val)}. (This * method returns a negative BigInteger if and only if this and val are * both negative.) * * @param val value to be AND'ed with this BigInteger. * @return {@code this & val} */ public BigInteger and(BigInteger val) { int[] result = new int[Math.max(intLength(), val.intLength())]; for (int i=0; i<result.length; i++) result[i] = (getInt(result.length-i-1) & val.getInt(result.length-i-1)); return valueOf(result); } /** {@collect.stats} * Returns a BigInteger whose value is {@code (this | val)}. (This method * returns a negative BigInteger if and only if either this or val is * negative.) * * @param val value to be OR'ed with this BigInteger. * @return {@code this | val} */ public BigInteger or(BigInteger val) { int[] result = new int[Math.max(intLength(), val.intLength())]; for (int i=0; i<result.length; i++) result[i] = (getInt(result.length-i-1) | val.getInt(result.length-i-1)); return valueOf(result); } /** {@collect.stats} * Returns a BigInteger whose value is {@code (this ^ val)}. (This method * returns a negative BigInteger if and only if exactly one of this and * val are negative.) * * @param val value to be XOR'ed with this BigInteger. * @return {@code this ^ val} */ public BigInteger xor(BigInteger val) { int[] result = new int[Math.max(intLength(), val.intLength())]; for (int i=0; i<result.length; i++) result[i] = (getInt(result.length-i-1) ^ val.getInt(result.length-i-1)); return valueOf(result); } /** {@collect.stats} * Returns a BigInteger whose value is {@code (~this)}. (This method * returns a negative value if and only if this BigInteger is * non-negative.) * * @return {@code ~this} */ public BigInteger not() { int[] result = new int[intLength()]; for (int i=0; i<result.length; i++) result[i] = ~getInt(result.length-i-1); return valueOf(result); } /** {@collect.stats} * Returns a BigInteger whose value is {@code (this & ~val)}. This * method, which is equivalent to {@code and(val.not())}, is provided as * a convenience for masking operations. (This method returns a negative * BigInteger if and only if {@code this} is negative and {@code val} is * positive.) * * @param val value to be complemented and AND'ed with this BigInteger. * @return {@code this & ~val} */ public BigInteger andNot(BigInteger val) { int[] result = new int[Math.max(intLength(), val.intLength())]; for (int i=0; i<result.length; i++) result[i] = (getInt(result.length-i-1) & ~val.getInt(result.length-i-1)); return valueOf(result); } // Single Bit Operations /** {@collect.stats} * Returns {@code true} if and only if the designated bit is set. * (Computes {@code ((this & (1<<n)) != 0)}.) * * @param n index of bit to test. * @return {@code true} if and only if the designated bit is set. * @throws ArithmeticException {@code n} is negative. */ public boolean testBit(int n) { if (n<0) throw new ArithmeticException("Negative bit address"); return (getInt(n >>> 5) & (1 << (n & 31))) != 0; } /** {@collect.stats} * Returns a BigInteger whose value is equivalent to this BigInteger * with the designated bit set. (Computes {@code (this | (1<<n))}.) * * @param n index of bit to set. * @return {@code this | (1<<n)} * @throws ArithmeticException {@code n} is negative. */ public BigInteger setBit(int n) { if (n<0) throw new ArithmeticException("Negative bit address"); int intNum = n >>> 5; int[] result = new int[Math.max(intLength(), intNum+2)]; for (int i=0; i<result.length; i++) result[result.length-i-1] = getInt(i); result[result.length-intNum-1] |= (1 << (n & 31)); return valueOf(result); } /** {@collect.stats} * Returns a BigInteger whose value is equivalent to this BigInteger * with the designated bit cleared. * (Computes {@code (this & ~(1<<n))}.) * * @param n index of bit to clear. * @return {@code this & ~(1<<n)} * @throws ArithmeticException {@code n} is negative. */ public BigInteger clearBit(int n) { if (n<0) throw new ArithmeticException("Negative bit address"); int intNum = n >>> 5; int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)]; for (int i=0; i<result.length; i++) result[result.length-i-1] = getInt(i); result[result.length-intNum-1] &= ~(1 << (n & 31)); return valueOf(result); } /** {@collect.stats} * Returns a BigInteger whose value is equivalent to this BigInteger * with the designated bit flipped. * (Computes {@code (this ^ (1<<n))}.) * * @param n index of bit to flip. * @return {@code this ^ (1<<n)} * @throws ArithmeticException {@code n} is negative. */ public BigInteger flipBit(int n) { if (n<0) throw new ArithmeticException("Negative bit address"); int intNum = n >>> 5; int[] result = new int[Math.max(intLength(), intNum+2)]; for (int i=0; i<result.length; i++) result[result.length-i-1] = getInt(i); result[result.length-intNum-1] ^= (1 << (n & 31)); return valueOf(result); } /** {@collect.stats} * Returns the index of the rightmost (lowest-order) one bit in this * BigInteger (the number of zero bits to the right of the rightmost * one bit). Returns -1 if this BigInteger contains no one bits. * (Computes {@code (this==0? -1 : log2(this & -this))}.) * * @return index of the rightmost one bit in this BigInteger. */ public int getLowestSetBit() { @SuppressWarnings("deprecation") int lsb = lowestSetBit - 2; if (lsb == -2) { // lowestSetBit not initialized yet lsb = 0; if (signum == 0) { lsb -= 1; } else { // Search for lowest order nonzero int int i,b; for (i=0; (b = getInt(i))==0; i++) ; lsb += (i << 5) + Integer.numberOfTrailingZeros(b); } lowestSetBit = lsb + 2; } return lsb; } // Miscellaneous Bit Operations /** {@collect.stats} * Returns the number of bits in the minimal two's-complement * representation of this BigInteger, <i>excluding</i> a sign bit. * For positive BigIntegers, this is equivalent to the number of bits in * the ordinary binary representation. (Computes * {@code (ceil(log2(this < 0 ? -this : this+1)))}.) * * @return number of bits in the minimal two's-complement * representation of this BigInteger, <i>excluding</i> a sign bit. */ public int bitLength() { @SuppressWarnings("deprecation") int n = bitLength - 1; if (n == -1) { // bitLength not initialized yet int[] m = mag; int len = m.length; if (len == 0) { n = 0; // offset by one to initialize } else { // Calculate the bit length of the magnitude int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]); if (signum < 0) { // Check if magnitude is a power of two boolean pow2 = (Integer.bitCount(mag[0]) == 1); for(int i=1; i< len && pow2; i++) pow2 = (mag[i] == 0); n = (pow2 ? magBitLength -1 : magBitLength); } else { n = magBitLength; } } bitLength = n + 1; } return n; } /** {@collect.stats} * Returns the number of bits in the two's complement representation * of this BigInteger that differ from its sign bit. This method is * useful when implementing bit-vector style sets atop BigIntegers. * * @return number of bits in the two's complement representation * of this BigInteger that differ from its sign bit. */ public int bitCount() { @SuppressWarnings("deprecation") int bc = bitCount - 1; if (bc == -1) { // bitCount not initialized yet bc = 0; // offset by one to initialize // Count the bits in the magnitude for (int i=0; i<mag.length; i++) bc += Integer.bitCount(mag[i]); if (signum < 0) { // Count the trailing zeros in the magnitude int magTrailingZeroCount = 0, j; for (j=mag.length-1; mag[j]==0; j--) magTrailingZeroCount += 32; magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]); bc += magTrailingZeroCount - 1; } bitCount = bc + 1; } return bc; } // Primality Testing /** {@collect.stats} * Returns {@code true} if this BigInteger is probably prime, * {@code false} if it's definitely composite. If * {@code certainty} is {@code <= 0}, {@code true} is * returned. * * @param certainty a measure of the uncertainty that the caller is * willing to tolerate: if the call returns {@code true} * the probability that this BigInteger is prime exceeds * (1 - 1/2<sup>{@code certainty}</sup>). The execution time of * this method is proportional to the value of this parameter. * @return {@code true} if this BigInteger is probably prime, * {@code false} if it's definitely composite. */ public boolean isProbablePrime(int certainty) { if (certainty <= 0) return true; BigInteger w = this.abs(); if (w.equals(TWO)) return true; if (!w.testBit(0) || w.equals(ONE)) return false; return w.primeToCertainty(certainty, null); } // Comparison Operations /** {@collect.stats} * Compares this BigInteger with the specified BigInteger. This * method is provided in preference to individual methods for each * of the six boolean comparison operators ({@literal <}, ==, * {@literal >}, {@literal >=}, !=, {@literal <=}). The suggested * idiom for performing these comparisons is: {@code * (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where * &lt;<i>op</i>&gt; is one of the six comparison operators. * * @param val BigInteger to which this BigInteger is to be compared. * @return -1, 0 or 1 as this BigInteger is numerically less than, equal * to, or greater than {@code val}. */ public int compareTo(BigInteger val) { if (signum == val.signum) { switch (signum) { case 1: return compareMagnitude(val); case -1: return val.compareMagnitude(this); default: return 0; } } return signum > val.signum ? 1 : -1; } /** {@collect.stats} * Compares the magnitude array of this BigInteger with the specified * BigInteger's. This is the version of compareTo ignoring sign. * * @param val BigInteger whose magnitude array to be compared. * @return -1, 0 or 1 as this magnitude array is less than, equal to or * greater than the magnitude aray for the specified BigInteger's. */ final int compareMagnitude(BigInteger val) { int[] m1 = mag; int len1 = m1.length; int[] m2 = val.mag; int len2 = m2.length; if (len1 < len2) return -1; if (len1 > len2) return 1; for (int i = 0; i < len1; i++) { int a = m1[i]; int b = m2[i]; if (a != b) return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1; } return 0; } /** {@collect.stats} * Compares this BigInteger with the specified Object for equality. * * @param x Object to which this BigInteger is to be compared. * @return {@code true} if and only if the specified Object is a * BigInteger whose value is numerically equal to this BigInteger. */ public boolean equals(Object x) { // This test is just an optimization, which may or may not help if (x == this) return true; if (!(x instanceof BigInteger)) return false; BigInteger xInt = (BigInteger) x; if (xInt.signum != signum) return false; int[] m = mag; int len = m.length; int[] xm = xInt.mag; if (len != xm.length) return false; for (int i = 0; i < len; i++) if (xm[i] != m[i]) return false; return true; } /** {@collect.stats} * Returns the minimum of this BigInteger and {@code val}. * * @param val value with which the minimum is to be computed. * @return the BigInteger whose value is the lesser of this BigInteger and * {@code val}. If they are equal, either may be returned. */ public BigInteger min(BigInteger val) { return (compareTo(val)<0 ? this : val); } /** {@collect.stats} * Returns the maximum of this BigInteger and {@code val}. * * @param val value with which the maximum is to be computed. * @return the BigInteger whose value is the greater of this and * {@code val}. If they are equal, either may be returned. */ public BigInteger max(BigInteger val) { return (compareTo(val)>0 ? this : val); } // Hash Function /** {@collect.stats} * Returns the hash code for this BigInteger. * * @return hash code for this BigInteger. */ public int hashCode() { int hashCode = 0; for (int i=0; i<mag.length; i++) hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK)); return hashCode * signum; } /** {@collect.stats} * Returns the String representation of this BigInteger in the * given radix. If the radix is outside the range from {@link * Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive, * it will default to 10 (as is the case for * {@code Integer.toString}). The digit-to-character mapping * provided by {@code Character.forDigit} is used, and a minus * sign is prepended if appropriate. (This representation is * compatible with the {@link #BigInteger(String, int) (String, * int)} constructor.) * * @param radix radix of the String representation. * @return String representation of this BigInteger in the given radix. * @see Integer#toString * @see Character#forDigit * @see #BigInteger(java.lang.String, int) */ public String toString(int radix) { if (signum == 0) return "0"; if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; // Compute upper bound on number of digit groups and allocate space int maxNumDigitGroups = (4*mag.length + 6)/7; String digitGroup[] = new String[maxNumDigitGroups]; // Translate number to string, a digit group at a time BigInteger tmp = this.abs(); int numGroups = 0; while (tmp.signum != 0) { BigInteger d = longRadix[radix]; MutableBigInteger q = new MutableBigInteger(), a = new MutableBigInteger(tmp.mag), b = new MutableBigInteger(d.mag); MutableBigInteger r = a.divide(b, q); BigInteger q2 = q.toBigInteger(tmp.signum * d.signum); BigInteger r2 = r.toBigInteger(tmp.signum * d.signum); digitGroup[numGroups++] = Long.toString(r2.longValue(), radix); tmp = q2; } // Put sign (if any) and first digit group into result buffer StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1); if (signum<0) buf.append('-'); buf.append(digitGroup[numGroups-1]); // Append remaining digit groups padded with leading zeros for (int i=numGroups-2; i>=0; i--) { // Prepend (any) leading zeros for this digit group int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length(); if (numLeadingZeros != 0) buf.append(zeros[numLeadingZeros]); buf.append(digitGroup[i]); } return buf.toString(); } /* zero[i] is a string of i consecutive zeros. */ private static String zeros[] = new String[64]; static { zeros[63] = "000000000000000000000000000000000000000000000000000000000000000"; for (int i=0; i<63; i++) zeros[i] = zeros[63].substring(0, i); } /** {@collect.stats} * Returns the decimal String representation of this BigInteger. * The digit-to-character mapping provided by * {@code Character.forDigit} is used, and a minus sign is * prepended if appropriate. (This representation is compatible * with the {@link #BigInteger(String) (String)} constructor, and * allows for String concatenation with Java's + operator.) * * @return decimal String representation of this BigInteger. * @see Character#forDigit * @see #BigInteger(java.lang.String) */ public String toString() { return toString(10); } /** {@collect.stats} * Returns a byte array containing the two's-complement * representation of this BigInteger. The byte array will be in * <i>big-endian</i> byte-order: the most significant byte is in * the zeroth element. The array will contain the minimum number * of bytes required to represent this BigInteger, including at * least one sign bit, which is {@code (ceil((this.bitLength() + * 1)/8))}. (This representation is compatible with the * {@link #BigInteger(byte[]) (byte[])} constructor.) * * @return a byte array containing the two's-complement representation of * this BigInteger. * @see #BigInteger(byte[]) */ public byte[] toByteArray() { int byteLen = bitLength()/8 + 1; byte[] byteArray = new byte[byteLen]; for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i>=0; i--) { if (bytesCopied == 4) { nextInt = getInt(intIndex++); bytesCopied = 1; } else { nextInt >>>= 8; bytesCopied++; } byteArray[i] = (byte)nextInt; } return byteArray; } /** {@collect.stats} * Converts this BigInteger to an {@code int}. This * conversion is analogous to a <a * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing * primitive conversion</i></a> from {@code long} to * {@code int} as defined in the <a * href="http://java.sun.com/docs/books/jls/html/">Java Language * Specification</a>: if this BigInteger is too big to fit in an * {@code int}, only the low-order 32 bits are returned. * Note that this conversion can lose information about the * overall magnitude of the BigInteger value as well as return a * result with the opposite sign. * * @return this BigInteger converted to an {@code int}. */ public int intValue() { int result = 0; result = getInt(0); return result; } /** {@collect.stats} * Converts this BigInteger to a {@code long}. This * conversion is analogous to a <a * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing * primitive conversion</i></a> from {@code long} to * {@code int} as defined in the <a * href="http://java.sun.com/docs/books/jls/html/">Java Language * Specification</a>: if this BigInteger is too big to fit in a * {@code long}, only the low-order 64 bits are returned. * Note that this conversion can lose information about the * overall magnitude of the BigInteger value as well as return a * result with the opposite sign. * * @return this BigInteger converted to a {@code long}. */ public long longValue() { long result = 0; for (int i=1; i>=0; i--) result = (result << 32) + (getInt(i) & LONG_MASK); return result; } /** {@collect.stats} * Converts this BigInteger to a {@code float}. This * conversion is similar to the <a * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing * primitive conversion</i></a> from {@code double} to * {@code float} defined in the <a * href="http://java.sun.com/docs/books/jls/html/">Java Language * Specification</a>: if this BigInteger has too great a magnitude * to represent as a {@code float}, it will be converted to * {@link Float#NEGATIVE_INFINITY} or {@link * Float#POSITIVE_INFINITY} as appropriate. Note that even when * the return value is finite, this conversion can lose * information about the precision of the BigInteger value. * * @return this BigInteger converted to a {@code float}. */ public float floatValue() { // Somewhat inefficient, but guaranteed to work. return Float.parseFloat(this.toString()); } /** {@collect.stats} * Converts this BigInteger to a {@code double}. This * conversion is similar to the <a * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing * primitive conversion</i></a> from {@code double} to * {@code float} defined in the <a * href="http://java.sun.com/docs/books/jls/html/">Java Language * Specification</a>: if this BigInteger has too great a magnitude * to represent as a {@code double}, it will be converted to * {@link Double#NEGATIVE_INFINITY} or {@link * Double#POSITIVE_INFINITY} as appropriate. Note that even when * the return value is finite, this conversion can lose * information about the precision of the BigInteger value. * * @return this BigInteger converted to a {@code double}. */ public double doubleValue() { // Somewhat inefficient, but guaranteed to work. return Double.parseDouble(this.toString()); } /** {@collect.stats} * Returns a copy of the input array stripped of any leading zero bytes. */ private static int[] stripLeadingZeroInts(int val[]) { int vlen = val.length; int keep; // Find first nonzero byte for (keep = 0; keep < vlen && val[keep] == 0; keep++) ; return java.util.Arrays.copyOfRange(val, keep, vlen); } /** {@collect.stats} * Returns the input array stripped of any leading zero bytes. * Since the source is trusted the copying may be skipped. */ private static int[] trustedStripLeadingZeroInts(int val[]) { int vlen = val.length; int keep; // Find first nonzero byte for (keep = 0; keep < vlen && val[keep] == 0; keep++) ; return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen); } /** {@collect.stats} * Returns a copy of the input array stripped of any leading zero bytes. */ private static int[] stripLeadingZeroBytes(byte a[]) { int byteLength = a.length; int keep; // Find first nonzero byte for (keep = 0; keep < byteLength && a[keep]==0; keep++) ; // Allocate new array and copy relevant part of input array int intLength = ((byteLength - keep) + 3) >>> 2; int[] result = new int[intLength]; int b = byteLength - 1; for (int i = intLength-1; i >= 0; i--) { result[i] = a[b--] & 0xff; int bytesRemaining = b - keep + 1; int bytesToTransfer = Math.min(3, bytesRemaining); for (int j=8; j <= (bytesToTransfer << 3); j += 8) result[i] |= ((a[b--] & 0xff) << j); } return result; } /** {@collect.stats} * Takes an array a representing a negative 2's-complement number and * returns the minimal (no leading zero bytes) unsigned whose value is -a. */ private static int[] makePositive(byte a[]) { int keep, k; int byteLength = a.length; // Find first non-sign (0xff) byte of input for (keep=0; keep<byteLength && a[keep]==-1; keep++) ; /* Allocate output array. If all non-sign bytes are 0x00, we must * allocate space for one extra output byte. */ for (k=keep; k<byteLength && a[k]==0; k++) ; int extraByte = (k==byteLength) ? 1 : 0; int intLength = ((byteLength - keep + extraByte) + 3)/4; int result[] = new int[intLength]; /* Copy one's complement of input into output, leaving extra * byte (if it exists) == 0x00 */ int b = byteLength - 1; for (int i = intLength-1; i >= 0; i--) { result[i] = a[b--] & 0xff; int numBytesToTransfer = Math.min(3, b-keep+1); if (numBytesToTransfer < 0) numBytesToTransfer = 0; for (int j=8; j <= 8*numBytesToTransfer; j += 8) result[i] |= ((a[b--] & 0xff) << j); // Mask indicates which bits must be complemented int mask = -1 >>> (8*(3-numBytesToTransfer)); result[i] = ~result[i] & mask; } // Add one to one's complement to generate two's complement for (int i=result.length-1; i>=0; i--) { result[i] = (int)((result[i] & LONG_MASK) + 1); if (result[i] != 0) break; } return result; } /** {@collect.stats} * Takes an array a representing a negative 2's-complement number and * returns the minimal (no leading zero ints) unsigned whose value is -a. */ private static int[] makePositive(int a[]) { int keep, j; // Find first non-sign (0xffffffff) int of input for (keep=0; keep<a.length && a[keep]==-1; keep++) ; /* Allocate output array. If all non-sign ints are 0x00, we must * allocate space for one extra output int. */ for (j=keep; j<a.length && a[j]==0; j++) ; int extraInt = (j==a.length ? 1 : 0); int result[] = new int[a.length - keep + extraInt]; /* Copy one's complement of input into output, leaving extra * int (if it exists) == 0x00 */ for (int i = keep; i<a.length; i++) result[i - keep + extraInt] = ~a[i]; // Add one to one's complement to generate two's complement for (int i=result.length-1; ++result[i]==0; i--) ; return result; } /* * The following two arrays are used for fast String conversions. Both * are indexed by radix. The first is the number of digits of the given * radix that can fit in a Java long without "going negative", i.e., the * highest integer n such that radix**n < 2**63. The second is the * "long radix" that tears each number into "long digits", each of which * consists of the number of digits in the corresponding element in * digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not * used. */ private static int digitsPerLong[] = {0, 0, 62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12}; private static BigInteger longRadix[] = {null, null, valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL), valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL), valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L), valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L), valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L), valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL), valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L), valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L), valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L), valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L), valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L), valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L), valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL), valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L), valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L), valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L), valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L), valueOf(0x41c21cb8e1000000L)}; /* * These two arrays are the integer analogue of above. */ private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11, 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5}; private static int intRadix[] = {0, 0, 0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800, 0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61, 0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000, 0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d, 0x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40, 0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41, 0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400 }; /** {@collect.stats} * These routines provide access to the two's complement representation * of BigIntegers. */ /** {@collect.stats} * Returns the length of the two's complement representation in ints, * including space for at least one sign bit. */ private int intLength() { return (bitLength() >>> 5) + 1; } /* Returns sign bit */ private int signBit() { return signum < 0 ? 1 : 0; } /* Returns an int of sign bits */ private int signInt() { return signum < 0 ? -1 : 0; } /** {@collect.stats} * Returns the specified int of the little-endian two's complement * representation (int 0 is the least significant). The int number can * be arbitrarily high (values are logically preceded by infinitely many * sign ints). */ private int getInt(int n) { if (n < 0) return 0; if (n >= mag.length) return signInt(); int magInt = mag[mag.length-n-1]; return (signum >= 0 ? magInt : (n <= firstNonzeroIntNum() ? -magInt : ~magInt)); } /** {@collect.stats} * Returns the index of the int that contains the first nonzero int in the * little-endian binary representation of the magnitude (int 0 is the * least significant). If the magnitude is zero, return value is undefined. */ private int firstNonzeroIntNum() { int fn = firstNonzeroIntNum - 2; if (fn == -2) { // firstNonzeroIntNum not initialized yet fn = 0; // Search for the first nonzero int int i; int mlen = mag.length; for (i = mlen - 1; i >= 0 && mag[i] == 0; i--) ; fn = mlen - i - 1; firstNonzeroIntNum = fn + 2; // offset by two to initialize } return fn; } /** {@collect.stats} use serialVersionUID from JDK 1.1. for interoperability */ private static final long serialVersionUID = -8287574255936472291L; /** {@collect.stats} * Serializable fields for BigInteger. * * @serialField signum int * signum of this BigInteger. * @serialField magnitude int[] * magnitude array of this BigInteger. * @serialField bitCount int * number of bits in this BigInteger * @serialField bitLength int * the number of bits in the minimal two's-complement * representation of this BigInteger * @serialField lowestSetBit int * lowest set bit in the twos complement representation */ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("signum", Integer.TYPE), new ObjectStreamField("magnitude", byte[].class), new ObjectStreamField("bitCount", Integer.TYPE), new ObjectStreamField("bitLength", Integer.TYPE), new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE), new ObjectStreamField("lowestSetBit", Integer.TYPE) }; /** {@collect.stats} * Reconstitute the {@code BigInteger} instance from a stream (that is, * deserialize it). The magnitude is read in as an array of bytes * for historical reasons, but it is converted to an array of ints * and the byte array is discarded. * Note: * The current convention is to initialize the cache fields, bitCount, * bitLength and lowestSetBit, to 0 rather than some other marker value. * Therefore, no explicit action to set these fields needs to be taken in * readObject because those fields already have a 0 value be default since * defaultReadObject is not being used. */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { /* * In order to maintain compatibility with previous serialized forms, * the magnitude of a BigInteger is serialized as an array of bytes. * The magnitude field is used as a temporary store for the byte array * that is deserialized. The cached computation fields should be * transient but are serialized for compatibility reasons. */ // prepare to read the alternate persistent fields ObjectInputStream.GetField fields = s.readFields(); // Read the alternate persistent fields that we care about int sign = fields.get("signum", -2); byte[] magnitude = (byte[])fields.get("magnitude", null); // Validate signum if (sign < -1 || sign > 1) { String message = "BigInteger: Invalid signum value"; if (fields.defaulted("signum")) message = "BigInteger: Signum not present in stream"; throw new java.io.StreamCorruptedException(message); } if ((magnitude.length == 0) != (sign == 0)) { String message = "BigInteger: signum-magnitude mismatch"; if (fields.defaulted("magnitude")) message = "BigInteger: Magnitude not present in stream"; throw new java.io.StreamCorruptedException(message); } // Commit final fields via Unsafe unsafe.putIntVolatile(this, signumOffset, sign); // Calculate mag field from magnitude and discard magnitude unsafe.putObjectVolatile(this, magOffset, stripLeadingZeroBytes(magnitude)); } // Support for resetting final fields while deserializing private static final sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe(); private static final long signumOffset; private static final long magOffset; static { try { signumOffset = unsafe.objectFieldOffset (BigInteger.class.getDeclaredField("signum")); magOffset = unsafe.objectFieldOffset (BigInteger.class.getDeclaredField("mag")); } catch (Exception ex) { throw new Error(ex); } } /** {@collect.stats} * Save the {@code BigInteger} instance to a stream. * The magnitude of a BigInteger is serialized as a byte array for * historical reasons. * * @serialData two necessary fields are written as well as obsolete * fields for compatibility with older versions. */ private void writeObject(ObjectOutputStream s) throws IOException { // set the values of the Serializable fields ObjectOutputStream.PutField fields = s.putFields(); fields.put("signum", signum); fields.put("magnitude", magSerializedForm()); // The values written for cached fields are compatible with older // versions, but are ignored in readObject so don't otherwise matter. fields.put("bitCount", -1); fields.put("bitLength", -1); fields.put("lowestSetBit", -2); fields.put("firstNonzeroByteNum", -2); // save them s.writeFields(); } /** {@collect.stats} * Returns the mag array as an array of bytes. */ private byte[] magSerializedForm() { int len = mag.length; int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0])); int byteLen = (bitLen + 7) >>> 3; byte[] result = new byte[byteLen]; for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0; i>=0; i--) { if (bytesCopied == 4) { nextInt = mag[intIndex--]; bytesCopied = 1; } else { nextInt >>>= 8; bytesCopied++; } result[i] = (byte)nextInt; } return result; } }
Java
/* * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.math; /** {@collect.stats} * A class used to represent multiprecision integers that makes efficient * use of allocated space by allowing a number to occupy only part of * an array so that the arrays do not have to be reallocated as often. * When performing an operation with many iterations the array used to * hold a number is only reallocated when necessary and does not have to * be the same size as the number it represents. A mutable number allows * calculations to occur on the same number without having to create * a new number for every step of the calculation as occurs with * BigIntegers. * * @see BigInteger * @author Michael McCloskey * @since 1.3 */ import java.util.Arrays; import static java.math.BigInteger.LONG_MASK; import static java.math.BigDecimal.INFLATED; class MutableBigInteger { /** {@collect.stats} * Holds the magnitude of this MutableBigInteger in big endian order. * The magnitude may start at an offset into the value array, and it may * end before the length of the value array. */ int[] value; /** {@collect.stats} * The number of ints of the value array that are currently used * to hold the magnitude of this MutableBigInteger. The magnitude starts * at an offset and offset + intLen may be less than value.length. */ int intLen; /** {@collect.stats} * The offset into the value array where the magnitude of this * MutableBigInteger begins. */ int offset = 0; // Constants /** {@collect.stats} * MutableBigInteger with one element value array with the value 1. Used by * BigDecimal divideAndRound to increment the quotient. Use this constant * only when the method is not going to modify this object. */ static final MutableBigInteger ONE = new MutableBigInteger(1); // Constructors /** {@collect.stats} * The default constructor. An empty MutableBigInteger is created with * a one word capacity. */ MutableBigInteger() { value = new int[1]; intLen = 0; } /** {@collect.stats} * Construct a new MutableBigInteger with a magnitude specified by * the int val. */ MutableBigInteger(int val) { value = new int[1]; intLen = 1; value[0] = val; } /** {@collect.stats} * Construct a new MutableBigInteger with the specified value array * up to the length of the array supplied. */ MutableBigInteger(int[] val) { value = val; intLen = val.length; } /** {@collect.stats} * Construct a new MutableBigInteger with a magnitude equal to the * specified BigInteger. */ MutableBigInteger(BigInteger b) { intLen = b.mag.length; value = Arrays.copyOf(b.mag, intLen); } /** {@collect.stats} * Construct a new MutableBigInteger with a magnitude equal to the * specified MutableBigInteger. */ MutableBigInteger(MutableBigInteger val) { intLen = val.intLen; value = Arrays.copyOfRange(val.value, val.offset, val.offset + intLen); } /** {@collect.stats} * Internal helper method to return the magnitude array. The caller is not * supposed to modify the returned array. */ private int[] getMagnitudeArray() { if (offset > 0 || value.length != intLen) return Arrays.copyOfRange(value, offset, offset + intLen); return value; } /** {@collect.stats} * Convert this MutableBigInteger to a long value. The caller has to make * sure this MutableBigInteger can be fit into long. */ private long toLong() { assert (intLen <= 2) : "this MutableBigInteger exceeds the range of long"; if (intLen == 0) return 0; long d = value[offset] & LONG_MASK; return (intLen == 2) ? d << 32 | (value[offset + 1] & LONG_MASK) : d; } /** {@collect.stats} * Convert this MutableBigInteger to a BigInteger object. */ BigInteger toBigInteger(int sign) { if (intLen == 0 || sign == 0) return BigInteger.ZERO; return new BigInteger(getMagnitudeArray(), sign); } /** {@collect.stats} * Convert this MutableBigInteger to BigDecimal object with the specified sign * and scale. */ BigDecimal toBigDecimal(int sign, int scale) { if (intLen == 0 || sign == 0) return BigDecimal.valueOf(0, scale); int[] mag = getMagnitudeArray(); int len = mag.length; int d = mag[0]; // If this MutableBigInteger can't be fit into long, we need to // make a BigInteger object for the resultant BigDecimal object. if (len > 2 || (d < 0 && len == 2)) return new BigDecimal(new BigInteger(mag, sign), INFLATED, scale, 0); long v = (len == 2) ? ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) : d & LONG_MASK; return new BigDecimal(null, sign == -1 ? -v : v, scale, 0); } /** {@collect.stats} * Clear out a MutableBigInteger for reuse. */ void clear() { offset = intLen = 0; for (int index=0, n=value.length; index < n; index++) value[index] = 0; } /** {@collect.stats} * Set a MutableBigInteger to zero, removing its offset. */ void reset() { offset = intLen = 0; } /** {@collect.stats} * Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1 * as this MutableBigInteger is numerically less than, equal to, or * greater than <tt>b</tt>. */ final int compare(MutableBigInteger b) { int blen = b.intLen; if (intLen < blen) return -1; if (intLen > blen) return 1; // Add Integer.MIN_VALUE to make the comparison act as unsigned integer // comparison. int[] bval = b.value; for (int i = offset, j = b.offset; i < intLen + offset; i++, j++) { int b1 = value[i] + 0x80000000; int b2 = bval[j] + 0x80000000; if (b1 < b2) return -1; if (b1 > b2) return 1; } return 0; } /** {@collect.stats} * Compare this against half of a MutableBigInteger object (Needed for * remainder tests). * Assumes no leading unnecessary zeros, which holds for results * from divide(). */ final int compareHalf(MutableBigInteger b) { int blen = b.intLen; int len = intLen; if (len <= 0) return blen <=0 ? 0 : -1; if (len > blen) return 1; if (len < blen - 1) return -1; int[] bval = b.value; int bstart = 0; int carry = 0; // Only 2 cases left:len == blen or len == blen - 1 if (len != blen) { // len == blen - 1 if (bval[bstart] == 1) { ++bstart; carry = 0x80000000; } else return -1; } // compare values with right-shifted values of b, // carrying shifted-out bits across words int[] val = value; for (int i = offset, j = bstart; i < len + offset;) { int bv = bval[j++]; long hb = ((bv >>> 1) + carry) & LONG_MASK; long v = val[i++] & LONG_MASK; if (v != hb) return v < hb ? -1 : 1; carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0 } return carry == 0? 0 : -1; } /** {@collect.stats} * Return the index of the lowest set bit in this MutableBigInteger. If the * magnitude of this MutableBigInteger is zero, -1 is returned. */ private final int getLowestSetBit() { if (intLen == 0) return -1; int j, b; for (j=intLen-1; (j>0) && (value[j+offset]==0); j--) ; b = value[j+offset]; if (b==0) return -1; return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b); } /** {@collect.stats} * Return the int in use in this MutableBigInteger at the specified * index. This method is not used because it is not inlined on all * platforms. */ private final int getInt(int index) { return value[offset+index]; } /** {@collect.stats} * Return a long which is equal to the unsigned value of the int in * use in this MutableBigInteger at the specified index. This method is * not used because it is not inlined on all platforms. */ private final long getLong(int index) { return value[offset+index] & LONG_MASK; } /** {@collect.stats} * Ensure that the MutableBigInteger is in normal form, specifically * making sure that there are no leading zeros, and that if the * magnitude is zero, then intLen is zero. */ final void normalize() { if (intLen == 0) { offset = 0; return; } int index = offset; if (value[index] != 0) return; int indexBound = index+intLen; do { index++; } while(index < indexBound && value[index]==0); int numZeros = index - offset; intLen -= numZeros; offset = (intLen==0 ? 0 : offset+numZeros); } /** {@collect.stats} * If this MutableBigInteger cannot hold len words, increase the size * of the value array to len words. */ private final void ensureCapacity(int len) { if (value.length < len) { value = new int[len]; offset = 0; intLen = len; } } /** {@collect.stats} * Convert this MutableBigInteger into an int array with no leading * zeros, of a length that is equal to this MutableBigInteger's intLen. */ int[] toIntArray() { int[] result = new int[intLen]; for(int i=0; i<intLen; i++) result[i] = value[offset+i]; return result; } /** {@collect.stats} * Sets the int at index+offset in this MutableBigInteger to val. * This does not get inlined on all platforms so it is not used * as often as originally intended. */ void setInt(int index, int val) { value[offset + index] = val; } /** {@collect.stats} * Sets this MutableBigInteger's value array to the specified array. * The intLen is set to the specified length. */ void setValue(int[] val, int length) { value = val; intLen = length; offset = 0; } /** {@collect.stats} * Sets this MutableBigInteger's value array to a copy of the specified * array. The intLen is set to the length of the new array. */ void copyValue(MutableBigInteger src) { int len = src.intLen; if (value.length < len) value = new int[len]; System.arraycopy(src.value, src.offset, value, 0, len); intLen = len; offset = 0; } /** {@collect.stats} * Sets this MutableBigInteger's value array to a copy of the specified * array. The intLen is set to the length of the specified array. */ void copyValue(int[] val) { int len = val.length; if (value.length < len) value = new int[len]; System.arraycopy(val, 0, value, 0, len); intLen = len; offset = 0; } /** {@collect.stats} * Returns true iff this MutableBigInteger has a value of one. */ boolean isOne() { return (intLen == 1) && (value[offset] == 1); } /** {@collect.stats} * Returns true iff this MutableBigInteger has a value of zero. */ boolean isZero() { return (intLen == 0); } /** {@collect.stats} * Returns true iff this MutableBigInteger is even. */ boolean isEven() { return (intLen == 0) || ((value[offset + intLen - 1] & 1) == 0); } /** {@collect.stats} * Returns true iff this MutableBigInteger is odd. */ boolean isOdd() { return isZero() ? false : ((value[offset + intLen - 1] & 1) == 1); } /** {@collect.stats} * Returns true iff this MutableBigInteger is in normal form. A * MutableBigInteger is in normal form if it has no leading zeros * after the offset, and intLen + offset <= value.length. */ boolean isNormal() { if (intLen + offset > value.length) return false; if (intLen ==0) return true; return (value[offset] != 0); } /** {@collect.stats} * Returns a String representation of this MutableBigInteger in radix 10. */ public String toString() { BigInteger b = toBigInteger(1); return b.toString(); } /** {@collect.stats} * Right shift this MutableBigInteger n bits. The MutableBigInteger is left * in normal form. */ void rightShift(int n) { if (intLen == 0) return; int nInts = n >>> 5; int nBits = n & 0x1F; this.intLen -= nInts; if (nBits == 0) return; int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]); if (nBits >= bitsInHighWord) { this.primitiveLeftShift(32 - nBits); this.intLen--; } else { primitiveRightShift(nBits); } } /** {@collect.stats} * Left shift this MutableBigInteger n bits. */ void leftShift(int n) { /* * If there is enough storage space in this MutableBigInteger already * the available space will be used. Space to the right of the used * ints in the value array is faster to utilize, so the extra space * will be taken from the right if possible. */ if (intLen == 0) return; int nInts = n >>> 5; int nBits = n&0x1F; int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]); // If shift can be done without moving words, do so if (n <= (32-bitsInHighWord)) { primitiveLeftShift(nBits); return; } int newLen = intLen + nInts +1; if (nBits <= (32-bitsInHighWord)) newLen--; if (value.length < newLen) { // The array must grow int[] result = new int[newLen]; for (int i=0; i<intLen; i++) result[i] = value[offset+i]; setValue(result, newLen); } else if (value.length - offset >= newLen) { // Use space on right for(int i=0; i<newLen - intLen; i++) value[offset+intLen+i] = 0; } else { // Must use space on left for (int i=0; i<intLen; i++) value[i] = value[offset+i]; for (int i=intLen; i<newLen; i++) value[i] = 0; offset = 0; } intLen = newLen; if (nBits == 0) return; if (nBits <= (32-bitsInHighWord)) primitiveLeftShift(nBits); else primitiveRightShift(32 -nBits); } /** {@collect.stats} * A primitive used for division. This method adds in one multiple of the * divisor a back to the dividend result at a specified offset. It is used * when qhat was estimated too large, and must be adjusted. */ private int divadd(int[] a, int[] result, int offset) { long carry = 0; for (int j=a.length-1; j >= 0; j--) { long sum = (a[j] & LONG_MASK) + (result[j+offset] & LONG_MASK) + carry; result[j+offset] = (int)sum; carry = sum >>> 32; } return (int)carry; } /** {@collect.stats} * This method is used for division. It multiplies an n word input a by one * word input x, and subtracts the n word product from q. This is needed * when subtracting qhat*divisor from dividend. */ private int mulsub(int[] q, int[] a, int x, int len, int offset) { long xLong = x & LONG_MASK; long carry = 0; offset += len; for (int j=len-1; j >= 0; j--) { long product = (a[j] & LONG_MASK) * xLong + carry; long difference = q[offset] - product; q[offset--] = (int)difference; carry = (product >>> 32) + (((difference & LONG_MASK) > (((~(int)product) & LONG_MASK))) ? 1:0); } return (int)carry; } /** {@collect.stats} * Right shift this MutableBigInteger n bits, where n is * less than 32. * Assumes that intLen > 0, n > 0 for speed */ private final void primitiveRightShift(int n) { int[] val = value; int n2 = 32 - n; for (int i=offset+intLen-1, c=val[i]; i>offset; i--) { int b = c; c = val[i-1]; val[i] = (c << n2) | (b >>> n); } val[offset] >>>= n; } /** {@collect.stats} * Left shift this MutableBigInteger n bits, where n is * less than 32. * Assumes that intLen > 0, n > 0 for speed */ private final void primitiveLeftShift(int n) { int[] val = value; int n2 = 32 - n; for (int i=offset, c=val[i], m=i+intLen-1; i<m; i++) { int b = c; c = val[i+1]; val[i] = (b << n) | (c >>> n2); } val[offset+intLen-1] <<= n; } /** {@collect.stats} * Adds the contents of two MutableBigInteger objects.The result * is placed within this MutableBigInteger. * The contents of the addend are not changed. */ void add(MutableBigInteger addend) { int x = intLen; int y = addend.intLen; int resultLen = (intLen > addend.intLen ? intLen : addend.intLen); int[] result = (value.length < resultLen ? new int[resultLen] : value); int rstart = result.length-1; long sum; long carry = 0; // Add common parts of both numbers while(x>0 && y>0) { x--; y--; sum = (value[x+offset] & LONG_MASK) + (addend.value[y+addend.offset] & LONG_MASK) + carry; result[rstart--] = (int)sum; carry = sum >>> 32; } // Add remainder of the longer number while(x>0) { x--; if (carry == 0 && result == value && rstart == (x + offset)) return; sum = (value[x+offset] & LONG_MASK) + carry; result[rstart--] = (int)sum; carry = sum >>> 32; } while(y>0) { y--; sum = (addend.value[y+addend.offset] & LONG_MASK) + carry; result[rstart--] = (int)sum; carry = sum >>> 32; } if (carry > 0) { // Result must grow in length resultLen++; if (result.length < resultLen) { int temp[] = new int[resultLen]; // Result one word longer from carry-out; copy low-order // bits into new result. System.arraycopy(result, 0, temp, 1, result.length); temp[0] = 1; result = temp; } else { result[rstart--] = 1; } } value = result; intLen = resultLen; offset = result.length - resultLen; } /** {@collect.stats} * Subtracts the smaller of this and b from the larger and places the * result into this MutableBigInteger. */ int subtract(MutableBigInteger b) { MutableBigInteger a = this; int[] result = value; int sign = a.compare(b); if (sign == 0) { reset(); return 0; } if (sign < 0) { MutableBigInteger tmp = a; a = b; b = tmp; } int resultLen = a.intLen; if (result.length < resultLen) result = new int[resultLen]; long diff = 0; int x = a.intLen; int y = b.intLen; int rstart = result.length - 1; // Subtract common parts of both numbers while (y>0) { x--; y--; diff = (a.value[x+a.offset] & LONG_MASK) - (b.value[y+b.offset] & LONG_MASK) - ((int)-(diff>>32)); result[rstart--] = (int)diff; } // Subtract remainder of longer number while (x>0) { x--; diff = (a.value[x+a.offset] & LONG_MASK) - ((int)-(diff>>32)); result[rstart--] = (int)diff; } value = result; intLen = resultLen; offset = value.length - resultLen; normalize(); return sign; } /** {@collect.stats} * Subtracts the smaller of a and b from the larger and places the result * into the larger. Returns 1 if the answer is in a, -1 if in b, 0 if no * operation was performed. */ private int difference(MutableBigInteger b) { MutableBigInteger a = this; int sign = a.compare(b); if (sign ==0) return 0; if (sign < 0) { MutableBigInteger tmp = a; a = b; b = tmp; } long diff = 0; int x = a.intLen; int y = b.intLen; // Subtract common parts of both numbers while (y>0) { x--; y--; diff = (a.value[a.offset+ x] & LONG_MASK) - (b.value[b.offset+ y] & LONG_MASK) - ((int)-(diff>>32)); a.value[a.offset+x] = (int)diff; } // Subtract remainder of longer number while (x>0) { x--; diff = (a.value[a.offset+ x] & LONG_MASK) - ((int)-(diff>>32)); a.value[a.offset+x] = (int)diff; } a.normalize(); return sign; } /** {@collect.stats} * Multiply the contents of two MutableBigInteger objects. The result is * placed into MutableBigInteger z. The contents of y are not changed. */ void multiply(MutableBigInteger y, MutableBigInteger z) { int xLen = intLen; int yLen = y.intLen; int newLen = xLen + yLen; // Put z into an appropriate state to receive product if (z.value.length < newLen) z.value = new int[newLen]; z.offset = 0; z.intLen = newLen; // The first iteration is hoisted out of the loop to avoid extra add long carry = 0; for (int j=yLen-1, k=yLen+xLen-1; j >= 0; j--, k--) { long product = (y.value[j+y.offset] & LONG_MASK) * (value[xLen-1+offset] & LONG_MASK) + carry; z.value[k] = (int)product; carry = product >>> 32; } z.value[xLen-1] = (int)carry; // Perform the multiplication word by word for (int i = xLen-2; i >= 0; i--) { carry = 0; for (int j=yLen-1, k=yLen+i; j >= 0; j--, k--) { long product = (y.value[j+y.offset] & LONG_MASK) * (value[i+offset] & LONG_MASK) + (z.value[k] & LONG_MASK) + carry; z.value[k] = (int)product; carry = product >>> 32; } z.value[i] = (int)carry; } // Remove leading zeros from product z.normalize(); } /** {@collect.stats} * Multiply the contents of this MutableBigInteger by the word y. The * result is placed into z. */ void mul(int y, MutableBigInteger z) { if (y == 1) { z.copyValue(this); return; } if (y == 0) { z.clear(); return; } // Perform the multiplication word by word long ylong = y & LONG_MASK; int[] zval = (z.value.length<intLen+1 ? new int[intLen + 1] : z.value); long carry = 0; for (int i = intLen-1; i >= 0; i--) { long product = ylong * (value[i+offset] & LONG_MASK) + carry; zval[i+1] = (int)product; carry = product >>> 32; } if (carry == 0) { z.offset = 1; z.intLen = intLen; } else { z.offset = 0; z.intLen = intLen + 1; zval[0] = (int)carry; } z.value = zval; } /** {@collect.stats} * This method is used for division of an n word dividend by a one word * divisor. The quotient is placed into quotient. The one word divisor is * specified by divisor. * * @return the remainder of the division is returned. * */ int divideOneWord(int divisor, MutableBigInteger quotient) { long divisorLong = divisor & LONG_MASK; // Special case of one word dividend if (intLen == 1) { long dividendValue = value[offset] & LONG_MASK; int q = (int) (dividendValue / divisorLong); int r = (int) (dividendValue - q * divisorLong); quotient.value[0] = q; quotient.intLen = (q == 0) ? 0 : 1; quotient.offset = 0; return r; } if (quotient.value.length < intLen) quotient.value = new int[intLen]; quotient.offset = 0; quotient.intLen = intLen; // Normalize the divisor int shift = Integer.numberOfLeadingZeros(divisor); int rem = value[offset]; long remLong = rem & LONG_MASK; if (remLong < divisorLong) { quotient.value[0] = 0; } else { quotient.value[0] = (int)(remLong / divisorLong); rem = (int) (remLong - (quotient.value[0] * divisorLong)); remLong = rem & LONG_MASK; } int xlen = intLen; int[] qWord = new int[2]; while (--xlen > 0) { long dividendEstimate = (remLong<<32) | (value[offset + intLen - xlen] & LONG_MASK); if (dividendEstimate >= 0) { qWord[0] = (int) (dividendEstimate / divisorLong); qWord[1] = (int) (dividendEstimate - qWord[0] * divisorLong); } else { divWord(qWord, dividendEstimate, divisor); } quotient.value[intLen - xlen] = qWord[0]; rem = qWord[1]; remLong = rem & LONG_MASK; } quotient.normalize(); // Unnormalize if (shift > 0) return rem % divisor; else return rem; } /** {@collect.stats} * Calculates the quotient of this div b and places the quotient in the * provided MutableBigInteger objects and the remainder object is returned. * * Uses Algorithm D in Knuth section 4.3.1. * Many optimizations to that algorithm have been adapted from the Colin * Plumb C library. * It special cases one word divisors for speed. The content of b is not * changed. * */ MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) { if (b.intLen == 0) throw new ArithmeticException("BigInteger divide by zero"); // Dividend is zero if (intLen == 0) { quotient.intLen = quotient.offset; return new MutableBigInteger(); } int cmp = compare(b); // Dividend less than divisor if (cmp < 0) { quotient.intLen = quotient.offset = 0; return new MutableBigInteger(this); } // Dividend equal to divisor if (cmp == 0) { quotient.value[0] = quotient.intLen = 1; quotient.offset = 0; return new MutableBigInteger(); } quotient.clear(); // Special case one word divisor if (b.intLen == 1) { int r = divideOneWord(b.value[b.offset], quotient); if (r == 0) return new MutableBigInteger(); return new MutableBigInteger(r); } // Copy divisor value to protect divisor int[] div = Arrays.copyOfRange(b.value, b.offset, b.offset + b.intLen); return divideMagnitude(div, quotient); } /** {@collect.stats} * Internally used to calculate the quotient of this div v and places the * quotient in the provided MutableBigInteger object and the remainder is * returned. * * @return the remainder of the division will be returned. */ long divide(long v, MutableBigInteger quotient) { if (v == 0) throw new ArithmeticException("BigInteger divide by zero"); // Dividend is zero if (intLen == 0) { quotient.intLen = quotient.offset = 0; return 0; } if (v < 0) v = -v; int d = (int)(v >>> 32); quotient.clear(); // Special case on word divisor if (d == 0) return divideOneWord((int)v, quotient) & LONG_MASK; else { int[] div = new int[]{ d, (int)(v & LONG_MASK) }; return divideMagnitude(div, quotient).toLong(); } } /** {@collect.stats} * Divide this MutableBigInteger by the divisor represented by its magnitude * array. The quotient will be placed into the provided quotient object & * the remainder object is returned. */ private MutableBigInteger divideMagnitude(int[] divisor, MutableBigInteger quotient) { // Remainder starts as dividend with space for a leading zero MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]); System.arraycopy(value, offset, rem.value, 1, intLen); rem.intLen = intLen; rem.offset = 1; int nlen = rem.intLen; // Set the quotient size int dlen = divisor.length; int limit = nlen - dlen + 1; if (quotient.value.length < limit) { quotient.value = new int[limit]; quotient.offset = 0; } quotient.intLen = limit; int[] q = quotient.value; // D1 normalize the divisor int shift = Integer.numberOfLeadingZeros(divisor[0]); if (shift > 0) { // First shift will not grow array BigInteger.primitiveLeftShift(divisor, dlen, shift); // But this one might rem.leftShift(shift); } // Must insert leading 0 in rem if its length did not change if (rem.intLen == nlen) { rem.offset = 0; rem.value[0] = 0; rem.intLen++; } int dh = divisor[0]; long dhLong = dh & LONG_MASK; int dl = divisor[1]; int[] qWord = new int[2]; // D2 Initialize j for(int j=0; j<limit; j++) { // D3 Calculate qhat // estimate qhat int qhat = 0; int qrem = 0; boolean skipCorrection = false; int nh = rem.value[j+rem.offset]; int nh2 = nh + 0x80000000; int nm = rem.value[j+1+rem.offset]; if (nh == dh) { qhat = ~0; qrem = nh + nm; skipCorrection = qrem + 0x80000000 < nh2; } else { long nChunk = (((long)nh) << 32) | (nm & LONG_MASK); if (nChunk >= 0) { qhat = (int) (nChunk / dhLong); qrem = (int) (nChunk - (qhat * dhLong)); } else { divWord(qWord, nChunk, dh); qhat = qWord[0]; qrem = qWord[1]; } } if (qhat == 0) continue; if (!skipCorrection) { // Correct qhat long nl = rem.value[j+2+rem.offset] & LONG_MASK; long rs = ((qrem & LONG_MASK) << 32) | nl; long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK); if (unsignedLongCompare(estProduct, rs)) { qhat--; qrem = (int)((qrem & LONG_MASK) + dhLong); if ((qrem & LONG_MASK) >= dhLong) { estProduct -= (dl & LONG_MASK); rs = ((qrem & LONG_MASK) << 32) | nl; if (unsignedLongCompare(estProduct, rs)) qhat--; } } } // D4 Multiply and subtract rem.value[j+rem.offset] = 0; int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset); // D5 Test remainder if (borrow + 0x80000000 > nh2) { // D6 Add back divadd(divisor, rem.value, j+1+rem.offset); qhat--; } // Store the quotient digit q[j] = qhat; } // D7 loop on j // D8 Unnormalize if (shift > 0) rem.rightShift(shift); quotient.normalize(); rem.normalize(); return rem; } /** {@collect.stats} * Compare two longs as if they were unsigned. * Returns true iff one is bigger than two. */ private boolean unsignedLongCompare(long one, long two) { return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE); } /** {@collect.stats} * This method divides a long quantity by an int to estimate * qhat for two multi precision numbers. It is used when * the signed value of n is less than zero. */ private void divWord(int[] result, long n, int d) { long dLong = d & LONG_MASK; if (dLong == 1) { result[0] = (int)n; result[1] = 0; return; } // Approximate the quotient and remainder long q = (n >>> 1) / (dLong >>> 1); long r = n - q*dLong; // Correct the approximation while (r < 0) { r += dLong; q--; } while (r >= dLong) { r -= dLong; q++; } // n - q*dlong == r && 0 <= r <dLong, hence we're done. result[0] = (int)q; result[1] = (int)r; } /** {@collect.stats} * Calculate GCD of this and b. This and b are changed by the computation. */ MutableBigInteger hybridGCD(MutableBigInteger b) { // Use Euclid's algorithm until the numbers are approximately the // same length, then use the binary GCD algorithm to find the GCD. MutableBigInteger a = this; MutableBigInteger q = new MutableBigInteger(); while (b.intLen != 0) { if (Math.abs(a.intLen - b.intLen) < 2) return a.binaryGCD(b); MutableBigInteger r = a.divide(b, q); a = b; b = r; } return a; } /** {@collect.stats} * Calculate GCD of this and v. * Assumes that this and v are not zero. */ private MutableBigInteger binaryGCD(MutableBigInteger v) { // Algorithm B from Knuth section 4.5.2 MutableBigInteger u = this; MutableBigInteger r = new MutableBigInteger(); // step B1 int s1 = u.getLowestSetBit(); int s2 = v.getLowestSetBit(); int k = (s1 < s2) ? s1 : s2; if (k != 0) { u.rightShift(k); v.rightShift(k); } // step B2 boolean uOdd = (k==s1); MutableBigInteger t = uOdd ? v: u; int tsign = uOdd ? -1 : 1; int lb; while ((lb = t.getLowestSetBit()) >= 0) { // steps B3 and B4 t.rightShift(lb); // step B5 if (tsign > 0) u = t; else v = t; // Special case one word numbers if (u.intLen < 2 && v.intLen < 2) { int x = u.value[u.offset]; int y = v.value[v.offset]; x = binaryGcd(x, y); r.value[0] = x; r.intLen = 1; r.offset = 0; if (k > 0) r.leftShift(k); return r; } // step B6 if ((tsign = u.difference(v)) == 0) break; t = (tsign >= 0) ? u : v; } if (k > 0) u.leftShift(k); return u; } /** {@collect.stats} * Calculate GCD of a and b interpreted as unsigned integers. */ static int binaryGcd(int a, int b) { if (b==0) return a; if (a==0) return b; // Right shift a & b till their last bits equal to 1. int aZeros = Integer.numberOfTrailingZeros(a); int bZeros = Integer.numberOfTrailingZeros(b); a >>>= aZeros; b >>>= bZeros; int t = (aZeros < bZeros ? aZeros : bZeros); while (a != b) { if ((a+0x80000000) > (b+0x80000000)) { // a > b as unsigned a -= b; a >>>= Integer.numberOfTrailingZeros(a); } else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); } } return a<<t; } /** {@collect.stats} * Returns the modInverse of this mod p. This and p are not affected by * the operation. */ MutableBigInteger mutableModInverse(MutableBigInteger p) { // Modulus is odd, use Schroeppel's algorithm if (p.isOdd()) return modInverse(p); // Base and modulus are even, throw exception if (isEven()) throw new ArithmeticException("BigInteger not invertible."); // Get even part of modulus expressed as a power of 2 int powersOf2 = p.getLowestSetBit(); // Construct odd part of modulus MutableBigInteger oddMod = new MutableBigInteger(p); oddMod.rightShift(powersOf2); if (oddMod.isOne()) return modInverseMP2(powersOf2); // Calculate 1/a mod oddMod MutableBigInteger oddPart = modInverse(oddMod); // Calculate 1/a mod evenMod MutableBigInteger evenPart = modInverseMP2(powersOf2); // Combine the results using Chinese Remainder Theorem MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2); MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2); MutableBigInteger temp1 = new MutableBigInteger(); MutableBigInteger temp2 = new MutableBigInteger(); MutableBigInteger result = new MutableBigInteger(); oddPart.leftShift(powersOf2); oddPart.multiply(y1, result); evenPart.multiply(oddMod, temp1); temp1.multiply(y2, temp2); result.add(temp2); return result.divide(p, temp1); } /* * Calculate the multiplicative inverse of this mod 2^k. */ MutableBigInteger modInverseMP2(int k) { if (isEven()) throw new ArithmeticException("Non-invertible. (GCD != 1)"); if (k > 64) return euclidModInverse(k); int t = inverseMod32(value[offset+intLen-1]); if (k < 33) { t = (k == 32 ? t : t & ((1 << k) - 1)); return new MutableBigInteger(t); } long pLong = (value[offset+intLen-1] & LONG_MASK); if (intLen > 1) pLong |= ((long)value[offset+intLen-2] << 32); long tLong = t & LONG_MASK; tLong = tLong * (2 - pLong * tLong); // 1 more Newton iter step tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1)); MutableBigInteger result = new MutableBigInteger(new int[2]); result.value[0] = (int)(tLong >>> 32); result.value[1] = (int)tLong; result.intLen = 2; result.normalize(); return result; } /* * Returns the multiplicative inverse of val mod 2^32. Assumes val is odd. */ static int inverseMod32(int val) { // Newton's iteration! int t = val; t *= 2 - val*t; t *= 2 - val*t; t *= 2 - val*t; t *= 2 - val*t; return t; } /* * Calculate the multiplicative inverse of 2^k mod mod, where mod is odd. */ static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) { // Copy the mod to protect original return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k); } /** {@collect.stats} * Calculate the multiplicative inverse of this mod mod, where mod is odd. * This and mod are not changed by the calculation. * * This method implements an algorithm due to Richard Schroeppel, that uses * the same intermediate representation as Montgomery Reduction * ("Montgomery Form"). The algorithm is described in an unpublished * manuscript entitled "Fast Modular Reciprocals." */ private MutableBigInteger modInverse(MutableBigInteger mod) { MutableBigInteger p = new MutableBigInteger(mod); MutableBigInteger f = new MutableBigInteger(this); MutableBigInteger g = new MutableBigInteger(p); SignedMutableBigInteger c = new SignedMutableBigInteger(1); SignedMutableBigInteger d = new SignedMutableBigInteger(); MutableBigInteger temp = null; SignedMutableBigInteger sTemp = null; int k = 0; // Right shift f k times until odd, left shift d k times if (f.isEven()) { int trailingZeros = f.getLowestSetBit(); f.rightShift(trailingZeros); d.leftShift(trailingZeros); k = trailingZeros; } // The Almost Inverse Algorithm while(!f.isOne()) { // If gcd(f, g) != 1, number is not invertible modulo mod if (f.isZero()) throw new ArithmeticException("BigInteger not invertible."); // If f < g exchange f, g and c, d if (f.compare(g) < 0) { temp = f; f = g; g = temp; sTemp = d; d = c; c = sTemp; } // If f == g (mod 4) if (((f.value[f.offset + f.intLen - 1] ^ g.value[g.offset + g.intLen - 1]) & 3) == 0) { f.subtract(g); c.signedSubtract(d); } else { // If f != g (mod 4) f.add(g); c.signedAdd(d); } // Right shift f k times until odd, left shift d k times int trailingZeros = f.getLowestSetBit(); f.rightShift(trailingZeros); d.leftShift(trailingZeros); k += trailingZeros; } while (c.sign < 0) c.signedAdd(p); return fixup(c, p, k); } /* * The Fixup Algorithm * Calculates X such that X = C * 2^(-k) (mod P) * Assumes C<P and P is odd. */ static MutableBigInteger fixup(MutableBigInteger c, MutableBigInteger p, int k) { MutableBigInteger temp = new MutableBigInteger(); // Set r to the multiplicative inverse of p mod 2^32 int r = -inverseMod32(p.value[p.offset+p.intLen-1]); for(int i=0, numWords = k >> 5; i<numWords; i++) { // V = R * c (mod 2^j) int v = r * c.value[c.offset + c.intLen-1]; // c = c + (v * p) p.mul(v, temp); c.add(temp); // c = c / 2^j c.intLen--; } int numBits = k & 0x1f; if (numBits != 0) { // V = R * c (mod 2^j) int v = r * c.value[c.offset + c.intLen-1]; v &= ((1<<numBits) - 1); // c = c + (v * p) p.mul(v, temp); c.add(temp); // c = c / 2^j c.rightShift(numBits); } // In theory, c may be greater than p at this point (Very rare!) while (c.compare(p) >= 0) c.subtract(p); return c; } /** {@collect.stats} * Uses the extended Euclidean algorithm to compute the modInverse of base * mod a modulus that is a power of 2. The modulus is 2^k. */ MutableBigInteger euclidModInverse(int k) { MutableBigInteger b = new MutableBigInteger(1); b.leftShift(k); MutableBigInteger mod = new MutableBigInteger(b); MutableBigInteger a = new MutableBigInteger(this); MutableBigInteger q = new MutableBigInteger(); MutableBigInteger r = b.divide(a, q); MutableBigInteger swapper = b; // swap b & r b = r; r = swapper; MutableBigInteger t1 = new MutableBigInteger(q); MutableBigInteger t0 = new MutableBigInteger(1); MutableBigInteger temp = new MutableBigInteger(); while (!b.isOne()) { r = a.divide(b, q); if (r.intLen == 0) throw new ArithmeticException("BigInteger not invertible."); swapper = r; a = swapper; if (q.intLen == 1) t1.mul(q.value[q.offset], temp); else q.multiply(t1, temp); swapper = q; q = temp; temp = swapper; t0.add(q); if (a.isOne()) return t0; r = b.divide(a, q); if (r.intLen == 0) throw new ArithmeticException("BigInteger not invertible."); swapper = b; b = r; if (q.intLen == 1) t0.mul(q.value[q.offset], temp); else q.multiply(t0, temp); swapper = q; q = temp; temp = swapper; t1.add(q); } mod.subtract(t1); return mod; } }
Java
/* * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Portions Copyright IBM Corporation, 2001. All Rights Reserved. */ package java.math; /** {@collect.stats} * Specifies a <i>rounding behavior</i> for numerical operations * capable of discarding precision. Each rounding mode indicates how * the least significant returned digit of a rounded result is to be * calculated. If fewer digits are returned than the digits needed to * represent the exact numerical result, the discarded digits will be * referred to as the <i>discarded fraction</i> regardless the digits' * contribution to the value of the number. In other words, * considered as a numerical value, the discarded fraction could have * an absolute value greater than one. * * <p>Each rounding mode description includes a table listing how * different two-digit decimal values would round to a one digit * decimal value under the rounding mode in question. The result * column in the tables could be gotten by creating a * {@code BigDecimal} number with the specified value, forming a * {@link MathContext} object with the proper settings * ({@code precision} set to {@code 1}, and the * {@code roundingMode} set to the rounding mode in question), and * calling {@link BigDecimal#round round} on this number with the * proper {@code MathContext}. A summary table showing the results * of these rounding operations for all rounding modes appears below. * *<p> *<table border> * <caption top><h3>Summary of Rounding Operations Under Different Rounding Modes</h3></caption> * <tr><th></th><th colspan=8>Result of rounding input to one digit with the given * rounding mode</th> * <tr valign=top> * <th>Input Number</th> <th>{@code UP}</th> * <th>{@code DOWN}</th> * <th>{@code CEILING}</th> * <th>{@code FLOOR}</th> * <th>{@code HALF_UP}</th> * <th>{@code HALF_DOWN}</th> * <th>{@code HALF_EVEN}</th> * <th>{@code UNNECESSARY}</th> * * <tr align=right><td>5.5</td> <td>6</td> <td>5</td> <td>6</td> <td>5</td> <td>6</td> <td>5</td> <td>6</td> <td>throw {@code ArithmeticException}</td> * <tr align=right><td>2.5</td> <td>3</td> <td>2</td> <td>3</td> <td>2</td> <td>3</td> <td>2</td> <td>2</td> <td>throw {@code ArithmeticException}</td> * <tr align=right><td>1.6</td> <td>2</td> <td>1</td> <td>2</td> <td>1</td> <td>2</td> <td>2</td> <td>2</td> <td>throw {@code ArithmeticException}</td> * <tr align=right><td>1.1</td> <td>2</td> <td>1</td> <td>2</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>throw {@code ArithmeticException}</td> * <tr align=right><td>1.0</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> * <tr align=right><td>-1.0</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>-1</td> * <tr align=right><td>-1.1</td> <td>-2</td> <td>-1</td> <td>-1</td> <td>-2</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>throw {@code ArithmeticException}</td> * <tr align=right><td>-1.6</td> <td>-2</td> <td>-1</td> <td>-1</td> <td>-2</td> <td>-2</td> <td>-2</td> <td>-2</td> <td>throw {@code ArithmeticException}</td> * <tr align=right><td>-2.5</td> <td>-3</td> <td>-2</td> <td>-2</td> <td>-3</td> <td>-3</td> <td>-2</td> <td>-2</td> <td>throw {@code ArithmeticException}</td> * <tr align=right><td>-5.5</td> <td>-6</td> <td>-5</td> <td>-5</td> <td>-6</td> <td>-6</td> <td>-5</td> <td>-6</td> <td>throw {@code ArithmeticException}</td> *</table> * * * <p>This {@code enum} is intended to replace the integer-based * enumeration of rounding mode constants in {@link BigDecimal} * ({@link BigDecimal#ROUND_UP}, {@link BigDecimal#ROUND_DOWN}, * etc. ). * * @see BigDecimal * @see MathContext * @author Josh Bloch * @author Mike Cowlishaw * @author Joseph D. Darcy * @since 1.5 */ public enum RoundingMode { /** {@collect.stats} * Rounding mode to round away from zero. Always increments the * digit prior to a non-zero discarded fraction. Note that this * rounding mode never decreases the magnitude of the calculated * value. * *<p>Example: *<table border> *<tr valign=top><th>Input Number</th> * <th>Input rounded to one digit<br> with {@code UP} rounding *<tr align=right><td>5.5</td> <td>6</td> *<tr align=right><td>2.5</td> <td>3</td> *<tr align=right><td>1.6</td> <td>2</td> *<tr align=right><td>1.1</td> <td>2</td> *<tr align=right><td>1.0</td> <td>1</td> *<tr align=right><td>-1.0</td> <td>-1</td> *<tr align=right><td>-1.1</td> <td>-2</td> *<tr align=right><td>-1.6</td> <td>-2</td> *<tr align=right><td>-2.5</td> <td>-3</td> *<tr align=right><td>-5.5</td> <td>-6</td> *</table> */ UP(BigDecimal.ROUND_UP), /** {@collect.stats} * Rounding mode to round towards zero. Never increments the digit * prior to a discarded fraction (i.e., truncates). Note that this * rounding mode never increases the magnitude of the calculated value. * *<p>Example: *<table border> *<tr valign=top><th>Input Number</th> * <th>Input rounded to one digit<br> with {@code DOWN} rounding *<tr align=right><td>5.5</td> <td>5</td> *<tr align=right><td>2.5</td> <td>2</td> *<tr align=right><td>1.6</td> <td>1</td> *<tr align=right><td>1.1</td> <td>1</td> *<tr align=right><td>1.0</td> <td>1</td> *<tr align=right><td>-1.0</td> <td>-1</td> *<tr align=right><td>-1.1</td> <td>-1</td> *<tr align=right><td>-1.6</td> <td>-1</td> *<tr align=right><td>-2.5</td> <td>-2</td> *<tr align=right><td>-5.5</td> <td>-5</td> *</table> */ DOWN(BigDecimal.ROUND_DOWN), /** {@collect.stats} * Rounding mode to round towards positive infinity. If the * result is positive, behaves as for {@code RoundingMode.UP}; * if negative, behaves as for {@code RoundingMode.DOWN}. Note * that this rounding mode never decreases the calculated value. * *<p>Example: *<table border> *<tr valign=top><th>Input Number</th> * <th>Input rounded to one digit<br> with {@code CEILING} rounding *<tr align=right><td>5.5</td> <td>6</td> *<tr align=right><td>2.5</td> <td>3</td> *<tr align=right><td>1.6</td> <td>2</td> *<tr align=right><td>1.1</td> <td>2</td> *<tr align=right><td>1.0</td> <td>1</td> *<tr align=right><td>-1.0</td> <td>-1</td> *<tr align=right><td>-1.1</td> <td>-1</td> *<tr align=right><td>-1.6</td> <td>-1</td> *<tr align=right><td>-2.5</td> <td>-2</td> *<tr align=right><td>-5.5</td> <td>-5</td> *</table> */ CEILING(BigDecimal.ROUND_CEILING), /** {@collect.stats} * Rounding mode to round towards negative infinity. If the * result is positive, behave as for {@code RoundingMode.DOWN}; * if negative, behave as for {@code RoundingMode.UP}. Note that * this rounding mode never increases the calculated value. * *<p>Example: *<table border> *<tr valign=top><th>Input Number</th> * <th>Input rounded to one digit<br> with {@code FLOOR} rounding *<tr align=right><td>5.5</td> <td>5</td> *<tr align=right><td>2.5</td> <td>2</td> *<tr align=right><td>1.6</td> <td>1</td> *<tr align=right><td>1.1</td> <td>1</td> *<tr align=right><td>1.0</td> <td>1</td> *<tr align=right><td>-1.0</td> <td>-1</td> *<tr align=right><td>-1.1</td> <td>-2</td> *<tr align=right><td>-1.6</td> <td>-2</td> *<tr align=right><td>-2.5</td> <td>-3</td> *<tr align=right><td>-5.5</td> <td>-6</td> *</table> */ FLOOR(BigDecimal.ROUND_FLOOR), /** {@collect.stats} * Rounding mode to round towards {@literal "nearest neighbor"} * unless both neighbors are equidistant, in which case round up. * Behaves as for {@code RoundingMode.UP} if the discarded * fraction is &ge; 0.5; otherwise, behaves as for * {@code RoundingMode.DOWN}. Note that this is the rounding * mode commonly taught at school. * *<p>Example: *<table border> *<tr valign=top><th>Input Number</th> * <th>Input rounded to one digit<br> with {@code HALF_UP} rounding *<tr align=right><td>5.5</td> <td>6</td> *<tr align=right><td>2.5</td> <td>3</td> *<tr align=right><td>1.6</td> <td>2</td> *<tr align=right><td>1.1</td> <td>1</td> *<tr align=right><td>1.0</td> <td>1</td> *<tr align=right><td>-1.0</td> <td>-1</td> *<tr align=right><td>-1.1</td> <td>-1</td> *<tr align=right><td>-1.6</td> <td>-2</td> *<tr align=right><td>-2.5</td> <td>-3</td> *<tr align=right><td>-5.5</td> <td>-6</td> *</table> */ HALF_UP(BigDecimal.ROUND_HALF_UP), /** {@collect.stats} * Rounding mode to round towards {@literal "nearest neighbor"} * unless both neighbors are equidistant, in which case round * down. Behaves as for {@code RoundingMode.UP} if the discarded * fraction is &gt; 0.5; otherwise, behaves as for * {@code RoundingMode.DOWN}. * *<p>Example: *<table border> *<tr valign=top><th>Input Number</th> * <th>Input rounded to one digit<br> with {@code HALF_DOWN} rounding *<tr align=right><td>5.5</td> <td>5</td> *<tr align=right><td>2.5</td> <td>2</td> *<tr align=right><td>1.6</td> <td>2</td> *<tr align=right><td>1.1</td> <td>1</td> *<tr align=right><td>1.0</td> <td>1</td> *<tr align=right><td>-1.0</td> <td>-1</td> *<tr align=right><td>-1.1</td> <td>-1</td> *<tr align=right><td>-1.6</td> <td>-2</td> *<tr align=right><td>-2.5</td> <td>-2</td> *<tr align=right><td>-5.5</td> <td>-5</td> *</table> */ HALF_DOWN(BigDecimal.ROUND_HALF_DOWN), /** {@collect.stats} * Rounding mode to round towards the {@literal "nearest neighbor"} * unless both neighbors are equidistant, in which case, round * towards the even neighbor. Behaves as for * {@code RoundingMode.HALF_UP} if the digit to the left of the * discarded fraction is odd; behaves as for * {@code RoundingMode.HALF_DOWN} if it's even. Note that this * is the rounding mode that statistically minimizes cumulative * error when applied repeatedly over a sequence of calculations. * It is sometimes known as {@literal "Banker's rounding,"} and is * chiefly used in the USA. This rounding mode is analogous to * the rounding policy used for {@code float} and {@code double} * arithmetic in Java. * *<p>Example: *<table border> *<tr valign=top><th>Input Number</th> * <th>Input rounded to one digit<br> with {@code HALF_EVEN} rounding *<tr align=right><td>5.5</td> <td>6</td> *<tr align=right><td>2.5</td> <td>2</td> *<tr align=right><td>1.6</td> <td>2</td> *<tr align=right><td>1.1</td> <td>1</td> *<tr align=right><td>1.0</td> <td>1</td> *<tr align=right><td>-1.0</td> <td>-1</td> *<tr align=right><td>-1.1</td> <td>-1</td> *<tr align=right><td>-1.6</td> <td>-2</td> *<tr align=right><td>-2.5</td> <td>-2</td> *<tr align=right><td>-5.5</td> <td>-6</td> *</table> */ HALF_EVEN(BigDecimal.ROUND_HALF_EVEN), /** {@collect.stats} * Rounding mode to assert that the requested operation has an exact * result, hence no rounding is necessary. If this rounding mode is * specified on an operation that yields an inexact result, an * {@code ArithmeticException} is thrown. *<p>Example: *<table border> *<tr valign=top><th>Input Number</th> * <th>Input rounded to one digit<br> with {@code UNNECESSARY} rounding *<tr align=right><td>5.5</td> <td>throw {@code ArithmeticException}</td> *<tr align=right><td>2.5</td> <td>throw {@code ArithmeticException}</td> *<tr align=right><td>1.6</td> <td>throw {@code ArithmeticException}</td> *<tr align=right><td>1.1</td> <td>throw {@code ArithmeticException}</td> *<tr align=right><td>1.0</td> <td>1</td> *<tr align=right><td>-1.0</td> <td>-1</td> *<tr align=right><td>-1.1</td> <td>throw {@code ArithmeticException}</td> *<tr align=right><td>-1.6</td> <td>throw {@code ArithmeticException}</td> *<tr align=right><td>-2.5</td> <td>throw {@code ArithmeticException}</td> *<tr align=right><td>-5.5</td> <td>throw {@code ArithmeticException}</td> *</table> */ UNNECESSARY(BigDecimal.ROUND_UNNECESSARY); // Corresponding BigDecimal rounding constant final int oldMode; /** {@collect.stats} * Constructor * * @param oldMode The {@code BigDecimal} constant corresponding to * this mode */ private RoundingMode(int oldMode) { this.oldMode = oldMode; } /** {@collect.stats} * Returns the {@code RoundingMode} object corresponding to a * legacy integer rounding mode constant in {@link BigDecimal}. * * @param rm legacy integer rounding mode to convert * @return {@code RoundingMode} corresponding to the given integer. * @throws IllegalArgumentException integer is out of range */ public static RoundingMode valueOf(int rm) { switch(rm) { case BigDecimal.ROUND_UP: return UP; case BigDecimal.ROUND_DOWN: return DOWN; case BigDecimal.ROUND_CEILING: return CEILING; case BigDecimal.ROUND_FLOOR: return FLOOR; case BigDecimal.ROUND_HALF_UP: return HALF_UP; case BigDecimal.ROUND_HALF_DOWN: return HALF_DOWN; case BigDecimal.ROUND_HALF_EVEN: return HALF_EVEN; case BigDecimal.ROUND_UNNECESSARY: return UNNECESSARY; default: throw new IllegalArgumentException("argument out of range"); } } }
Java
/* * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Portions Copyright IBM Corporation, 2001. All Rights Reserved. */ package java.math; import java.util.Arrays; import static java.math.BigInteger.LONG_MASK; /** {@collect.stats} * Immutable, arbitrary-precision signed decimal numbers. A * {@code BigDecimal} consists of an arbitrary precision integer * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero * or positive, the scale is the number of digits to the right of the * decimal point. If negative, the unscaled value of the number is * multiplied by ten to the power of the negation of the scale. The * value of the number represented by the {@code BigDecimal} is * therefore <tt>(unscaledValue &times; 10<sup>-scale</sup>)</tt>. * * <p>The {@code BigDecimal} class provides operations for * arithmetic, scale manipulation, rounding, comparison, hashing, and * format conversion. The {@link #toString} method provides a * canonical representation of a {@code BigDecimal}. * * <p>The {@code BigDecimal} class gives its user complete control * over rounding behavior. If no rounding mode is specified and the * exact result cannot be represented, an exception is thrown; * otherwise, calculations can be carried out to a chosen precision * and rounding mode by supplying an appropriate {@link MathContext} * object to the operation. In either case, eight <em>rounding * modes</em> are provided for the control of rounding. Using the * integer fields in this class (such as {@link #ROUND_HALF_UP}) to * represent rounding mode is largely obsolete; the enumeration values * of the {@code RoundingMode} {@code enum}, (such as {@link * RoundingMode#HALF_UP}) should be used instead. * * <p>When a {@code MathContext} object is supplied with a precision * setting of 0 (for example, {@link MathContext#UNLIMITED}), * arithmetic operations are exact, as are the arithmetic methods * which take no {@code MathContext} object. (This is the only * behavior that was supported in releases prior to 5.) As a * corollary of computing the exact result, the rounding mode setting * of a {@code MathContext} object with a precision setting of 0 is * not used and thus irrelevant. In the case of divide, the exact * quotient could have an infinitely long decimal expansion; for * example, 1 divided by 3. If the quotient has a nonterminating * decimal expansion and the operation is specified to return an exact * result, an {@code ArithmeticException} is thrown. Otherwise, the * exact result of the division is returned, as done for other * operations. * * <p>When the precision setting is not 0, the rules of * {@code BigDecimal} arithmetic are broadly compatible with selected * modes of operation of the arithmetic defined in ANSI X3.274-1996 * and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those * standards, {@code BigDecimal} includes many rounding modes, which * were mandatory for division in {@code BigDecimal} releases prior * to 5. Any conflicts between these ANSI standards and the * {@code BigDecimal} specification are resolved in favor of * {@code BigDecimal}. * * <p>Since the same numerical value can have different * representations (with different scales), the rules of arithmetic * and rounding must specify both the numerical result and the scale * used in the result's representation. * * * <p>In general the rounding modes and precision setting determine * how operations return results with a limited number of digits when * the exact result has more digits (perhaps infinitely many in the * case of division) than the number of digits returned. * * First, the * total number of digits to return is specified by the * {@code MathContext}'s {@code precision} setting; this determines * the result's <i>precision</i>. The digit count starts from the * leftmost nonzero digit of the exact result. The rounding mode * determines how any discarded trailing digits affect the returned * result. * * <p>For all arithmetic operators , the operation is carried out as * though an exact intermediate result were first calculated and then * rounded to the number of digits specified by the precision setting * (if necessary), using the selected rounding mode. If the exact * result is not returned, some digit positions of the exact result * are discarded. When rounding increases the magnitude of the * returned result, it is possible for a new digit position to be * created by a carry propagating to a leading {@literal "9"} digit. * For example, rounding the value 999.9 to three digits rounding up * would be numerically equal to one thousand, represented as * 100&times;10<sup>1</sup>. In such cases, the new {@literal "1"} is * the leading digit position of the returned result. * * <p>Besides a logical exact result, each arithmetic operation has a * preferred scale for representing a result. The preferred * scale for each operation is listed in the table below. * * <table border> * <caption top><h3>Preferred Scales for Results of Arithmetic Operations * </h3></caption> * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr> * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td> * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td> * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td> * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td> * </table> * * These scales are the ones used by the methods which return exact * arithmetic results; except that an exact divide may have to use a * larger scale since the exact result may have more digits. For * example, {@code 1/32} is {@code 0.03125}. * * <p>Before rounding, the scale of the logical exact intermediate * result is the preferred scale for that operation. If the exact * numerical result cannot be represented in {@code precision} * digits, rounding selects the set of digits to return and the scale * of the result is reduced from the scale of the intermediate result * to the least scale which can represent the {@code precision} * digits actually returned. If the exact result can be represented * with at most {@code precision} digits, the representation * of the result with the scale closest to the preferred scale is * returned. In particular, an exactly representable quotient may be * represented in fewer than {@code precision} digits by removing * trailing zeros and decreasing the scale. For example, rounding to * three digits using the {@linkplain RoundingMode#FLOOR floor} * rounding mode, <br> * * {@code 19/100 = 0.19 // integer=19, scale=2} <br> * * but<br> * * {@code 21/110 = 0.190 // integer=190, scale=3} <br> * * <p>Note that for add, subtract, and multiply, the reduction in * scale will equal the number of digit positions of the exact result * which are discarded. If the rounding causes a carry propagation to * create a new high-order digit position, an additional digit of the * result is discarded than when no new digit position is created. * * <p>Other methods may have slightly different rounding semantics. * For example, the result of the {@code pow} method using the * {@linkplain #pow(int, MathContext) specified algorithm} can * occasionally differ from the rounded mathematical result by more * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>. * * <p>Two types of operations are provided for manipulating the scale * of a {@code BigDecimal}: scaling/rounding operations and decimal * point motion operations. Scaling/rounding operations ({@link * #setScale setScale} and {@link #round round}) return a * {@code BigDecimal} whose value is approximately (or exactly) equal * to that of the operand, but whose scale or precision is the * specified value; that is, they increase or decrease the precision * of the stored number with minimal effect on its value. Decimal * point motion operations ({@link #movePointLeft movePointLeft} and * {@link #movePointRight movePointRight}) return a * {@code BigDecimal} created from the operand by moving the decimal * point a specified distance in the specified direction. * * <p>For the sake of brevity and clarity, pseudo-code is used * throughout the descriptions of {@code BigDecimal} methods. The * pseudo-code expression {@code (i + j)} is shorthand for "a * {@code BigDecimal} whose value is that of the {@code BigDecimal} * {@code i} added to that of the {@code BigDecimal} * {@code j}." The pseudo-code expression {@code (i == j)} is * shorthand for "{@code true} if and only if the * {@code BigDecimal} {@code i} represents the same value as the * {@code BigDecimal} {@code j}." Other pseudo-code expressions * are interpreted similarly. Square brackets are used to represent * the particular {@code BigInteger} and scale pair defining a * {@code BigDecimal} value; for example [19, 2] is the * {@code BigDecimal} numerically equal to 0.19 having a scale of 2. * * <p>Note: care should be exercised if {@code BigDecimal} objects * are used as keys in a {@link java.util.SortedMap SortedMap} or * elements in a {@link java.util.SortedSet SortedSet} since * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent * with equals</i>. See {@link Comparable}, {@link * java.util.SortedMap} or {@link java.util.SortedSet} for more * information. * * <p>All methods and constructors for this class throw * {@code NullPointerException} when passed a {@code null} object * reference for any input parameter. * * @see BigInteger * @see MathContext * @see RoundingMode * @see java.util.SortedMap * @see java.util.SortedSet * @author Josh Bloch * @author Mike Cowlishaw * @author Joseph D. Darcy */ public class BigDecimal extends Number implements Comparable<BigDecimal> { /** {@collect.stats} * The unscaled value of this BigDecimal, as returned by {@link * #unscaledValue}. * * @serial * @see #unscaledValue */ private volatile BigInteger intVal; /** {@collect.stats} * The scale of this BigDecimal, as returned by {@link #scale}. * * @serial * @see #scale */ private int scale; // Note: this may have any value, so // calculations must be done in longs /** {@collect.stats} * The number of decimal digits in this BigDecimal, or 0 if the * number of digits are not known (lookaside information). If * nonzero, the value is guaranteed correct. Use the precision() * method to obtain and set the value if it might be 0. This * field is mutable until set nonzero. * * @since 1.5 */ private transient int precision; /** {@collect.stats} * Used to store the canonical string representation, if computed. */ private transient String stringCache; /** {@collect.stats} * Sentinel value for {@link #intCompact} indicating the * significand information is only available from {@code intVal}. */ static final long INFLATED = Long.MIN_VALUE; /** {@collect.stats} * If the absolute value of the significand of this BigDecimal is * less than or equal to {@code Long.MAX_VALUE}, the value can be * compactly stored in this field and used in computations. */ private transient long intCompact; // All 18-digit base ten strings fit into a long; not all 19-digit // strings will private static final int MAX_COMPACT_DIGITS = 18; private static final int MAX_BIGINT_BITS = 62; /* Appease the serialization gods */ private static final long serialVersionUID = 6108874887143696463L; private static final ThreadLocal<StringBuilderHelper> threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() { @Override protected StringBuilderHelper initialValue() { return new StringBuilderHelper(); } }; // Cache of common small BigDecimal values. private static final BigDecimal zeroThroughTen[] = { new BigDecimal(BigInteger.ZERO, 0, 0, 1), new BigDecimal(BigInteger.ONE, 1, 0, 1), new BigDecimal(BigInteger.valueOf(2), 2, 0, 1), new BigDecimal(BigInteger.valueOf(3), 3, 0, 1), new BigDecimal(BigInteger.valueOf(4), 4, 0, 1), new BigDecimal(BigInteger.valueOf(5), 5, 0, 1), new BigDecimal(BigInteger.valueOf(6), 6, 0, 1), new BigDecimal(BigInteger.valueOf(7), 7, 0, 1), new BigDecimal(BigInteger.valueOf(8), 8, 0, 1), new BigDecimal(BigInteger.valueOf(9), 9, 0, 1), new BigDecimal(BigInteger.TEN, 10, 0, 2), }; // Cache of zero scaled by 0 - 15 private static final BigDecimal[] ZERO_SCALED_BY = { zeroThroughTen[0], new BigDecimal(BigInteger.ZERO, 0, 1, 1), new BigDecimal(BigInteger.ZERO, 0, 2, 1), new BigDecimal(BigInteger.ZERO, 0, 3, 1), new BigDecimal(BigInteger.ZERO, 0, 4, 1), new BigDecimal(BigInteger.ZERO, 0, 5, 1), new BigDecimal(BigInteger.ZERO, 0, 6, 1), new BigDecimal(BigInteger.ZERO, 0, 7, 1), new BigDecimal(BigInteger.ZERO, 0, 8, 1), new BigDecimal(BigInteger.ZERO, 0, 9, 1), new BigDecimal(BigInteger.ZERO, 0, 10, 1), new BigDecimal(BigInteger.ZERO, 0, 11, 1), new BigDecimal(BigInteger.ZERO, 0, 12, 1), new BigDecimal(BigInteger.ZERO, 0, 13, 1), new BigDecimal(BigInteger.ZERO, 0, 14, 1), new BigDecimal(BigInteger.ZERO, 0, 15, 1), }; // Half of Long.MIN_VALUE & Long.MAX_VALUE. private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2; private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2; // Constants /** {@collect.stats} * The value 0, with a scale of 0. * * @since 1.5 */ public static final BigDecimal ZERO = zeroThroughTen[0]; /** {@collect.stats} * The value 1, with a scale of 0. * * @since 1.5 */ public static final BigDecimal ONE = zeroThroughTen[1]; /** {@collect.stats} * The value 10, with a scale of 0. * * @since 1.5 */ public static final BigDecimal TEN = zeroThroughTen[10]; // Constructors /** {@collect.stats} * Trusted package private constructor. * Trusted simply means if val is INFLATED, intVal could not be null and * if intVal is null, val could not be INFLATED. */ BigDecimal(BigInteger intVal, long val, int scale, int prec) { this.scale = scale; this.precision = prec; this.intCompact = val; this.intVal = intVal; } /** {@collect.stats} * Translates a character array representation of a * {@code BigDecimal} into a {@code BigDecimal}, accepting the * same sequence of characters as the {@link #BigDecimal(String)} * constructor, while allowing a sub-array to be specified. * * <p>Note that if the sequence of characters is already available * within a character array, using this constructor is faster than * converting the {@code char} array to string and using the * {@code BigDecimal(String)} constructor . * * @param in {@code char} array that is the source of characters. * @param offset first character in the array to inspect. * @param len number of characters to consider. * @throws NumberFormatException if {@code in} is not a valid * representation of a {@code BigDecimal} or the defined subarray * is not wholly within {@code in}. * @since 1.5 */ public BigDecimal(char[] in, int offset, int len) { // protect against huge length. if (offset+len > in.length || offset < 0) throw new NumberFormatException(); // This is the primary string to BigDecimal constructor; all // incoming strings end up here; it uses explicit (inline) // parsing for speed and generates at most one intermediate // (temporary) object (a char[] array) for non-compact case. // Use locals for all fields values until completion int prec = 0; // record precision value int scl = 0; // record scale value long rs = 0; // the compact value in long BigInteger rb = null; // the inflated value in BigInteger // use array bounds checking to handle too-long, len == 0, // bad offset, etc. try { // handle the sign boolean isneg = false; // assume positive if (in[offset] == '-') { isneg = true; // leading minus means negative offset++; len--; } else if (in[offset] == '+') { // leading + allowed offset++; len--; } // should now be at numeric part of the significand boolean dot = false; // true when there is a '.' int cfirst = offset; // record start of integer long exp = 0; // exponent char c; // current character boolean isCompact = (len <= MAX_COMPACT_DIGITS); // integer significand array & idx is the index to it. The array // is ONLY used when we can't use a compact representation. char coeff[] = isCompact ? null : new char[len]; int idx = 0; for (; len > 0; offset++, len--) { c = in[offset]; // have digit if ((c >= '0' && c <= '9') || Character.isDigit(c)) { // First compact case, we need not to preserve the character // and we can just compute the value in place. if (isCompact) { int digit = Character.digit(c, 10); if (digit == 0) { if (prec == 0) prec = 1; else if (rs != 0) { rs *= 10; ++prec; } // else digit is a redundant leading zero } else { if (prec != 1 || rs != 0) ++prec; // prec unchanged if preceded by 0s rs = rs * 10 + digit; } } else { // the unscaled value is likely a BigInteger object. if (c == '0' || Character.digit(c, 10) == 0) { if (prec == 0) { coeff[idx] = c; prec = 1; } else if (idx != 0) { coeff[idx++] = c; ++prec; } // else c must be a redundant leading zero } else { if (prec != 1 || idx != 0) ++prec; // prec unchanged if preceded by 0s coeff[idx++] = c; } } if (dot) ++scl; continue; } // have dot if (c == '.') { // have dot if (dot) // two dots throw new NumberFormatException(); dot = true; continue; } // exponent expected if ((c != 'e') && (c != 'E')) throw new NumberFormatException(); offset++; c = in[offset]; len--; boolean negexp = (c == '-'); // optional sign if (negexp || c == '+') { offset++; c = in[offset]; len--; } if (len <= 0) // no exponent digits throw new NumberFormatException(); // skip leading zeros in the exponent while (len > 10 && Character.digit(c, 10) == 0) { offset++; c = in[offset]; len--; } if (len > 10) // too many nonzero exponent digits throw new NumberFormatException(); // c now holds first digit of exponent for (;; len--) { int v; if (c >= '0' && c <= '9') { v = c - '0'; } else { v = Character.digit(c, 10); if (v < 0) // not a digit throw new NumberFormatException(); } exp = exp * 10 + v; if (len == 1) break; // that was final character offset++; c = in[offset]; } if (negexp) // apply sign exp = -exp; // Next test is required for backwards compatibility if ((int)exp != exp) // overflow throw new NumberFormatException(); break; // [saves a test] } // here when no characters left if (prec == 0) // no digits found throw new NumberFormatException(); // Adjust scale if exp is not zero. if (exp != 0) { // had significant exponent // Can't call checkScale which relies on proper fields value long adjustedScale = scl - exp; if (adjustedScale > Integer.MAX_VALUE || adjustedScale < Integer.MIN_VALUE) throw new NumberFormatException("Scale out of range."); scl = (int)adjustedScale; } // Remove leading zeros from precision (digits count) if (isCompact) { rs = isneg ? -rs : rs; } else { char quick[]; if (!isneg) { quick = (coeff.length != prec) ? Arrays.copyOf(coeff, prec) : coeff; } else { quick = new char[prec + 1]; quick[0] = '-'; System.arraycopy(coeff, 0, quick, 1, prec); } rb = new BigInteger(quick); rs = compactValFor(rb); } } catch (ArrayIndexOutOfBoundsException e) { throw new NumberFormatException(); } catch (NegativeArraySizeException e) { throw new NumberFormatException(); } this.scale = scl; this.precision = prec; this.intCompact = rs; this.intVal = (rs != INFLATED) ? null : rb; } /** {@collect.stats} * Translates a character array representation of a * {@code BigDecimal} into a {@code BigDecimal}, accepting the * same sequence of characters as the {@link #BigDecimal(String)} * constructor, while allowing a sub-array to be specified and * with rounding according to the context settings. * * <p>Note that if the sequence of characters is already available * within a character array, using this constructor is faster than * converting the {@code char} array to string and using the * {@code BigDecimal(String)} constructor . * * @param in {@code char} array that is the source of characters. * @param offset first character in the array to inspect. * @param len number of characters to consider.. * @param mc the context to use. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @throws NumberFormatException if {@code in} is not a valid * representation of a {@code BigDecimal} or the defined subarray * is not wholly within {@code in}. * @since 1.5 */ public BigDecimal(char[] in, int offset, int len, MathContext mc) { this(in, offset, len); if (mc.precision > 0) roundThis(mc); } /** {@collect.stats} * Translates a character array representation of a * {@code BigDecimal} into a {@code BigDecimal}, accepting the * same sequence of characters as the {@link #BigDecimal(String)} * constructor. * * <p>Note that if the sequence of characters is already available * as a character array, using this constructor is faster than * converting the {@code char} array to string and using the * {@code BigDecimal(String)} constructor . * * @param in {@code char} array that is the source of characters. * @throws NumberFormatException if {@code in} is not a valid * representation of a {@code BigDecimal}. * @since 1.5 */ public BigDecimal(char[] in) { this(in, 0, in.length); } /** {@collect.stats} * Translates a character array representation of a * {@code BigDecimal} into a {@code BigDecimal}, accepting the * same sequence of characters as the {@link #BigDecimal(String)} * constructor and with rounding according to the context * settings. * * <p>Note that if the sequence of characters is already available * as a character array, using this constructor is faster than * converting the {@code char} array to string and using the * {@code BigDecimal(String)} constructor . * * @param in {@code char} array that is the source of characters. * @param mc the context to use. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @throws NumberFormatException if {@code in} is not a valid * representation of a {@code BigDecimal}. * @since 1.5 */ public BigDecimal(char[] in, MathContext mc) { this(in, 0, in.length, mc); } /** {@collect.stats} * Translates the string representation of a {@code BigDecimal} * into a {@code BigDecimal}. The string representation consists * of an optional sign, {@code '+'} (<tt> '&#92;u002B'</tt>) or * {@code '-'} (<tt>'&#92;u002D'</tt>), followed by a sequence of * zero or more decimal digits ("the integer"), optionally * followed by a fraction, optionally followed by an exponent. * * <p>The fraction consists of a decimal point followed by zero * or more decimal digits. The string must contain at least one * digit in either the integer or the fraction. The number formed * by the sign, the integer and the fraction is referred to as the * <i>significand</i>. * * <p>The exponent consists of the character {@code 'e'} * (<tt>'&#92;u0065'</tt>) or {@code 'E'} (<tt>'&#92;u0045'</tt>) * followed by one or more decimal digits. The value of the * exponent must lie between -{@link Integer#MAX_VALUE} ({@link * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive. * * <p>More formally, the strings this constructor accepts are * described by the following grammar: * <blockquote> * <dl> * <dt><i>BigDecimalString:</i> * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i> * <p> * <dt><i>Sign:</i> * <dd>{@code +} * <dd>{@code -} * <p> * <dt><i>Significand:</i> * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i> * <dd>{@code .} <i>FractionPart</i> * <dd><i>IntegerPart</i> * <p> * <dt><i>IntegerPart: * <dd>Digits</i> * <p> * <dt><i>FractionPart: * <dd>Digits</i> * <p> * <dt><i>Exponent: * <dd>ExponentIndicator SignedInteger</i> * <p> * <dt><i>ExponentIndicator:</i> * <dd>{@code e} * <dd>{@code E} * <p> * <dt><i>SignedInteger: * <dd>Sign<sub>opt</sub> Digits</i> * <p> * <dt><i>Digits: * <dd>Digit * <dd>Digits Digit</i> * <p> * <dt><i>Digit:</i> * <dd>any character for which {@link Character#isDigit} * returns {@code true}, including 0, 1, 2 ... * </dl> * </blockquote> * * <p>The scale of the returned {@code BigDecimal} will be the * number of digits in the fraction, or zero if the string * contains no decimal point, subject to adjustment for any * exponent; if the string contains an exponent, the exponent is * subtracted from the scale. The value of the resulting scale * must lie between {@code Integer.MIN_VALUE} and * {@code Integer.MAX_VALUE}, inclusive. * * <p>The character-to-digit mapping is provided by {@link * java.lang.Character#digit} set to convert to radix 10. The * String may not contain any extraneous characters (whitespace, * for example). * * <p><b>Examples:</b><br> * The value of the returned {@code BigDecimal} is equal to * <i>significand</i> &times; 10<sup>&nbsp;<i>exponent</i></sup>. * For each string on the left, the resulting representation * [{@code BigInteger}, {@code scale}] is shown on the right. * <pre> * "0" [0,0] * "0.00" [0,2] * "123" [123,0] * "-123" [-123,0] * "1.23E3" [123,-1] * "1.23E+3" [123,-1] * "12.3E+7" [123,-6] * "12.0" [120,1] * "12.3" [123,1] * "0.00123" [123,5] * "-1.23E-12" [-123,14] * "1234.5E-4" [12345,5] * "0E+7" [0,-7] * "-0" [0,0] * </pre> * * <p>Note: For values other than {@code float} and * {@code double} NaN and &plusmn;Infinity, this constructor is * compatible with the values returned by {@link Float#toString} * and {@link Double#toString}. This is generally the preferred * way to convert a {@code float} or {@code double} into a * BigDecimal, as it doesn't suffer from the unpredictability of * the {@link #BigDecimal(double)} constructor. * * @param val String representation of {@code BigDecimal}. * * @throws NumberFormatException if {@code val} is not a valid * representation of a {@code BigDecimal}. */ public BigDecimal(String val) { this(val.toCharArray(), 0, val.length()); } /** {@collect.stats} * Translates the string representation of a {@code BigDecimal} * into a {@code BigDecimal}, accepting the same strings as the * {@link #BigDecimal(String)} constructor, with rounding * according to the context settings. * * @param val string representation of a {@code BigDecimal}. * @param mc the context to use. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @throws NumberFormatException if {@code val} is not a valid * representation of a BigDecimal. * @since 1.5 */ public BigDecimal(String val, MathContext mc) { this(val.toCharArray(), 0, val.length()); if (mc.precision > 0) roundThis(mc); } /** {@collect.stats} * Translates a {@code double} into a {@code BigDecimal} which * is the exact decimal representation of the {@code double}'s * binary floating-point value. The scale of the returned * {@code BigDecimal} is the smallest value such that * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer. * <p> * <b>Notes:</b> * <ol> * <li> * The results of this constructor can be somewhat unpredictable. * One might assume that writing {@code new BigDecimal(0.1)} in * Java creates a {@code BigDecimal} which is exactly equal to * 0.1 (an unscaled value of 1, with a scale of 1), but it is * actually equal to * 0.1000000000000000055511151231257827021181583404541015625. * This is because 0.1 cannot be represented exactly as a * {@code double} (or, for that matter, as a binary fraction of * any finite length). Thus, the value that is being passed * <i>in</i> to the constructor is not exactly equal to 0.1, * appearances notwithstanding. * * <li> * The {@code String} constructor, on the other hand, is * perfectly predictable: writing {@code new BigDecimal("0.1")} * creates a {@code BigDecimal} which is <i>exactly</i> equal to * 0.1, as one would expect. Therefore, it is generally * recommended that the {@linkplain #BigDecimal(String) * <tt>String</tt> constructor} be used in preference to this one. * * <li> * When a {@code double} must be used as a source for a * {@code BigDecimal}, note that this constructor provides an * exact conversion; it does not give the same result as * converting the {@code double} to a {@code String} using the * {@link Double#toString(double)} method and then using the * {@link #BigDecimal(String)} constructor. To get that result, * use the {@code static} {@link #valueOf(double)} method. * </ol> * * @param val {@code double} value to be converted to * {@code BigDecimal}. * @throws NumberFormatException if {@code val} is infinite or NaN. */ public BigDecimal(double val) { if (Double.isInfinite(val) || Double.isNaN(val)) throw new NumberFormatException("Infinite or NaN"); // Translate the double into sign, exponent and significand, according // to the formulae in JLS, Section 20.10.22. long valBits = Double.doubleToLongBits(val); int sign = ((valBits >> 63)==0 ? 1 : -1); int exponent = (int) ((valBits >> 52) & 0x7ffL); long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1 : (valBits & ((1L<<52) - 1)) | (1L<<52)); exponent -= 1075; // At this point, val == sign * significand * 2**exponent. /* * Special case zero to supress nonterminating normalization * and bogus scale calculation. */ if (significand == 0) { intVal = BigInteger.ZERO; intCompact = 0; precision = 1; return; } // Normalize while((significand & 1) == 0) { // i.e., significand is even significand >>= 1; exponent++; } // Calculate intVal and scale long s = sign * significand; BigInteger b; if (exponent < 0) { b = BigInteger.valueOf(5).pow(-exponent).multiply(s); scale = -exponent; } else if (exponent > 0) { b = BigInteger.valueOf(2).pow(exponent).multiply(s); } else { b = BigInteger.valueOf(s); } intCompact = compactValFor(b); intVal = (intCompact != INFLATED) ? null : b; } /** {@collect.stats} * Translates a {@code double} into a {@code BigDecimal}, with * rounding according to the context settings. The scale of the * {@code BigDecimal} is the smallest value such that * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer. * * <p>The results of this constructor can be somewhat unpredictable * and its use is generally not recommended; see the notes under * the {@link #BigDecimal(double)} constructor. * * @param val {@code double} value to be converted to * {@code BigDecimal}. * @param mc the context to use. * @throws ArithmeticException if the result is inexact but the * RoundingMode is UNNECESSARY. * @throws NumberFormatException if {@code val} is infinite or NaN. * @since 1.5 */ public BigDecimal(double val, MathContext mc) { this(val); if (mc.precision > 0) roundThis(mc); } /** {@collect.stats} * Translates a {@code BigInteger} into a {@code BigDecimal}. * The scale of the {@code BigDecimal} is zero. * * @param val {@code BigInteger} value to be converted to * {@code BigDecimal}. */ public BigDecimal(BigInteger val) { intCompact = compactValFor(val); intVal = (intCompact != INFLATED) ? null : val; } /** {@collect.stats} * Translates a {@code BigInteger} into a {@code BigDecimal} * rounding according to the context settings. The scale of the * {@code BigDecimal} is zero. * * @param val {@code BigInteger} value to be converted to * {@code BigDecimal}. * @param mc the context to use. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @since 1.5 */ public BigDecimal(BigInteger val, MathContext mc) { this(val); if (mc.precision > 0) roundThis(mc); } /** {@collect.stats} * Translates a {@code BigInteger} unscaled value and an * {@code int} scale into a {@code BigDecimal}. The value of * the {@code BigDecimal} is * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>. * * @param unscaledVal unscaled value of the {@code BigDecimal}. * @param scale scale of the {@code BigDecimal}. */ public BigDecimal(BigInteger unscaledVal, int scale) { // Negative scales are now allowed this(unscaledVal); this.scale = scale; } /** {@collect.stats} * Translates a {@code BigInteger} unscaled value and an * {@code int} scale into a {@code BigDecimal}, with rounding * according to the context settings. The value of the * {@code BigDecimal} is <tt>(unscaledVal &times; * 10<sup>-scale</sup>)</tt>, rounded according to the * {@code precision} and rounding mode settings. * * @param unscaledVal unscaled value of the {@code BigDecimal}. * @param scale scale of the {@code BigDecimal}. * @param mc the context to use. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @since 1.5 */ public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) { this(unscaledVal); this.scale = scale; if (mc.precision > 0) roundThis(mc); } /** {@collect.stats} * Translates an {@code int} into a {@code BigDecimal}. The * scale of the {@code BigDecimal} is zero. * * @param val {@code int} value to be converted to * {@code BigDecimal}. * @since 1.5 */ public BigDecimal(int val) { intCompact = val; } /** {@collect.stats} * Translates an {@code int} into a {@code BigDecimal}, with * rounding according to the context settings. The scale of the * {@code BigDecimal}, before any rounding, is zero. * * @param val {@code int} value to be converted to {@code BigDecimal}. * @param mc the context to use. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @since 1.5 */ public BigDecimal(int val, MathContext mc) { intCompact = val; if (mc.precision > 0) roundThis(mc); } /** {@collect.stats} * Translates a {@code long} into a {@code BigDecimal}. The * scale of the {@code BigDecimal} is zero. * * @param val {@code long} value to be converted to {@code BigDecimal}. * @since 1.5 */ public BigDecimal(long val) { this.intCompact = val; this.intVal = (val == INFLATED) ? BigInteger.valueOf(val) : null; } /** {@collect.stats} * Translates a {@code long} into a {@code BigDecimal}, with * rounding according to the context settings. The scale of the * {@code BigDecimal}, before any rounding, is zero. * * @param val {@code long} value to be converted to {@code BigDecimal}. * @param mc the context to use. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @since 1.5 */ public BigDecimal(long val, MathContext mc) { this(val); if (mc.precision > 0) roundThis(mc); } // Static Factory Methods /** {@collect.stats} * Translates a {@code long} unscaled value and an * {@code int} scale into a {@code BigDecimal}. This * {@literal "static factory method"} is provided in preference to * a ({@code long}, {@code int}) constructor because it * allows for reuse of frequently used {@code BigDecimal} values.. * * @param unscaledVal unscaled value of the {@code BigDecimal}. * @param scale scale of the {@code BigDecimal}. * @return a {@code BigDecimal} whose value is * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>. */ public static BigDecimal valueOf(long unscaledVal, int scale) { if (scale == 0) return valueOf(unscaledVal); else if (unscaledVal == 0) { if (scale > 0 && scale < ZERO_SCALED_BY.length) return ZERO_SCALED_BY[scale]; else return new BigDecimal(BigInteger.ZERO, 0, scale, 1); } return new BigDecimal(unscaledVal == INFLATED ? BigInteger.valueOf(unscaledVal) : null, unscaledVal, scale, 0); } /** {@collect.stats} * Translates a {@code long} value into a {@code BigDecimal} * with a scale of zero. This {@literal "static factory method"} * is provided in preference to a ({@code long}) constructor * because it allows for reuse of frequently used * {@code BigDecimal} values. * * @param val value of the {@code BigDecimal}. * @return a {@code BigDecimal} whose value is {@code val}. */ public static BigDecimal valueOf(long val) { if (val >= 0 && val < zeroThroughTen.length) return zeroThroughTen[(int)val]; else if (val != INFLATED) return new BigDecimal(null, val, 0, 0); return new BigDecimal(BigInteger.valueOf(val), val, 0, 0); } /** {@collect.stats} * Translates a {@code double} into a {@code BigDecimal}, using * the {@code double}'s canonical string representation provided * by the {@link Double#toString(double)} method. * * <p><b>Note:</b> This is generally the preferred way to convert * a {@code double} (or {@code float}) into a * {@code BigDecimal}, as the value returned is equal to that * resulting from constructing a {@code BigDecimal} from the * result of using {@link Double#toString(double)}. * * @param val {@code double} to convert to a {@code BigDecimal}. * @return a {@code BigDecimal} whose value is equal to or approximately * equal to the value of {@code val}. * @throws NumberFormatException if {@code val} is infinite or NaN. * @since 1.5 */ public static BigDecimal valueOf(double val) { // Reminder: a zero double returns '0.0', so we cannot fastpath // to use the constant ZERO. This might be important enough to // justify a factory approach, a cache, or a few private // constants, later. return new BigDecimal(Double.toString(val)); } // Arithmetic Operations /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this + * augend)}, and whose scale is {@code max(this.scale(), * augend.scale())}. * * @param augend value to be added to this {@code BigDecimal}. * @return {@code this + augend} */ public BigDecimal add(BigDecimal augend) { long xs = this.intCompact; long ys = augend.intCompact; BigInteger fst = (xs != INFLATED) ? null : this.intVal; BigInteger snd = (ys != INFLATED) ? null : augend.intVal; int rscale = this.scale; long sdiff = (long)rscale - augend.scale; if (sdiff != 0) { if (sdiff < 0) { int raise = checkScale(-sdiff); rscale = augend.scale; if (xs == INFLATED || (xs = longMultiplyPowerTen(xs, raise)) == INFLATED) fst = bigMultiplyPowerTen(raise); } else { int raise = augend.checkScale(sdiff); if (ys == INFLATED || (ys = longMultiplyPowerTen(ys, raise)) == INFLATED) snd = augend.bigMultiplyPowerTen(raise); } } if (xs != INFLATED && ys != INFLATED) { long sum = xs + ys; // See "Hacker's Delight" section 2-12 for explanation of // the overflow test. if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) // not overflowed return BigDecimal.valueOf(sum, rscale); } if (fst == null) fst = BigInteger.valueOf(xs); if (snd == null) snd = BigInteger.valueOf(ys); BigInteger sum = fst.add(snd); return (fst.signum == snd.signum) ? new BigDecimal(sum, INFLATED, rscale, 0) : new BigDecimal(sum, rscale); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this + augend)}, * with rounding according to the context settings. * * If either number is zero and the precision setting is nonzero then * the other number, rounded if necessary, is used as the result. * * @param augend value to be added to this {@code BigDecimal}. * @param mc the context to use. * @return {@code this + augend}, rounded as necessary. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @since 1.5 */ public BigDecimal add(BigDecimal augend, MathContext mc) { if (mc.precision == 0) return add(augend); BigDecimal lhs = this; // Could optimize if values are compact this.inflate(); augend.inflate(); // If either number is zero then the other number, rounded and // scaled if necessary, is used as the result. { boolean lhsIsZero = lhs.signum() == 0; boolean augendIsZero = augend.signum() == 0; if (lhsIsZero || augendIsZero) { int preferredScale = Math.max(lhs.scale(), augend.scale()); BigDecimal result; // Could use a factory for zero instead of a new object if (lhsIsZero && augendIsZero) return new BigDecimal(BigInteger.ZERO, 0, preferredScale, 0); result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc); if (result.scale() == preferredScale) return result; else if (result.scale() > preferredScale) { BigDecimal scaledResult = new BigDecimal(result.intVal, result.intCompact, result.scale, 0); scaledResult.stripZerosToMatchScale(preferredScale); return scaledResult; } else { // result.scale < preferredScale int precisionDiff = mc.precision - result.precision(); int scaleDiff = preferredScale - result.scale(); if (precisionDiff >= scaleDiff) return result.setScale(preferredScale); // can achieve target scale else return result.setScale(result.scale() + precisionDiff); } } } long padding = (long)lhs.scale - augend.scale; if (padding != 0) { // scales differ; alignment needed BigDecimal arg[] = preAlign(lhs, augend, padding, mc); matchScale(arg); lhs = arg[0]; augend = arg[1]; } BigDecimal d = new BigDecimal(lhs.inflate().add(augend.inflate()), lhs.scale); return doRound(d, mc); } /** {@collect.stats} * Returns an array of length two, the sum of whose entries is * equal to the rounded sum of the {@code BigDecimal} arguments. * * <p>If the digit positions of the arguments have a sufficient * gap between them, the value smaller in magnitude can be * condensed into a {@literal "sticky bit"} and the end result will * round the same way <em>if</em> the precision of the final * result does not include the high order digit of the small * magnitude operand. * * <p>Note that while strictly speaking this is an optimization, * it makes a much wider range of additions practical. * * <p>This corresponds to a pre-shift operation in a fixed * precision floating-point adder; this method is complicated by * variable precision of the result as determined by the * MathContext. A more nuanced operation could implement a * {@literal "right shift"} on the smaller magnitude operand so * that the number of digits of the smaller operand could be * reduced even though the significands partially overlapped. */ private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend, long padding, MathContext mc) { assert padding != 0; BigDecimal big; BigDecimal small; if (padding < 0) { // lhs is big; augend is small big = lhs; small = augend; } else { // lhs is small; augend is big big = augend; small = lhs; } /* * This is the estimated scale of an ulp of the result; it * assumes that the result doesn't have a carry-out on a true * add (e.g. 999 + 1 => 1000) or any subtractive cancellation * on borrowing (e.g. 100 - 1.2 => 98.8) */ long estResultUlpScale = (long)big.scale - big.precision() + mc.precision; /* * The low-order digit position of big is big.scale(). This * is true regardless of whether big has a positive or * negative scale. The high-order digit position of small is * small.scale - (small.precision() - 1). To do the full * condensation, the digit positions of big and small must be * disjoint *and* the digit positions of small should not be * directly visible in the result. */ long smallHighDigitPos = (long)small.scale - small.precision() + 1; if (smallHighDigitPos > big.scale + 2 && // big and small disjoint smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible small = BigDecimal.valueOf(small.signum(), this.checkScale(Math.max(big.scale, estResultUlpScale) + 3)); } // Since addition is symmetric, preserving input order in // returned operands doesn't matter BigDecimal[] result = {big, small}; return result; } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this - * subtrahend)}, and whose scale is {@code max(this.scale(), * subtrahend.scale())}. * * @param subtrahend value to be subtracted from this {@code BigDecimal}. * @return {@code this - subtrahend} */ public BigDecimal subtract(BigDecimal subtrahend) { return add(subtrahend.negate()); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)}, * with rounding according to the context settings. * * If {@code subtrahend} is zero then this, rounded if necessary, is used as the * result. If this is zero then the result is {@code subtrahend.negate(mc)}. * * @param subtrahend value to be subtracted from this {@code BigDecimal}. * @param mc the context to use. * @return {@code this - subtrahend}, rounded as necessary. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @since 1.5 */ public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) { BigDecimal nsubtrahend = subtrahend.negate(); if (mc.precision == 0) return add(nsubtrahend); // share the special rounding code in add() return add(nsubtrahend, mc); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is <tt>(this &times; * multiplicand)</tt>, and whose scale is {@code (this.scale() + * multiplicand.scale())}. * * @param multiplicand value to be multiplied by this {@code BigDecimal}. * @return {@code this * multiplicand} */ public BigDecimal multiply(BigDecimal multiplicand) { long x = this.intCompact; long y = multiplicand.intCompact; int productScale = checkScale((long)scale + multiplicand.scale); // Might be able to do a more clever check incorporating the // inflated check into the overflow computation. if (x != INFLATED && y != INFLATED) { /* * If the product is not an overflowed value, continue * to use the compact representation. if either of x or y * is INFLATED, the product should also be regarded as * an overflow. Before using the overflow test suggested in * "Hacker's Delight" section 2-12, we perform quick checks * using the precision information to see whether the overflow * would occur since division is expensive on most CPUs. */ long product = x * y; long prec = this.precision() + multiplicand.precision(); if (prec < 19 || (prec < 21 && (y == 0 || product / y == x))) return BigDecimal.valueOf(product, productScale); return new BigDecimal(BigInteger.valueOf(x).multiply(y), INFLATED, productScale, 0); } BigInteger rb; if (x == INFLATED && y == INFLATED) rb = this.intVal.multiply(multiplicand.intVal); else if (x != INFLATED) rb = multiplicand.intVal.multiply(x); else rb = this.intVal.multiply(y); return new BigDecimal(rb, INFLATED, productScale, 0); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is <tt>(this &times; * multiplicand)</tt>, with rounding according to the context settings. * * @param multiplicand value to be multiplied by this {@code BigDecimal}. * @param mc the context to use. * @return {@code this * multiplicand}, rounded as necessary. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @since 1.5 */ public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) { if (mc.precision == 0) return multiply(multiplicand); return doRound(this.multiply(multiplicand), mc); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this / * divisor)}, and whose scale is as specified. If rounding must * be performed to generate a result with the specified scale, the * specified rounding mode is applied. * * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method * should be used in preference to this legacy method. * * @param divisor value by which this {@code BigDecimal} is to be divided. * @param scale scale of the {@code BigDecimal} quotient to be returned. * @param roundingMode rounding mode to apply. * @return {@code this / divisor} * @throws ArithmeticException if {@code divisor} is zero, * {@code roundingMode==ROUND_UNNECESSARY} and * the specified scale is insufficient to represent the result * of the division exactly. * @throws IllegalArgumentException if {@code roundingMode} does not * represent a valid rounding mode. * @see #ROUND_UP * @see #ROUND_DOWN * @see #ROUND_CEILING * @see #ROUND_FLOOR * @see #ROUND_HALF_UP * @see #ROUND_HALF_DOWN * @see #ROUND_HALF_EVEN * @see #ROUND_UNNECESSARY */ public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) { /* * IMPLEMENTATION NOTE: This method *must* return a new object * since divideAndRound uses divide to generate a value whose * scale is then modified. */ if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY) throw new IllegalArgumentException("Invalid rounding mode"); /* * Rescale dividend or divisor (whichever can be "upscaled" to * produce correctly scaled quotient). * Take care to detect out-of-range scales */ BigDecimal dividend = this; if (checkScale((long)scale + divisor.scale) > this.scale) dividend = this.setScale(scale + divisor.scale, ROUND_UNNECESSARY); else divisor = divisor.setScale(checkScale((long)this.scale - scale), ROUND_UNNECESSARY); return divideAndRound(dividend.intCompact, dividend.intVal, divisor.intCompact, divisor.intVal, scale, roundingMode, scale); } /** {@collect.stats} * Internally used for division operation. The dividend and divisor are * passed both in {@code long} format and {@code BigInteger} format. The * returned {@code BigDecimal} object is the quotient whose scale is set to * the passed in scale. If the remainder is not zero, it will be rounded * based on the passed in roundingMode. Also, if the remainder is zero and * the last parameter, i.e. preferredScale is NOT equal to scale, the * trailing zeros of the result is stripped to match the preferredScale. */ private static BigDecimal divideAndRound(long ldividend, BigInteger bdividend, long ldivisor, BigInteger bdivisor, int scale, int roundingMode, int preferredScale) { boolean isRemainderZero; // record remainder is zero or not int qsign; // quotient sign long q = 0, r = 0; // store quotient & remainder in long MutableBigInteger mq = null; // store quotient MutableBigInteger mr = null; // store remainder MutableBigInteger mdivisor = null; boolean isLongDivision = (ldividend != INFLATED && ldivisor != INFLATED); if (isLongDivision) { q = ldividend / ldivisor; if (roundingMode == ROUND_DOWN && scale == preferredScale) return new BigDecimal(null, q, scale, 0); r = ldividend % ldivisor; isRemainderZero = (r == 0); qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1; } else { if (bdividend == null) bdividend = BigInteger.valueOf(ldividend); // Descend into mutables for faster remainder checks MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); mq = new MutableBigInteger(); if (ldivisor != INFLATED) { r = mdividend.divide(ldivisor, mq); isRemainderZero = (r == 0); qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum; } else { mdivisor = new MutableBigInteger(bdivisor.mag); mr = mdividend.divide(mdivisor, mq); isRemainderZero = mr.isZero(); qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1; } } boolean increment = false; if (!isRemainderZero) { int cmpFracHalf; /* Round as appropriate */ if (roundingMode == ROUND_UNNECESSARY) { // Rounding prohibited throw new ArithmeticException("Rounding necessary"); } else if (roundingMode == ROUND_UP) { // Away from zero increment = true; } else if (roundingMode == ROUND_DOWN) { // Towards zero increment = false; } else if (roundingMode == ROUND_CEILING) { // Towards +infinity increment = (qsign > 0); } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity increment = (qsign < 0); } else { if (isLongDivision || ldivisor != INFLATED) { if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) { cmpFracHalf = 1; // 2 * r can't fit into long } else { cmpFracHalf = longCompareMagnitude(2 * r, ldivisor); } } else { cmpFracHalf = mr.compareHalf(mdivisor); } if (cmpFracHalf < 0) increment = false; // We're closer to higher digit else if (cmpFracHalf > 0) // We're closer to lower digit increment = true; else if (roundingMode == ROUND_HALF_UP) increment = true; else if (roundingMode == ROUND_HALF_DOWN) increment = false; else // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd increment = isLongDivision ? (q & 1L) != 0L : mq.isOdd(); } } BigDecimal res; if (isLongDivision) res = new BigDecimal(null, (increment ? q + qsign : q), scale, 0); else { if (increment) mq.add(MutableBigInteger.ONE); res = mq.toBigDecimal(qsign, scale); } if (isRemainderZero && preferredScale != scale) res.stripZerosToMatchScale(preferredScale); return res; } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this / * divisor)}, and whose scale is as specified. If rounding must * be performed to generate a result with the specified scale, the * specified rounding mode is applied. * * @param divisor value by which this {@code BigDecimal} is to be divided. * @param scale scale of the {@code BigDecimal} quotient to be returned. * @param roundingMode rounding mode to apply. * @return {@code this / divisor} * @throws ArithmeticException if {@code divisor} is zero, * {@code roundingMode==RoundingMode.UNNECESSARY} and * the specified scale is insufficient to represent the result * of the division exactly. * @since 1.5 */ public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) { return divide(divisor, scale, roundingMode.oldMode); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this / * divisor)}, and whose scale is {@code this.scale()}. If * rounding must be performed to generate a result with the given * scale, the specified rounding mode is applied. * * <p>The new {@link #divide(BigDecimal, RoundingMode)} method * should be used in preference to this legacy method. * * @param divisor value by which this {@code BigDecimal} is to be divided. * @param roundingMode rounding mode to apply. * @return {@code this / divisor} * @throws ArithmeticException if {@code divisor==0}, or * {@code roundingMode==ROUND_UNNECESSARY} and * {@code this.scale()} is insufficient to represent the result * of the division exactly. * @throws IllegalArgumentException if {@code roundingMode} does not * represent a valid rounding mode. * @see #ROUND_UP * @see #ROUND_DOWN * @see #ROUND_CEILING * @see #ROUND_FLOOR * @see #ROUND_HALF_UP * @see #ROUND_HALF_DOWN * @see #ROUND_HALF_EVEN * @see #ROUND_UNNECESSARY */ public BigDecimal divide(BigDecimal divisor, int roundingMode) { return this.divide(divisor, scale, roundingMode); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this / * divisor)}, and whose scale is {@code this.scale()}. If * rounding must be performed to generate a result with the given * scale, the specified rounding mode is applied. * * @param divisor value by which this {@code BigDecimal} is to be divided. * @param roundingMode rounding mode to apply. * @return {@code this / divisor} * @throws ArithmeticException if {@code divisor==0}, or * {@code roundingMode==RoundingMode.UNNECESSARY} and * {@code this.scale()} is insufficient to represent the result * of the division exactly. * @since 1.5 */ public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) { return this.divide(divisor, scale, roundingMode.oldMode); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this / * divisor)}, and whose preferred scale is {@code (this.scale() - * divisor.scale())}; if the exact quotient cannot be * represented (because it has a non-terminating decimal * expansion) an {@code ArithmeticException} is thrown. * * @param divisor value by which this {@code BigDecimal} is to be divided. * @throws ArithmeticException if the exact quotient does not have a * terminating decimal expansion * @return {@code this / divisor} * @since 1.5 * @author Joseph D. Darcy */ public BigDecimal divide(BigDecimal divisor) { /* * Handle zero cases first. */ if (divisor.signum() == 0) { // x/0 if (this.signum() == 0) // 0/0 throw new ArithmeticException("Division undefined"); // NaN throw new ArithmeticException("Division by zero"); } // Calculate preferred scale int preferredScale = saturateLong((long)this.scale - divisor.scale); if (this.signum() == 0) // 0/y return (preferredScale >= 0 && preferredScale < ZERO_SCALED_BY.length) ? ZERO_SCALED_BY[preferredScale] : BigDecimal.valueOf(0, preferredScale); else { this.inflate(); divisor.inflate(); /* * If the quotient this/divisor has a terminating decimal * expansion, the expansion can have no more than * (a.precision() + ceil(10*b.precision)/3) digits. * Therefore, create a MathContext object with this * precision and do a divide with the UNNECESSARY rounding * mode. */ MathContext mc = new MathContext( (int)Math.min(this.precision() + (long)Math.ceil(10.0*divisor.precision()/3.0), Integer.MAX_VALUE), RoundingMode.UNNECESSARY); BigDecimal quotient; try { quotient = this.divide(divisor, mc); } catch (ArithmeticException e) { throw new ArithmeticException("Non-terminating decimal expansion; " + "no exact representable decimal result."); } int quotientScale = quotient.scale(); // divide(BigDecimal, mc) tries to adjust the quotient to // the desired one by removing trailing zeros; since the // exact divide method does not have an explicit digit // limit, we can add zeros too. if (preferredScale > quotientScale) return quotient.setScale(preferredScale, ROUND_UNNECESSARY); return quotient; } } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this / * divisor)}, with rounding according to the context settings. * * @param divisor value by which this {@code BigDecimal} is to be divided. * @param mc the context to use. * @return {@code this / divisor}, rounded as necessary. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY} or * {@code mc.precision == 0} and the quotient has a * non-terminating decimal expansion. * @since 1.5 */ public BigDecimal divide(BigDecimal divisor, MathContext mc) { int mcp = mc.precision; if (mcp == 0) return divide(divisor); BigDecimal dividend = this; long preferredScale = (long)dividend.scale - divisor.scale; // Now calculate the answer. We use the existing // divide-and-round method, but as this rounds to scale we have // to normalize the values here to achieve the desired result. // For x/y we first handle y=0 and x=0, and then normalize x and // y to give x' and y' with the following constraints: // (a) 0.1 <= x' < 1 // (b) x' <= y' < 10*x' // Dividing x'/y' with the required scale set to mc.precision then // will give a result in the range 0.1 to 1 rounded to exactly // the right number of digits (except in the case of a result of // 1.000... which can arise when x=y, or when rounding overflows // The 1.000... case will reduce properly to 1. if (divisor.signum() == 0) { // x/0 if (dividend.signum() == 0) // 0/0 throw new ArithmeticException("Division undefined"); // NaN throw new ArithmeticException("Division by zero"); } if (dividend.signum() == 0) // 0/y return new BigDecimal(BigInteger.ZERO, 0, saturateLong(preferredScale), 1); // Normalize dividend & divisor so that both fall into [0.1, 0.999...] int xscale = dividend.precision(); int yscale = divisor.precision(); dividend = new BigDecimal(dividend.intVal, dividend.intCompact, xscale, xscale); divisor = new BigDecimal(divisor.intVal, divisor.intCompact, yscale, yscale); if (dividend.compareMagnitude(divisor) > 0) // satisfy constraint (b) yscale = divisor.scale -= 1; // [that is, divisor *= 10] // In order to find out whether the divide generates the exact result, // we avoid calling the above divide method. 'quotient' holds the // return BigDecimal object whose scale will be set to 'scl'. BigDecimal quotient; int scl = checkScale(preferredScale + yscale - xscale + mcp); if (checkScale((long)mcp + yscale) > xscale) dividend = dividend.setScale(mcp + yscale, ROUND_UNNECESSARY); else divisor = divisor.setScale(checkScale((long)xscale - mcp), ROUND_UNNECESSARY); quotient = divideAndRound(dividend.intCompact, dividend.intVal, divisor.intCompact, divisor.intVal, scl, mc.roundingMode.oldMode, checkScale(preferredScale)); // doRound, here, only affects 1000000000 case. quotient = doRound(quotient, mc); return quotient; } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is the integer part * of the quotient {@code (this / divisor)} rounded down. The * preferred scale of the result is {@code (this.scale() - * divisor.scale())}. * * @param divisor value by which this {@code BigDecimal} is to be divided. * @return The integer part of {@code this / divisor}. * @throws ArithmeticException if {@code divisor==0} * @since 1.5 */ public BigDecimal divideToIntegralValue(BigDecimal divisor) { // Calculate preferred scale int preferredScale = saturateLong((long)this.scale - divisor.scale); if (this.compareMagnitude(divisor) < 0) { // much faster when this << divisor return BigDecimal.valueOf(0, preferredScale); } if(this.signum() == 0 && divisor.signum() != 0) return this.setScale(preferredScale, ROUND_UNNECESSARY); // Perform a divide with enough digits to round to a correct // integer value; then remove any fractional digits int maxDigits = (int)Math.min(this.precision() + (long)Math.ceil(10.0*divisor.precision()/3.0) + Math.abs((long)this.scale() - divisor.scale()) + 2, Integer.MAX_VALUE); BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits, RoundingMode.DOWN)); if (quotient.scale > 0) { quotient = quotient.setScale(0, RoundingMode.DOWN); quotient.stripZerosToMatchScale(preferredScale); } if (quotient.scale < preferredScale) { // pad with zeros if necessary quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY); } return quotient; } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is the integer part * of {@code (this / divisor)}. Since the integer part of the * exact quotient does not depend on the rounding mode, the * rounding mode does not affect the values returned by this * method. The preferred scale of the result is * {@code (this.scale() - divisor.scale())}. An * {@code ArithmeticException} is thrown if the integer part of * the exact quotient needs more than {@code mc.precision} * digits. * * @param divisor value by which this {@code BigDecimal} is to be divided. * @param mc the context to use. * @return The integer part of {@code this / divisor}. * @throws ArithmeticException if {@code divisor==0} * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result * requires a precision of more than {@code mc.precision} digits. * @since 1.5 * @author Joseph D. Darcy */ public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) { if (mc.precision == 0 || // exact result (this.compareMagnitude(divisor) < 0) ) // zero result return divideToIntegralValue(divisor); // Calculate preferred scale int preferredScale = saturateLong((long)this.scale - divisor.scale); /* * Perform a normal divide to mc.precision digits. If the * remainder has absolute value less than the divisor, the * integer portion of the quotient fits into mc.precision * digits. Next, remove any fractional digits from the * quotient and adjust the scale to the preferred value. */ BigDecimal result = this. divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN)); if (result.scale() < 0) { /* * Result is an integer. See if quotient represents the * full integer portion of the exact quotient; if it does, * the computed remainder will be less than the divisor. */ BigDecimal product = result.multiply(divisor); // If the quotient is the full integer value, // |dividend-product| < |divisor|. if (this.subtract(product).compareMagnitude(divisor) >= 0) { throw new ArithmeticException("Division impossible"); } } else if (result.scale() > 0) { /* * Integer portion of quotient will fit into precision * digits; recompute quotient to scale 0 to avoid double * rounding and then try to adjust, if necessary. */ result = result.setScale(0, RoundingMode.DOWN); } // else result.scale() == 0; int precisionDiff; if ((preferredScale > result.scale()) && (precisionDiff = mc.precision - result.precision()) > 0) { return result.setScale(result.scale() + Math.min(precisionDiff, preferredScale - result.scale) ); } else { result.stripZerosToMatchScale(preferredScale); return result; } } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}. * * <p>The remainder is given by * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}. * Note that this is not the modulo operation (the result can be * negative). * * @param divisor value by which this {@code BigDecimal} is to be divided. * @return {@code this % divisor}. * @throws ArithmeticException if {@code divisor==0} * @since 1.5 */ public BigDecimal remainder(BigDecimal divisor) { BigDecimal divrem[] = this.divideAndRemainder(divisor); return divrem[1]; } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (this % * divisor)}, with rounding according to the context settings. * The {@code MathContext} settings affect the implicit divide * used to compute the remainder. The remainder computation * itself is by definition exact. Therefore, the remainder may * contain more than {@code mc.getPrecision()} digits. * * <p>The remainder is given by * {@code this.subtract(this.divideToIntegralValue(divisor, * mc).multiply(divisor))}. Note that this is not the modulo * operation (the result can be negative). * * @param divisor value by which this {@code BigDecimal} is to be divided. * @param mc the context to use. * @return {@code this % divisor}, rounded as necessary. * @throws ArithmeticException if {@code divisor==0} * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}, or {@code mc.precision} * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would * require a precision of more than {@code mc.precision} digits. * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) * @since 1.5 */ public BigDecimal remainder(BigDecimal divisor, MathContext mc) { BigDecimal divrem[] = this.divideAndRemainder(divisor, mc); return divrem[1]; } /** {@collect.stats} * Returns a two-element {@code BigDecimal} array containing the * result of {@code divideToIntegralValue} followed by the result of * {@code remainder} on the two operands. * * <p>Note that if both the integer quotient and remainder are * needed, this method is faster than using the * {@code divideToIntegralValue} and {@code remainder} methods * separately because the division need only be carried out once. * * @param divisor value by which this {@code BigDecimal} is to be divided, * and the remainder computed. * @return a two element {@code BigDecimal} array: the quotient * (the result of {@code divideToIntegralValue}) is the initial element * and the remainder is the final element. * @throws ArithmeticException if {@code divisor==0} * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) * @see #remainder(java.math.BigDecimal, java.math.MathContext) * @since 1.5 */ public BigDecimal[] divideAndRemainder(BigDecimal divisor) { // we use the identity x = i * y + r to determine r BigDecimal[] result = new BigDecimal[2]; result[0] = this.divideToIntegralValue(divisor); result[1] = this.subtract(result[0].multiply(divisor)); return result; } /** {@collect.stats} * Returns a two-element {@code BigDecimal} array containing the * result of {@code divideToIntegralValue} followed by the result of * {@code remainder} on the two operands calculated with rounding * according to the context settings. * * <p>Note that if both the integer quotient and remainder are * needed, this method is faster than using the * {@code divideToIntegralValue} and {@code remainder} methods * separately because the division need only be carried out once. * * @param divisor value by which this {@code BigDecimal} is to be divided, * and the remainder computed. * @param mc the context to use. * @return a two element {@code BigDecimal} array: the quotient * (the result of {@code divideToIntegralValue}) is the * initial element and the remainder is the final element. * @throws ArithmeticException if {@code divisor==0} * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}, or {@code mc.precision} * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would * require a precision of more than {@code mc.precision} digits. * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) * @see #remainder(java.math.BigDecimal, java.math.MathContext) * @since 1.5 */ public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) { if (mc.precision == 0) return divideAndRemainder(divisor); BigDecimal[] result = new BigDecimal[2]; BigDecimal lhs = this; result[0] = lhs.divideToIntegralValue(divisor, mc); result[1] = lhs.subtract(result[0].multiply(divisor)); return result; } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to * unlimited precision. * * <p>The parameter {@code n} must be in the range 0 through * 999999999, inclusive. {@code ZERO.pow(0)} returns {@link * #ONE}. * * Note that future releases may expand the allowable exponent * range of this method. * * @param n power to raise this {@code BigDecimal} to. * @return <tt>this<sup>n</sup></tt> * @throws ArithmeticException if {@code n} is out of range. * @since 1.5 */ public BigDecimal pow(int n) { if (n < 0 || n > 999999999) throw new ArithmeticException("Invalid operation"); // No need to calculate pow(n) if result will over/underflow. // Don't attempt to support "supernormal" numbers. int newScale = checkScale((long)scale * n); this.inflate(); return new BigDecimal(intVal.pow(n), newScale); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is * <tt>(this<sup>n</sup>)</tt>. The current implementation uses * the core algorithm defined in ANSI standard X3.274-1996 with * rounding according to the context settings. In general, the * returned numerical value is within two ulps of the exact * numerical value for the chosen precision. Note that future * releases may use a different algorithm with a decreased * allowable error bound and increased allowable exponent range. * * <p>The X3.274-1996 algorithm is: * * <ul> * <li> An {@code ArithmeticException} exception is thrown if * <ul> * <li>{@code abs(n) > 999999999} * <li>{@code mc.precision == 0} and {@code n < 0} * <li>{@code mc.precision > 0} and {@code n} has more than * {@code mc.precision} decimal digits * </ul> * * <li> if {@code n} is zero, {@link #ONE} is returned even if * {@code this} is zero, otherwise * <ul> * <li> if {@code n} is positive, the result is calculated via * the repeated squaring technique into a single accumulator. * The individual multiplications with the accumulator use the * same math context settings as in {@code mc} except for a * precision increased to {@code mc.precision + elength + 1} * where {@code elength} is the number of decimal digits in * {@code n}. * * <li> if {@code n} is negative, the result is calculated as if * {@code n} were positive; this value is then divided into one * using the working precision specified above. * * <li> The final value from either the positive or negative case * is then rounded to the destination precision. * </ul> * </ul> * * @param n power to raise this {@code BigDecimal} to. * @param mc the context to use. * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996 * algorithm * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}, or {@code n} is out * of range. * @since 1.5 */ public BigDecimal pow(int n, MathContext mc) { if (mc.precision == 0) return pow(n); if (n < -999999999 || n > 999999999) throw new ArithmeticException("Invalid operation"); if (n == 0) return ONE; // x**0 == 1 in X3.274 this.inflate(); BigDecimal lhs = this; MathContext workmc = mc; // working settings int mag = Math.abs(n); // magnitude of n if (mc.precision > 0) { int elength = longDigitLength(mag); // length of n in digits if (elength > mc.precision) // X3.274 rule throw new ArithmeticException("Invalid operation"); workmc = new MathContext(mc.precision + elength + 1, mc.roundingMode); } // ready to carry out power calculation... BigDecimal acc = ONE; // accumulator boolean seenbit = false; // set once we've seen a 1-bit for (int i=1;;i++) { // for each bit [top bit ignored] mag += mag; // shift left 1 bit if (mag < 0) { // top bit is set seenbit = true; // OK, we're off acc = acc.multiply(lhs, workmc); // acc=acc*x } if (i == 31) break; // that was the last bit if (seenbit) acc=acc.multiply(acc, workmc); // acc=acc*acc [square] // else (!seenbit) no point in squaring ONE } // if negative n, calculate the reciprocal using working precision if (n<0) // [hence mc.precision>0] acc=ONE.divide(acc, workmc); // round to final precision and strip zeros return doRound(acc, mc); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is the absolute value * of this {@code BigDecimal}, and whose scale is * {@code this.scale()}. * * @return {@code abs(this)} */ public BigDecimal abs() { return (signum() < 0 ? negate() : this); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is the absolute value * of this {@code BigDecimal}, with rounding according to the * context settings. * * @param mc the context to use. * @return {@code abs(this)}, rounded as necessary. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @since 1.5 */ public BigDecimal abs(MathContext mc) { return (signum() < 0 ? negate(mc) : plus(mc)); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (-this)}, * and whose scale is {@code this.scale()}. * * @return {@code -this}. */ public BigDecimal negate() { BigDecimal result; if (intCompact != INFLATED) result = BigDecimal.valueOf(-intCompact, scale); else { result = new BigDecimal(intVal.negate(), scale); result.precision = precision; } return result; } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (-this)}, * with rounding according to the context settings. * * @param mc the context to use. * @return {@code -this}, rounded as necessary. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @since 1.5 */ public BigDecimal negate(MathContext mc) { return negate().plus(mc); } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose * scale is {@code this.scale()}. * * <p>This method, which simply returns this {@code BigDecimal} * is included for symmetry with the unary minus method {@link * #negate()}. * * @return {@code this}. * @see #negate() * @since 1.5 */ public BigDecimal plus() { return this; } /** {@collect.stats} * Returns a {@code BigDecimal} whose value is {@code (+this)}, * with rounding according to the context settings. * * <p>The effect of this method is identical to that of the {@link * #round(MathContext)} method. * * @param mc the context to use. * @return {@code this}, rounded as necessary. A zero result will * have a scale of 0. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. * @see #round(MathContext) * @since 1.5 */ public BigDecimal plus(MathContext mc) { if (mc.precision == 0) // no rounding please return this; return doRound(this, mc); } /** {@collect.stats} * Returns the signum function of this {@code BigDecimal}. * * @return -1, 0, or 1 as the value of this {@code BigDecimal} * is negative, zero, or positive. */ public int signum() { return (intCompact != INFLATED)? Long.signum(intCompact): intVal.signum(); } /** {@collect.stats} * Returns the <i>scale</i> of this {@code BigDecimal}. If zero * or positive, the scale is the number of digits to the right of * the decimal point. If negative, the unscaled value of the * number is multiplied by ten to the power of the negation of the * scale. For example, a scale of {@code -3} means the unscaled * value is multiplied by 1000. * * @return the scale of this {@code BigDecimal}. */ public int scale() { return scale; } /** {@collect.stats} * Returns the <i>precision</i> of this {@code BigDecimal}. (The * precision is the number of digits in the unscaled value.) * * <p>The precision of a zero value is 1. * * @return the precision of this {@code BigDecimal}. * @since 1.5 */ public int precision() { int result = precision; if (result == 0) { long s = intCompact; if (s != INFLATED) result = longDigitLength(s); else result = bigDigitLength(inflate()); precision = result; } return result; } /** {@collect.stats} * Returns a {@code BigInteger} whose value is the <i>unscaled * value</i> of this {@code BigDecimal}. (Computes <tt>(this * * 10<sup>this.scale()</sup>)</tt>.) * * @return the unscaled value of this {@code BigDecimal}. * @since 1.2 */ public BigInteger unscaledValue() { return this.inflate(); } // Rounding Modes /** {@collect.stats} * Rounding mode to round away from zero. Always increments the * digit prior to a nonzero discarded fraction. Note that this rounding * mode never decreases the magnitude of the calculated value. */ public final static int ROUND_UP = 0; /** {@collect.stats} * Rounding mode to round towards zero. Never increments the digit * prior to a discarded fraction (i.e., truncates). Note that this * rounding mode never increases the magnitude of the calculated value. */ public final static int ROUND_DOWN = 1; /** {@collect.stats} * Rounding mode to round towards positive infinity. If the * {@code BigDecimal} is positive, behaves as for * {@code ROUND_UP}; if negative, behaves as for * {@code ROUND_DOWN}. Note that this rounding mode never * decreases the calculated value. */ public final static int ROUND_CEILING = 2; /** {@collect.stats} * Rounding mode to round towards negative infinity. If the * {@code BigDecimal} is positive, behave as for * {@code ROUND_DOWN}; if negative, behave as for * {@code ROUND_UP}. Note that this rounding mode never * increases the calculated value. */ public final static int ROUND_FLOOR = 3; /** {@collect.stats} * Rounding mode to round towards {@literal "nearest neighbor"} * unless both neighbors are equidistant, in which case round up. * Behaves as for {@code ROUND_UP} if the discarded fraction is * &ge; 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note * that this is the rounding mode that most of us were taught in * grade school. */ public final static int ROUND_HALF_UP = 4; /** {@collect.stats} * Rounding mode to round towards {@literal "nearest neighbor"} * unless both neighbors are equidistant, in which case round * down. Behaves as for {@code ROUND_UP} if the discarded * fraction is {@literal >} 0.5; otherwise, behaves as for * {@code ROUND_DOWN}. */ public final static int ROUND_HALF_DOWN = 5; /** {@collect.stats} * Rounding mode to round towards the {@literal "nearest neighbor"} * unless both neighbors are equidistant, in which case, round * towards the even neighbor. Behaves as for * {@code ROUND_HALF_UP} if the digit to the left of the * discarded fraction is odd; behaves as for * {@code ROUND_HALF_DOWN} if it's even. Note that this is the * rounding mode that minimizes cumulative error when applied * repeatedly over a sequence of calculations. */ public final static int ROUND_HALF_EVEN = 6; /** {@collect.stats} * Rounding mode to assert that the requested operation has an exact * result, hence no rounding is necessary. If this rounding mode is * specified on an operation that yields an inexact result, an * {@code ArithmeticException} is thrown. */ public final static int ROUND_UNNECESSARY = 7; // Scaling/Rounding Operations /** {@collect.stats} * Returns a {@code BigDecimal} rounded according to the * {@code MathContext} settings. If the precision setting is 0 then * no rounding takes place. * * <p>The effect of this method is identical to that of the * {@link #plus(MathContext)} method. * * @param mc the context to use. * @return a {@code BigDecimal} rounded according to the * {@code MathContext} settings. * @throws ArithmeticException if the rounding mode is * {@code UNNECESSARY} and the * {@code BigDecimal} operation would require rounding. * @see #plus(MathContext) * @since 1.5 */ public BigDecimal round(MathContext mc) { return plus(mc); } /** {@collect.stats} * Returns a {@code BigDecimal} whose scale is the specified * value, and whose unscaled value is determined by multiplying or * dividing this {@code BigDecimal}'s unscaled value by the * appropriate power of ten to maintain its overall value. If the * scale is reduced by the operation, the unscaled value must be * divided (rather than multiplied), and the value may be changed; * in this case, the specified rounding mode is applied to the * division. * * <p>Note that since BigDecimal objects are immutable, calls of * this method do <i>not</i> result in the original object being * modified, contrary to the usual convention of having methods * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>. * Instead, {@code setScale} returns an object with the proper * scale; the returned object may or may not be newly allocated. * * @param newScale scale of the {@code BigDecimal} value to be returned. * @param roundingMode The rounding mode to apply. * @return a {@code BigDecimal} whose scale is the specified value, * and whose unscaled value is determined by multiplying or * dividing this {@code BigDecimal}'s unscaled value by the * appropriate power of ten to maintain its overall value. * @throws ArithmeticException if {@code roundingMode==UNNECESSARY} * and the specified scaling operation would require * rounding. * @see RoundingMode * @since 1.5 */ public BigDecimal setScale(int newScale, RoundingMode roundingMode) { return setScale(newScale, roundingMode.oldMode); } /** {@collect.stats} * Returns a {@code BigDecimal} whose scale is the specified * value, and whose unscaled value is determined by multiplying or * dividing this {@code BigDecimal}'s unscaled value by the * appropriate power of ten to maintain its overall value. If the * scale is reduced by the operation, the unscaled value must be * divided (rather than multiplied), and the value may be changed; * in this case, the specified rounding mode is applied to the * division. * * <p>Note that since BigDecimal objects are immutable, calls of * this method do <i>not</i> result in the original object being * modified, contrary to the usual convention of having methods * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>. * Instead, {@code setScale} returns an object with the proper * scale; the returned object may or may not be newly allocated. * * <p>The new {@link #setScale(int, RoundingMode)} method should * be used in preference to this legacy method. * * @param newScale scale of the {@code BigDecimal} value to be returned. * @param roundingMode The rounding mode to apply. * @return a {@code BigDecimal} whose scale is the specified value, * and whose unscaled value is determined by multiplying or * dividing this {@code BigDecimal}'s unscaled value by the * appropriate power of ten to maintain its overall value. * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY} * and the specified scaling operation would require * rounding. * @throws IllegalArgumentException if {@code roundingMode} does not * represent a valid rounding mode. * @see #ROUND_UP * @see #ROUND_DOWN * @see #ROUND_CEILING * @see #ROUND_FLOOR * @see #ROUND_HALF_UP * @see #ROUND_HALF_DOWN * @see #ROUND_HALF_EVEN * @see #ROUND_UNNECESSARY */ public BigDecimal setScale(int newScale, int roundingMode) { if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY) throw new IllegalArgumentException("Invalid rounding mode"); int oldScale = this.scale; if (newScale == oldScale) // easy case return this; if (this.signum() == 0) // zero can have any scale return BigDecimal.valueOf(0, newScale); long rs = this.intCompact; if (newScale > oldScale) { int raise = checkScale((long)newScale - oldScale); BigInteger rb = null; if (rs == INFLATED || (rs = longMultiplyPowerTen(rs, raise)) == INFLATED) rb = bigMultiplyPowerTen(raise); return new BigDecimal(rb, rs, newScale, (precision > 0) ? precision + raise : 0); } else { // newScale < oldScale -- drop some digits // Can't predict the precision due to the effect of rounding. int drop = checkScale((long)oldScale - newScale); if (drop < LONG_TEN_POWERS_TABLE.length) return divideAndRound(rs, this.intVal, LONG_TEN_POWERS_TABLE[drop], null, newScale, roundingMode, newScale); else return divideAndRound(rs, this.intVal, INFLATED, bigTenToThe(drop), newScale, roundingMode, newScale); } } /** {@collect.stats} * Returns a {@code BigDecimal} whose scale is the specified * value, and whose value is numerically equal to this * {@code BigDecimal}'s. Throws an {@code ArithmeticException} * if this is not possible. * * <p>This call is typically used to increase the scale, in which * case it is guaranteed that there exists a {@code BigDecimal} * of the specified scale and the correct value. The call can * also be used to reduce the scale if the caller knows that the * {@code BigDecimal} has sufficiently many zeros at the end of * its fractional part (i.e., factors of ten in its integer value) * to allow for the rescaling without changing its value. * * <p>This method returns the same result as the two-argument * versions of {@code setScale}, but saves the caller the trouble * of specifying a rounding mode in cases where it is irrelevant. * * <p>Note that since {@code BigDecimal} objects are immutable, * calls of this method do <i>not</i> result in the original * object being modified, contrary to the usual convention of * having methods named <tt>set<i>X</i></tt> mutate field * <i>{@code X}</i>. Instead, {@code setScale} returns an * object with the proper scale; the returned object may or may * not be newly allocated. * * @param newScale scale of the {@code BigDecimal} value to be returned. * @return a {@code BigDecimal} whose scale is the specified value, and * whose unscaled value is determined by multiplying or dividing * this {@code BigDecimal}'s unscaled value by the appropriate * power of ten to maintain its overall value. * @throws ArithmeticException if the specified scaling operation would * require rounding. * @see #setScale(int, int) * @see #setScale(int, RoundingMode) */ public BigDecimal setScale(int newScale) { return setScale(newScale, ROUND_UNNECESSARY); } // Decimal Point Motion Operations /** {@collect.stats} * Returns a {@code BigDecimal} which is equivalent to this one * with the decimal point moved {@code n} places to the left. If * {@code n} is non-negative, the call merely adds {@code n} to * the scale. If {@code n} is negative, the call is equivalent * to {@code movePointRight(-n)}. The {@code BigDecimal} * returned by this call has value <tt>(this &times; * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n, * 0)}. * * @param n number of places to move the decimal point to the left. * @return a {@code BigDecimal} which is equivalent to this one with the * decimal point moved {@code n} places to the left. * @throws ArithmeticException if scale overflows. */ public BigDecimal movePointLeft(int n) { // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE int newScale = checkScale((long)scale + n); BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; } /** {@collect.stats} * Returns a {@code BigDecimal} which is equivalent to this one * with the decimal point moved {@code n} places to the right. * If {@code n} is non-negative, the call merely subtracts * {@code n} from the scale. If {@code n} is negative, the call * is equivalent to {@code movePointLeft(-n)}. The * {@code BigDecimal} returned by this call has value <tt>(this * &times; 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n, * 0)}. * * @param n number of places to move the decimal point to the right. * @return a {@code BigDecimal} which is equivalent to this one * with the decimal point moved {@code n} places to the right. * @throws ArithmeticException if scale overflows. */ public BigDecimal movePointRight(int n) { // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE int newScale = checkScale((long)scale - n); BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; } /** {@collect.stats} * Returns a BigDecimal whose numerical value is equal to * ({@code this} * 10<sup>n</sup>). The scale of * the result is {@code (this.scale() - n)}. * * @throws ArithmeticException if the scale would be * outside the range of a 32-bit integer. * * @since 1.5 */ public BigDecimal scaleByPowerOfTen(int n) { return new BigDecimal(intVal, intCompact, checkScale((long)scale - n), precision); } /** {@collect.stats} * Returns a {@code BigDecimal} which is numerically equal to * this one but with any trailing zeros removed from the * representation. For example, stripping the trailing zeros from * the {@code BigDecimal} value {@code 600.0}, which has * [{@code BigInteger}, {@code scale}] components equals to * [6000, 1], yields {@code 6E2} with [{@code BigInteger}, * {@code scale}] components equals to [6, -2] * * @return a numerically equal {@code BigDecimal} with any * trailing zeros removed. * @since 1.5 */ public BigDecimal stripTrailingZeros() { this.inflate(); BigDecimal result = new BigDecimal(intVal, scale); result.stripZerosToMatchScale(Long.MIN_VALUE); return result; } // Comparison Operations /** {@collect.stats} * Compares this {@code BigDecimal} with the specified * {@code BigDecimal}. Two {@code BigDecimal} objects that are * equal in value but have a different scale (like 2.0 and 2.00) * are considered equal by this method. This method is provided * in preference to individual methods for each of the six boolean * comparison operators ({@literal <}, ==, * {@literal >}, {@literal >=}, !=, {@literal <=}). The * suggested idiom for performing these comparisons is: * {@code (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where * &lt;<i>op</i>&gt; is one of the six comparison operators. * * @param val {@code BigDecimal} to which this {@code BigDecimal} is * to be compared. * @return -1, 0, or 1 as this {@code BigDecimal} is numerically * less than, equal to, or greater than {@code val}. */ public int compareTo(BigDecimal val) { // Quick path for equal scale and non-inflated case. if (scale == val.scale) { long xs = intCompact; long ys = val.intCompact; if (xs != INFLATED && ys != INFLATED) return xs != ys ? ((xs > ys) ? 1 : -1) : 0; } int xsign = this.signum(); int ysign = val.signum(); if (xsign != ysign) return (xsign > ysign) ? 1 : -1; if (xsign == 0) return 0; int cmp = compareMagnitude(val); return (xsign > 0) ? cmp : -cmp; } /** {@collect.stats} * Version of compareTo that ignores sign. */ private int compareMagnitude(BigDecimal val) { // Match scales, avoid unnecessary inflation long ys = val.intCompact; long xs = this.intCompact; if (xs == 0) return (ys == 0) ? 0 : -1; if (ys == 0) return 1; int sdiff = this.scale - val.scale; if (sdiff != 0) { // Avoid matching scales if the (adjusted) exponents differ int xae = this.precision() - this.scale; // [-1] int yae = val.precision() - val.scale; // [-1] if (xae < yae) return -1; if (xae > yae) return 1; BigInteger rb = null; if (sdiff < 0) { if ( (xs == INFLATED || (xs = longMultiplyPowerTen(xs, -sdiff)) == INFLATED) && ys == INFLATED) { rb = bigMultiplyPowerTen(-sdiff); return rb.compareMagnitude(val.intVal); } } else { // sdiff > 0 if ( (ys == INFLATED || (ys = longMultiplyPowerTen(ys, sdiff)) == INFLATED) && xs == INFLATED) { rb = val.bigMultiplyPowerTen(sdiff); return this.intVal.compareMagnitude(rb); } } } if (xs != INFLATED) return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1; else if (ys != INFLATED) return 1; else return this.intVal.compareMagnitude(val.intVal); } /** {@collect.stats} * Compares this {@code BigDecimal} with the specified * {@code Object} for equality. Unlike {@link * #compareTo(BigDecimal) compareTo}, this method considers two * {@code BigDecimal} objects equal only if they are equal in * value and scale (thus 2.0 is not equal to 2.00 when compared by * this method). * * @param x {@code Object} to which this {@code BigDecimal} is * to be compared. * @return {@code true} if and only if the specified {@code Object} is a * {@code BigDecimal} whose value and scale are equal to this * {@code BigDecimal}'s. * @see #compareTo(java.math.BigDecimal) * @see #hashCode */ @Override public boolean equals(Object x) { if (!(x instanceof BigDecimal)) return false; BigDecimal xDec = (BigDecimal) x; if (x == this) return true; if (scale != xDec.scale) return false; long s = this.intCompact; long xs = xDec.intCompact; if (s != INFLATED) { if (xs == INFLATED) xs = compactValFor(xDec.intVal); return xs == s; } else if (xs != INFLATED) return xs == compactValFor(this.intVal); return this.inflate().equals(xDec.inflate()); } /** {@collect.stats} * Returns the minimum of this {@code BigDecimal} and * {@code val}. * * @param val value with which the minimum is to be computed. * @return the {@code BigDecimal} whose value is the lesser of this * {@code BigDecimal} and {@code val}. If they are equal, * as defined by the {@link #compareTo(BigDecimal) compareTo} * method, {@code this} is returned. * @see #compareTo(java.math.BigDecimal) */ public BigDecimal min(BigDecimal val) { return (compareTo(val) <= 0 ? this : val); } /** {@collect.stats} * Returns the maximum of this {@code BigDecimal} and {@code val}. * * @param val value with which the maximum is to be computed. * @return the {@code BigDecimal} whose value is the greater of this * {@code BigDecimal} and {@code val}. If they are equal, * as defined by the {@link #compareTo(BigDecimal) compareTo} * method, {@code this} is returned. * @see #compareTo(java.math.BigDecimal) */ public BigDecimal max(BigDecimal val) { return (compareTo(val) >= 0 ? this : val); } // Hash Function /** {@collect.stats} * Returns the hash code for this {@code BigDecimal}. Note that * two {@code BigDecimal} objects that are numerically equal but * differ in scale (like 2.0 and 2.00) will generally <i>not</i> * have the same hash code. * * @return hash code for this {@code BigDecimal}. * @see #equals(Object) */ @Override public int hashCode() { if (intCompact != INFLATED) { long val2 = (intCompact < 0)? -intCompact : intCompact; int temp = (int)( ((int)(val2 >>> 32)) * 31 + (val2 & LONG_MASK)); return 31*((intCompact < 0) ?-temp:temp) + scale; } else return 31*intVal.hashCode() + scale; } // Format Converters /** {@collect.stats} * Returns the string representation of this {@code BigDecimal}, * using scientific notation if an exponent is needed. * * <p>A standard canonical string form of the {@code BigDecimal} * is created as though by the following steps: first, the * absolute value of the unscaled value of the {@code BigDecimal} * is converted to a string in base ten using the characters * {@code '0'} through {@code '9'} with no leading zeros (except * if its value is zero, in which case a single {@code '0'} * character is used). * * <p>Next, an <i>adjusted exponent</i> is calculated; this is the * negated scale, plus the number of characters in the converted * unscaled value, less one. That is, * {@code -scale+(ulength-1)}, where {@code ulength} is the * length of the absolute value of the unscaled value in decimal * digits (its <i>precision</i>). * * <p>If the scale is greater than or equal to zero and the * adjusted exponent is greater than or equal to {@code -6}, the * number will be converted to a character form without using * exponential notation. In this case, if the scale is zero then * no decimal point is added and if the scale is positive a * decimal point will be inserted with the scale specifying the * number of characters to the right of the decimal point. * {@code '0'} characters are added to the left of the converted * unscaled value as necessary. If no character precedes the * decimal point after this insertion then a conventional * {@code '0'} character is prefixed. * * <p>Otherwise (that is, if the scale is negative, or the * adjusted exponent is less than {@code -6}), the number will be * converted to a character form using exponential notation. In * this case, if the converted {@code BigInteger} has more than * one digit a decimal point is inserted after the first digit. * An exponent in character form is then suffixed to the converted * unscaled value (perhaps with inserted decimal point); this * comprises the letter {@code 'E'} followed immediately by the * adjusted exponent converted to a character form. The latter is * in base ten, using the characters {@code '0'} through * {@code '9'} with no leading zeros, and is always prefixed by a * sign character {@code '-'} (<tt>'&#92;u002D'</tt>) if the * adjusted exponent is negative, {@code '+'} * (<tt>'&#92;u002B'</tt>) otherwise). * * <p>Finally, the entire string is prefixed by a minus sign * character {@code '-'} (<tt>'&#92;u002D'</tt>) if the unscaled * value is less than zero. No sign character is prefixed if the * unscaled value is zero or positive. * * <p><b>Examples:</b> * <p>For each representation [<i>unscaled value</i>, <i>scale</i>] * on the left, the resulting string is shown on the right. * <pre> * [123,0] "123" * [-123,0] "-123" * [123,-1] "1.23E+3" * [123,-3] "1.23E+5" * [123,1] "12.3" * [123,5] "0.00123" * [123,10] "1.23E-8" * [-123,12] "-1.23E-10" * </pre> * * <b>Notes:</b> * <ol> * * <li>There is a one-to-one mapping between the distinguishable * {@code BigDecimal} values and the result of this conversion. * That is, every distinguishable {@code BigDecimal} value * (unscaled value and scale) has a unique string representation * as a result of using {@code toString}. If that string * representation is converted back to a {@code BigDecimal} using * the {@link #BigDecimal(String)} constructor, then the original * value will be recovered. * * <li>The string produced for a given number is always the same; * it is not affected by locale. This means that it can be used * as a canonical string representation for exchanging decimal * data, or as a key for a Hashtable, etc. Locale-sensitive * number formatting and parsing is handled by the {@link * java.text.NumberFormat} class and its subclasses. * * <li>The {@link #toEngineeringString} method may be used for * presenting numbers with exponents in engineering notation, and the * {@link #setScale(int,RoundingMode) setScale} method may be used for * rounding a {@code BigDecimal} so it has a known number of digits after * the decimal point. * * <li>The digit-to-character mapping provided by * {@code Character.forDigit} is used. * * </ol> * * @return string representation of this {@code BigDecimal}. * @see Character#forDigit * @see #BigDecimal(java.lang.String) */ @Override public String toString() { String sc = stringCache; if (sc == null) stringCache = sc = layoutChars(true); return sc; } /** {@collect.stats} * Returns a string representation of this {@code BigDecimal}, * using engineering notation if an exponent is needed. * * <p>Returns a string that represents the {@code BigDecimal} as * described in the {@link #toString()} method, except that if * exponential notation is used, the power of ten is adjusted to * be a multiple of three (engineering notation) such that the * integer part of nonzero values will be in the range 1 through * 999. If exponential notation is used for zero values, a * decimal point and one or two fractional zero digits are used so * that the scale of the zero value is preserved. Note that * unlike the output of {@link #toString()}, the output of this * method is <em>not</em> guaranteed to recover the same [integer, * scale] pair of this {@code BigDecimal} if the output string is * converting back to a {@code BigDecimal} using the {@linkplain * #BigDecimal(String) string constructor}. The result of this method meets * the weaker constraint of always producing a numerically equal * result from applying the string constructor to the method's output. * * @return string representation of this {@code BigDecimal}, using * engineering notation if an exponent is needed. * @since 1.5 */ public String toEngineeringString() { return layoutChars(false); } /** {@collect.stats} * Returns a string representation of this {@code BigDecimal} * without an exponent field. For values with a positive scale, * the number of digits to the right of the decimal point is used * to indicate scale. For values with a zero or negative scale, * the resulting string is generated as if the value were * converted to a numerically equal value with zero scale and as * if all the trailing zeros of the zero scale value were present * in the result. * * The entire string is prefixed by a minus sign character '-' * (<tt>'&#92;u002D'</tt>) if the unscaled value is less than * zero. No sign character is prefixed if the unscaled value is * zero or positive. * * Note that if the result of this method is passed to the * {@linkplain #BigDecimal(String) string constructor}, only the * numerical value of this {@code BigDecimal} will necessarily be * recovered; the representation of the new {@code BigDecimal} * may have a different scale. In particular, if this * {@code BigDecimal} has a negative scale, the string resulting * from this method will have a scale of zero when processed by * the string constructor. * * (This method behaves analogously to the {@code toString} * method in 1.4 and earlier releases.) * * @return a string representation of this {@code BigDecimal} * without an exponent field. * @since 1.5 * @see #toString() * @see #toEngineeringString() */ public String toPlainString() { BigDecimal bd = this; if (bd.scale < 0) bd = bd.setScale(0); bd.inflate(); if (bd.scale == 0) // No decimal point return bd.intVal.toString(); return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale); } /* Returns a digit.digit string */ private String getValueString(int signum, String intString, int scale) { /* Insert decimal point */ StringBuilder buf; int insertionPoint = intString.length() - scale; if (insertionPoint == 0) { /* Point goes right before intVal */ return (signum<0 ? "-0." : "0.") + intString; } else if (insertionPoint > 0) { /* Point goes inside intVal */ buf = new StringBuilder(intString); buf.insert(insertionPoint, '.'); if (signum < 0) buf.insert(0, '-'); } else { /* We must insert zeros between point and intVal */ buf = new StringBuilder(3-insertionPoint + intString.length()); buf.append(signum<0 ? "-0." : "0."); for (int i=0; i<-insertionPoint; i++) buf.append('0'); buf.append(intString); } return buf.toString(); } /** {@collect.stats} * Converts this {@code BigDecimal} to a {@code BigInteger}. * This conversion is analogous to a <a * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing * primitive conversion</i></a> from {@code double} to * {@code long} as defined in the <a * href="http://java.sun.com/docs/books/jls/html/">Java Language * Specification</a>: any fractional part of this * {@code BigDecimal} will be discarded. Note that this * conversion can lose information about the precision of the * {@code BigDecimal} value. * <p> * To have an exception thrown if the conversion is inexact (in * other words if a nonzero fractional part is discarded), use the * {@link #toBigIntegerExact()} method. * * @return this {@code BigDecimal} converted to a {@code BigInteger}. */ public BigInteger toBigInteger() { // force to an integer, quietly return this.setScale(0, ROUND_DOWN).inflate(); } /** {@collect.stats} * Converts this {@code BigDecimal} to a {@code BigInteger}, * checking for lost information. An exception is thrown if this * {@code BigDecimal} has a nonzero fractional part. * * @return this {@code BigDecimal} converted to a {@code BigInteger}. * @throws ArithmeticException if {@code this} has a nonzero * fractional part. * @since 1.5 */ public BigInteger toBigIntegerExact() { // round to an integer, with Exception if decimal part non-0 return this.setScale(0, ROUND_UNNECESSARY).inflate(); } /** {@collect.stats} * Converts this {@code BigDecimal} to a {@code long}. This * conversion is analogous to a <a * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing * primitive conversion</i></a> from {@code double} to * {@code short} as defined in the <a * href="http://java.sun.com/docs/books/jls/html/">Java Language * Specification</a>: any fractional part of this * {@code BigDecimal} will be discarded, and if the resulting * "{@code BigInteger}" is too big to fit in a * {@code long}, only the low-order 64 bits are returned. * Note that this conversion can lose information about the * overall magnitude and precision of this {@code BigDecimal} value as well * as return a result with the opposite sign. * * @return this {@code BigDecimal} converted to a {@code long}. */ public long longValue(){ return (intCompact != INFLATED && scale == 0) ? intCompact: toBigInteger().longValue(); } /** {@collect.stats} * Converts this {@code BigDecimal} to a {@code long}, checking * for lost information. If this {@code BigDecimal} has a * nonzero fractional part or is out of the possible range for a * {@code long} result then an {@code ArithmeticException} is * thrown. * * @return this {@code BigDecimal} converted to a {@code long}. * @throws ArithmeticException if {@code this} has a nonzero * fractional part, or will not fit in a {@code long}. * @since 1.5 */ public long longValueExact() { if (intCompact != INFLATED && scale == 0) return intCompact; // If more than 19 digits in integer part it cannot possibly fit if ((precision() - scale) > 19) // [OK for negative scale too] throw new java.lang.ArithmeticException("Overflow"); // Fastpath zero and < 1.0 numbers (the latter can be very slow // to round if very small) if (this.signum() == 0) return 0; if ((this.precision() - this.scale) <= 0) throw new ArithmeticException("Rounding necessary"); // round to an integer, with Exception if decimal part non-0 BigDecimal num = this.setScale(0, ROUND_UNNECESSARY); if (num.precision() >= 19) // need to check carefully LongOverflow.check(num); return num.inflate().longValue(); } private static class LongOverflow { /** {@collect.stats} BigInteger equal to Long.MIN_VALUE. */ private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE); /** {@collect.stats} BigInteger equal to Long.MAX_VALUE. */ private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE); public static void check(BigDecimal num) { num.inflate(); if ((num.intVal.compareTo(LONGMIN) < 0) || (num.intVal.compareTo(LONGMAX) > 0)) throw new java.lang.ArithmeticException("Overflow"); } } /** {@collect.stats} * Converts this {@code BigDecimal} to an {@code int}. This * conversion is analogous to a <a * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing * primitive conversion</i></a> from {@code double} to * {@code short} as defined in the <a * href="http://java.sun.com/docs/books/jls/html/">Java Language * Specification</a>: any fractional part of this * {@code BigDecimal} will be discarded, and if the resulting * "{@code BigInteger}" is too big to fit in an * {@code int}, only the low-order 32 bits are returned. * Note that this conversion can lose information about the * overall magnitude and precision of this {@code BigDecimal} * value as well as return a result with the opposite sign. * * @return this {@code BigDecimal} converted to an {@code int}. */ public int intValue() { return (intCompact != INFLATED && scale == 0) ? (int)intCompact : toBigInteger().intValue(); } /** {@collect.stats} * Converts this {@code BigDecimal} to an {@code int}, checking * for lost information. If this {@code BigDecimal} has a * nonzero fractional part or is out of the possible range for an * {@code int} result then an {@code ArithmeticException} is * thrown. * * @return this {@code BigDecimal} converted to an {@code int}. * @throws ArithmeticException if {@code this} has a nonzero * fractional part, or will not fit in an {@code int}. * @since 1.5 */ public int intValueExact() { long num; num = this.longValueExact(); // will check decimal part if ((int)num != num) throw new java.lang.ArithmeticException("Overflow"); return (int)num; } /** {@collect.stats} * Converts this {@code BigDecimal} to a {@code short}, checking * for lost information. If this {@code BigDecimal} has a * nonzero fractional part or is out of the possible range for a * {@code short} result then an {@code ArithmeticException} is * thrown. * * @return this {@code BigDecimal} converted to a {@code short}. * @throws ArithmeticException if {@code this} has a nonzero * fractional part, or will not fit in a {@code short}. * @since 1.5 */ public short shortValueExact() { long num; num = this.longValueExact(); // will check decimal part if ((short)num != num) throw new java.lang.ArithmeticException("Overflow"); return (short)num; } /** {@collect.stats} * Converts this {@code BigDecimal} to a {@code byte}, checking * for lost information. If this {@code BigDecimal} has a * nonzero fractional part or is out of the possible range for a * {@code byte} result then an {@code ArithmeticException} is * thrown. * * @return this {@code BigDecimal} converted to a {@code byte}. * @throws ArithmeticException if {@code this} has a nonzero * fractional part, or will not fit in a {@code byte}. * @since 1.5 */ public byte byteValueExact() { long num; num = this.longValueExact(); // will check decimal part if ((byte)num != num) throw new java.lang.ArithmeticException("Overflow"); return (byte)num; } /** {@collect.stats} * Converts this {@code BigDecimal} to a {@code float}. * This conversion is similar to the <a * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing * primitive conversion</i></a> from {@code double} to * {@code float} defined in the <a * href="http://java.sun.com/docs/books/jls/html/">Java Language * Specification</a>: if this {@code BigDecimal} has too great a * magnitude to represent as a {@code float}, it will be * converted to {@link Float#NEGATIVE_INFINITY} or {@link * Float#POSITIVE_INFINITY} as appropriate. Note that even when * the return value is finite, this conversion can lose * information about the precision of the {@code BigDecimal} * value. * * @return this {@code BigDecimal} converted to a {@code float}. */ public float floatValue(){ if (scale == 0 && intCompact != INFLATED) return (float)intCompact; // Somewhat inefficient, but guaranteed to work. return Float.parseFloat(this.toString()); } /** {@collect.stats} * Converts this {@code BigDecimal} to a {@code double}. * This conversion is similar to the <a * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing * primitive conversion</i></a> from {@code double} to * {@code float} as defined in the <a * href="http://java.sun.com/docs/books/jls/html/">Java Language * Specification</a>: if this {@code BigDecimal} has too great a * magnitude represent as a {@code double}, it will be * converted to {@link Double#NEGATIVE_INFINITY} or {@link * Double#POSITIVE_INFINITY} as appropriate. Note that even when * the return value is finite, this conversion can lose * information about the precision of the {@code BigDecimal} * value. * * @return this {@code BigDecimal} converted to a {@code double}. */ public double doubleValue(){ if (scale == 0 && intCompact != INFLATED) return (double)intCompact; // Somewhat inefficient, but guaranteed to work. return Double.parseDouble(this.toString()); } /** {@collect.stats} * Returns the size of an ulp, a unit in the last place, of this * {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal} * value is the positive distance between this value and the * {@code BigDecimal} value next larger in magnitude with the * same number of digits. An ulp of a zero value is numerically * equal to 1 with the scale of {@code this}. The result is * stored with the same scale as {@code this} so the result * for zero and nonzero values is equal to {@code [1, * this.scale()]}. * * @return the size of an ulp of {@code this} * @since 1.5 */ public BigDecimal ulp() { return BigDecimal.valueOf(1, this.scale()); } // Private class to build a string representation for BigDecimal object. // "StringBuilderHelper" is constructed as a thread local variable so it is // thread safe. The StringBuilder field acts as a buffer to hold the temporary // representation of BigDecimal. The cmpCharArray holds all the characters for // the compact representation of BigDecimal (except for '-' sign' if it is // negative) if its intCompact field is not INFLATED. It is shared by all // calls to toString() and its variants in that particular thread. static class StringBuilderHelper { final StringBuilder sb; // Placeholder for BigDecimal string final char[] cmpCharArray; // character array to place the intCompact StringBuilderHelper() { sb = new StringBuilder(); // All non negative longs can be made to fit into 19 character array. cmpCharArray = new char[19]; } // Accessors. StringBuilder getStringBuilder() { sb.setLength(0); return sb; } char[] getCompactCharArray() { return cmpCharArray; } /** {@collect.stats} * Places characters representing the intCompact in {@code long} into * cmpCharArray and returns the offset to the array where the * representation starts. * * @param intCompact the number to put into the cmpCharArray. * @return offset to the array where the representation starts. * Note: intCompact must be greater or equal to zero. */ int putIntCompact(long intCompact) { assert intCompact >= 0; long q; int r; // since we start from the least significant digit, charPos points to // the last character in cmpCharArray. int charPos = cmpCharArray.length; // Get 2 digits/iteration using longs until quotient fits into an int while (intCompact > Integer.MAX_VALUE) { q = intCompact / 100; r = (int)(intCompact - q * 100); intCompact = q; cmpCharArray[--charPos] = DIGIT_ONES[r]; cmpCharArray[--charPos] = DIGIT_TENS[r]; } // Get 2 digits/iteration using ints when i2 >= 100 int q2; int i2 = (int)intCompact; while (i2 >= 100) { q2 = i2 / 100; r = i2 - q2 * 100; i2 = q2; cmpCharArray[--charPos] = DIGIT_ONES[r]; cmpCharArray[--charPos] = DIGIT_TENS[r]; } cmpCharArray[--charPos] = DIGIT_ONES[i2]; if (i2 >= 10) cmpCharArray[--charPos] = DIGIT_TENS[i2]; return charPos; } final static char[] DIGIT_TENS = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', }; final static char[] DIGIT_ONES = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', }; } /** {@collect.stats} * Lay out this {@code BigDecimal} into a {@code char[]} array. * The Java 1.2 equivalent to this was called {@code getValueString}. * * @param sci {@code true} for Scientific exponential notation; * {@code false} for Engineering * @return string with canonical string representation of this * {@code BigDecimal} */ private String layoutChars(boolean sci) { if (scale == 0) // zero scale is trivial return (intCompact != INFLATED) ? Long.toString(intCompact): intVal.toString(); StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get(); char[] coeff; int offset; // offset is the starting index for coeff array // Get the significand as an absolute value if (intCompact != INFLATED) { offset = sbHelper.putIntCompact(Math.abs(intCompact)); coeff = sbHelper.getCompactCharArray(); } else { offset = 0; coeff = intVal.abs().toString().toCharArray(); } // Construct a buffer, with sufficient capacity for all cases. // If E-notation is needed, length will be: +1 if negative, +1 // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent. // Otherwise it could have +1 if negative, plus leading "0.00000" StringBuilder buf = sbHelper.getStringBuilder(); if (signum() < 0) // prefix '-' if negative buf.append('-'); int coeffLen = coeff.length - offset; long adjusted = -(long)scale + (coeffLen -1); if ((scale >= 0) && (adjusted >= -6)) { // plain number int pad = scale - coeffLen; // count of padding zeros if (pad >= 0) { // 0.xxx form buf.append('0'); buf.append('.'); for (; pad>0; pad--) { buf.append('0'); } buf.append(coeff, offset, coeffLen); } else { // xx.xx form buf.append(coeff, offset, -pad); buf.append('.'); buf.append(coeff, -pad + offset, scale); } } else { // E-notation is needed if (sci) { // Scientific notation buf.append(coeff[offset]); // first character if (coeffLen > 1) { // more to come buf.append('.'); buf.append(coeff, offset + 1, coeffLen - 1); } } else { // Engineering notation int sig = (int)(adjusted % 3); if (sig < 0) sig += 3; // [adjusted was negative] adjusted -= sig; // now a multiple of 3 sig++; if (signum() == 0) { switch (sig) { case 1: buf.append('0'); // exponent is a multiple of three break; case 2: buf.append("0.00"); adjusted += 3; break; case 3: buf.append("0.0"); adjusted += 3; break; default: throw new AssertionError("Unexpected sig value " + sig); } } else if (sig >= coeffLen) { // significand all in integer buf.append(coeff, offset, coeffLen); // may need some zeros, too for (int i = sig - coeffLen; i > 0; i--) buf.append('0'); } else { // xx.xxE form buf.append(coeff, offset, sig); buf.append('.'); buf.append(coeff, offset + sig, coeffLen - sig); } } if (adjusted != 0) { // [!sci could have made 0] buf.append('E'); if (adjusted > 0) // force sign for positive buf.append('+'); buf.append(adjusted); } } return buf.toString(); } /** {@collect.stats} * Return 10 to the power n, as a {@code BigInteger}. * * @param n the power of ten to be returned (>=0) * @return a {@code BigInteger} with the value (10<sup>n</sup>) */ private static BigInteger bigTenToThe(int n) { if (n < 0) return BigInteger.ZERO; if (n < BIG_TEN_POWERS_TABLE_MAX) { BigInteger[] pows = BIG_TEN_POWERS_TABLE; if (n < pows.length) return pows[n]; else return expandBigIntegerTenPowers(n); } // BigInteger.pow is slow, so make 10**n by constructing a // BigInteger from a character string (still not very fast) char tenpow[] = new char[n + 1]; tenpow[0] = '1'; for (int i = 1; i <= n; i++) tenpow[i] = '0'; return new BigInteger(tenpow); } /** {@collect.stats} * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n. * * @param n the power of ten to be returned (>=0) * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and * in the meantime, the BIG_TEN_POWERS_TABLE array gets * expanded to the size greater than n. */ private static BigInteger expandBigIntegerTenPowers(int n) { synchronized(BigDecimal.class) { BigInteger[] pows = BIG_TEN_POWERS_TABLE; int curLen = pows.length; // The following comparison and the above synchronized statement is // to prevent multiple threads from expanding the same array. if (curLen <= n) { int newLen = curLen << 1; while (newLen <= n) newLen <<= 1; pows = Arrays.copyOf(pows, newLen); for (int i = curLen; i < newLen; i++) pows[i] = pows[i - 1].multiply(BigInteger.TEN); // Based on the following facts: // 1. pows is a private local varible; // 2. the following store is a volatile store. // the newly created array elements can be safely published. BIG_TEN_POWERS_TABLE = pows; } return pows[n]; } } private static final long[] LONG_TEN_POWERS_TABLE = { 1, // 0 / 10^0 10, // 1 / 10^1 100, // 2 / 10^2 1000, // 3 / 10^3 10000, // 4 / 10^4 100000, // 5 / 10^5 1000000, // 6 / 10^6 10000000, // 7 / 10^7 100000000, // 8 / 10^8 1000000000, // 9 / 10^9 10000000000L, // 10 / 10^10 100000000000L, // 11 / 10^11 1000000000000L, // 12 / 10^12 10000000000000L, // 13 / 10^13 100000000000000L, // 14 / 10^14 1000000000000000L, // 15 / 10^15 10000000000000000L, // 16 / 10^16 100000000000000000L, // 17 / 10^17 1000000000000000000L // 18 / 10^18 }; private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {BigInteger.ONE, BigInteger.valueOf(10), BigInteger.valueOf(100), BigInteger.valueOf(1000), BigInteger.valueOf(10000), BigInteger.valueOf(100000), BigInteger.valueOf(1000000), BigInteger.valueOf(10000000), BigInteger.valueOf(100000000), BigInteger.valueOf(1000000000), BigInteger.valueOf(10000000000L), BigInteger.valueOf(100000000000L), BigInteger.valueOf(1000000000000L), BigInteger.valueOf(10000000000000L), BigInteger.valueOf(100000000000000L), BigInteger.valueOf(1000000000000000L), BigInteger.valueOf(10000000000000000L), BigInteger.valueOf(100000000000000000L), BigInteger.valueOf(1000000000000000000L) }; private static final int BIG_TEN_POWERS_TABLE_INITLEN = BIG_TEN_POWERS_TABLE.length; private static final int BIG_TEN_POWERS_TABLE_MAX = 16 * BIG_TEN_POWERS_TABLE_INITLEN; private static final long THRESHOLDS_TABLE[] = { Long.MAX_VALUE, // 0 Long.MAX_VALUE/10L, // 1 Long.MAX_VALUE/100L, // 2 Long.MAX_VALUE/1000L, // 3 Long.MAX_VALUE/10000L, // 4 Long.MAX_VALUE/100000L, // 5 Long.MAX_VALUE/1000000L, // 6 Long.MAX_VALUE/10000000L, // 7 Long.MAX_VALUE/100000000L, // 8 Long.MAX_VALUE/1000000000L, // 9 Long.MAX_VALUE/10000000000L, // 10 Long.MAX_VALUE/100000000000L, // 11 Long.MAX_VALUE/1000000000000L, // 12 Long.MAX_VALUE/10000000000000L, // 13 Long.MAX_VALUE/100000000000000L, // 14 Long.MAX_VALUE/1000000000000000L, // 15 Long.MAX_VALUE/10000000000000000L, // 16 Long.MAX_VALUE/100000000000000000L, // 17 Long.MAX_VALUE/1000000000000000000L // 18 }; /** {@collect.stats} * Compute val * 10 ^ n; return this product if it is * representable as a long, INFLATED otherwise. */ private static long longMultiplyPowerTen(long val, int n) { if (val == 0 || n <= 0) return val; long[] tab = LONG_TEN_POWERS_TABLE; long[] bounds = THRESHOLDS_TABLE; if (n < tab.length && n < bounds.length) { long tenpower = tab[n]; if (val == 1) return tenpower; if (Math.abs(val) <= bounds[n]) return val * tenpower; } return INFLATED; } /** {@collect.stats} * Compute this * 10 ^ n. * Needed mainly to allow special casing to trap zero value */ private BigInteger bigMultiplyPowerTen(int n) { if (n <= 0) return this.inflate(); if (intCompact != INFLATED) return bigTenToThe(n).multiply(intCompact); else return intVal.multiply(bigTenToThe(n)); } /** {@collect.stats} * Assign appropriate BigInteger to intVal field if intVal is * null, i.e. the compact representation is in use. */ private BigInteger inflate() { if (intVal == null) intVal = BigInteger.valueOf(intCompact); return intVal; } /** {@collect.stats} * Match the scales of two {@code BigDecimal}s to align their * least significant digits. * * <p>If the scales of val[0] and val[1] differ, rescale * (non-destructively) the lower-scaled {@code BigDecimal} so * they match. That is, the lower-scaled reference will be * replaced by a reference to a new object with the same scale as * the other {@code BigDecimal}. * * @param val array of two elements referring to the two * {@code BigDecimal}s to be aligned. */ private static void matchScale(BigDecimal[] val) { if (val[0].scale == val[1].scale) { return; } else if (val[0].scale < val[1].scale) { val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY); } else if (val[1].scale < val[0].scale) { val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY); } } /** {@collect.stats} * Reconstitute the {@code BigDecimal} instance from a stream (that is, * deserialize it). * * @param s the stream being read. */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in all fields s.defaultReadObject(); // validate possibly bad fields if (intVal == null) { String message = "BigDecimal: null intVal in stream"; throw new java.io.StreamCorruptedException(message); // [all values of scale are now allowed] } intCompact = compactValFor(intVal); } /** {@collect.stats} * Serialize this {@code BigDecimal} to the stream in question * * @param s the stream to serialize to. */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Must inflate to maintain compatible serial form. this.inflate(); // Write proper fields s.defaultWriteObject(); } /** {@collect.stats} * Returns the length of the absolute value of a {@code long}, in decimal * digits. * * @param x the {@code long} * @return the length of the unscaled value, in deciaml digits. */ private static int longDigitLength(long x) { /* * As described in "Bit Twiddling Hacks" by Sean Anderson, * (http://graphics.stanford.edu/~seander/bithacks.html) * integer log 10 of x is within 1 of * (1233/4096)* (1 + integer log 2 of x). * The fraction 1233/4096 approximates log10(2). So we first * do a version of log2 (a variant of Long class with * pre-checks and opposite directionality) and then scale and * check against powers table. This is a little simpler in * present context than the version in Hacker's Delight sec * 11-4. Adding one to bit length allows comparing downward * from the LONG_TEN_POWERS_TABLE that we need anyway. */ assert x != INFLATED; if (x < 0) x = -x; if (x < 10) // must screen for 0, might as well 10 return 1; int n = 64; // not 63, to avoid needing to add 1 later int y = (int)(x >>> 32); if (y == 0) { n -= 32; y = (int)x; } if (y >>> 16 == 0) { n -= 16; y <<= 16; } if (y >>> 24 == 0) { n -= 8; y <<= 8; } if (y >>> 28 == 0) { n -= 4; y <<= 4; } if (y >>> 30 == 0) { n -= 2; y <<= 2; } int r = (((y >>> 31) + n) * 1233) >>> 12; long[] tab = LONG_TEN_POWERS_TABLE; // if r >= length, must have max possible digits for long return (r >= tab.length || x < tab[r])? r : r+1; } /** {@collect.stats} * Returns the length of the absolute value of a BigInteger, in * decimal digits. * * @param b the BigInteger * @return the length of the unscaled value, in decimal digits */ private static int bigDigitLength(BigInteger b) { /* * Same idea as the long version, but we need a better * approximation of log10(2). Using 646456993/2^31 * is accurate up to max possible reported bitLength. */ if (b.signum == 0) return 1; int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31); return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1; } /** {@collect.stats} * Remove insignificant trailing zeros from this * {@code BigDecimal} until the preferred scale is reached or no * more zeros can be removed. If the preferred scale is less than * Integer.MIN_VALUE, all the trailing zeros will be removed. * * {@code BigInteger} assistance could help, here? * * <p>WARNING: This method should only be called on new objects as * it mutates the value fields. * * @return this {@code BigDecimal} with a scale possibly reduced * to be closed to the preferred scale. */ private BigDecimal stripZerosToMatchScale(long preferredScale) { this.inflate(); BigInteger qr[]; // quotient-remainder pair while ( intVal.compareMagnitude(BigInteger.TEN) >= 0 && scale > preferredScale) { if (intVal.testBit(0)) break; // odd number cannot end in 0 qr = intVal.divideAndRemainder(BigInteger.TEN); if (qr[1].signum() != 0) break; // non-0 remainder intVal=qr[0]; scale = checkScale((long)scale-1); // could Overflow if (precision > 0) // adjust precision if known precision--; } if (intVal != null) intCompact = compactValFor(intVal); return this; } /** {@collect.stats} * Check a scale for Underflow or Overflow. If this BigDecimal is * nonzero, throw an exception if the scale is outof range. If this * is zero, saturate the scale to the extreme value of the right * sign if the scale is out of range. * * @param val The new scale. * @throws ArithmeticException (overflow or underflow) if the new * scale is out of range. * @return validated scale as an int. */ private int checkScale(long val) { int asInt = (int)val; if (asInt != val) { asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE; BigInteger b; if (intCompact != 0 && ((b = intVal) == null || b.signum() != 0)) throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow"); } return asInt; } /** {@collect.stats} * Round an operand; used only if digits &gt; 0. Does not change * {@code this}; if rounding is needed a new {@code BigDecimal} * is created and returned. * * @param mc the context to use. * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY}. */ private BigDecimal roundOp(MathContext mc) { BigDecimal rounded = doRound(this, mc); return rounded; } /** {@collect.stats} Round this BigDecimal according to the MathContext settings; * used only if precision {@literal >} 0. * * <p>WARNING: This method should only be called on new objects as * it mutates the value fields. * * @param mc the context to use. * @throws ArithmeticException if the rounding mode is * {@code RoundingMode.UNNECESSARY} and the * {@code BigDecimal} operation would require rounding. */ private void roundThis(MathContext mc) { BigDecimal rounded = doRound(this, mc); if (rounded == this) // wasn't rounded return; this.intVal = rounded.intVal; this.intCompact = rounded.intCompact; this.scale = rounded.scale; this.precision = rounded.precision; } /** {@collect.stats} * Returns a {@code BigDecimal} rounded according to the * MathContext settings; used only if {@code mc.precision > 0}. * Does not change {@code this}; if rounding is needed a new * {@code BigDecimal} is created and returned. * * @param mc the context to use. * @return a {@code BigDecimal} rounded according to the MathContext * settings. May return this, if no rounding needed. * @throws ArithmeticException if the rounding mode is * {@code RoundingMode.UNNECESSARY} and the * result is inexact. */ private static BigDecimal doRound(BigDecimal d, MathContext mc) { int mcp = mc.precision; int drop; // This might (rarely) iterate to cover the 999=>1000 case while ((drop = d.precision() - mcp) > 0) { int newScale = d.checkScale((long)d.scale - drop); int mode = mc.roundingMode.oldMode; if (drop < LONG_TEN_POWERS_TABLE.length) d = divideAndRound(d.intCompact, d.intVal, LONG_TEN_POWERS_TABLE[drop], null, newScale, mode, newScale); else d = divideAndRound(d.intCompact, d.intVal, INFLATED, bigTenToThe(drop), newScale, mode, newScale); } return d; } /** {@collect.stats} * Returns the compact value for given {@code BigInteger}, or * INFLATED if too big. Relies on internal representation of * {@code BigInteger}. */ private static long compactValFor(BigInteger b) { int[] m = b.mag; int len = m.length; if (len == 0) return 0; int d = m[0]; if (len > 2 || (len == 2 && d < 0)) return INFLATED; long u = (len == 2)? (((long) m[1] & LONG_MASK) + (((long)d) << 32)) : (((long)d) & LONG_MASK); return (b.signum < 0)? -u : u; } private static int longCompareMagnitude(long x, long y) { if (x < 0) x = -x; if (y < 0) y = -y; return (x < y) ? -1 : ((x == y) ? 0 : 1); } private static int saturateLong(long s) { int i = (int)s; return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE); } /* * Internal printing routine */ private static void print(String name, BigDecimal bd) { System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n", name, bd.intCompact, bd.intVal, bd.scale, bd.precision); } /** {@collect.stats} * Check internal invariants of this BigDecimal. These invariants * include: * * <ul> * * <li>The object must be initialized; either intCompact must not be * INFLATED or intVal is non-null. Both of these conditions may * be true. * * <li>If both intCompact and intVal and set, their values must be * consistent. * * <li>If precision is nonzero, it must have the right value. * </ul> * * Note: Since this is an audit method, we are not supposed to change the * state of this BigDecimal object. */ private BigDecimal audit() { if (intCompact == INFLATED) { if (intVal == null) { print("audit", this); throw new AssertionError("null intVal"); } // Check precision if (precision > 0 && precision != bigDigitLength(intVal)) { print("audit", this); throw new AssertionError("precision mismatch"); } } else { if (intVal != null) { long val = intVal.longValue(); if (val != intCompact) { print("audit", this); throw new AssertionError("Inconsistent state, intCompact=" + intCompact + "\t intVal=" + val); } } // Check precision if (precision > 0 && precision != longDigitLength(intCompact)) { print("audit", this); throw new AssertionError("precision mismatch"); } } return this; } }
Java
/* * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.math; /** {@collect.stats} * A class used to represent multiprecision integers that makes efficient * use of allocated space by allowing a number to occupy only part of * an array so that the arrays do not have to be reallocated as often. * When performing an operation with many iterations the array used to * hold a number is only increased when necessary and does not have to * be the same size as the number it represents. A mutable number allows * calculations to occur on the same number without having to create * a new number for every step of the calculation as occurs with * BigIntegers. * * Note that SignedMutableBigIntegers only support signed addition and * subtraction. All other operations occur as with MutableBigIntegers. * * @see BigInteger * @author Michael McCloskey * @since 1.3 */ class SignedMutableBigInteger extends MutableBigInteger { /** {@collect.stats} * The sign of this MutableBigInteger. */ int sign = 1; // Constructors /** {@collect.stats} * The default constructor. An empty MutableBigInteger is created with * a one word capacity. */ SignedMutableBigInteger() { super(); } /** {@collect.stats} * Construct a new MutableBigInteger with a magnitude specified by * the int val. */ SignedMutableBigInteger(int val) { super(val); } /** {@collect.stats} * Construct a new MutableBigInteger with a magnitude equal to the * specified MutableBigInteger. */ SignedMutableBigInteger(MutableBigInteger val) { super(val); } // Arithmetic Operations /** {@collect.stats} * Signed addition built upon unsigned add and subtract. */ void signedAdd(SignedMutableBigInteger addend) { if (sign == addend.sign) add(addend); else sign = sign * subtract(addend); } /** {@collect.stats} * Signed addition built upon unsigned add and subtract. */ void signedAdd(MutableBigInteger addend) { if (sign == 1) add(addend); else sign = sign * subtract(addend); } /** {@collect.stats} * Signed subtraction built upon unsigned add and subtract. */ void signedSubtract(SignedMutableBigInteger addend) { if (sign == addend.sign) sign = sign * subtract(addend); else add(addend); } /** {@collect.stats} * Signed subtraction built upon unsigned add and subtract. */ void signedSubtract(MutableBigInteger addend) { if (sign == 1) sign = sign * subtract(addend); else add(addend); if (intLen == 0) sign = 1; } /** {@collect.stats} * Print out the first intLen ints of this MutableBigInteger's value * array starting at offset. */ public String toString() { return this.toBigInteger(sign).toString(); } }
Java
/* * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.event.*; import java.awt.peer.ComponentPeer; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.EmptyStackException; import java.util.logging.*; import sun.awt.AppContext; import sun.awt.AWTAutoShutdown; import sun.awt.PeerEvent; import sun.awt.SunToolkit; import java.security.AccessControlContext; import java.security.ProtectionDomain; import sun.misc.SharedSecrets; import sun.misc.JavaSecurityAccess; /** {@collect.stats} * <code>EventQueue</code> is a platform-independent class * that queues events, both from the underlying peer classes * and from trusted application classes. * <p> * It encapsulates asynchronous event dispatch machinery which * extracts events from the queue and dispatches them by calling * {@link #dispatchEvent(AWTEvent) dispatchEvent(AWTEvent)} method * on this <code>EventQueue</code> with the event to be dispatched * as an argument. The particular behavior of this machinery is * implementation-dependent. The only requirements are that events * which were actually enqueued to this queue (note that events * being posted to the <code>EventQueue</code> can be coalesced) * are dispatched: * <dl> * <dt> Sequentially. * <dd> That is, it is not permitted that several events from * this queue are dispatched simultaneously. * <dt> In the same order as they are enqueued. * <dd> That is, if <code>AWTEvent</code>&nbsp;A is enqueued * to the <code>EventQueue</code> before * <code>AWTEvent</code>&nbsp;B then event B will not be * dispatched before event A. * </dl> * <p> * Some browsers partition applets in different code bases into * separate contexts, and establish walls between these contexts. * In such a scenario, there will be one <code>EventQueue</code> * per context. Other browsers place all applets into the same * context, implying that there will be only a single, global * <code>EventQueue</code> for all applets. This behavior is * implementation-dependent. Consult your browser's documentation * for more information. * <p> * For information on the threading issues of the event dispatch * machinery, see <a href="doc-files/AWTThreadIssues.html#Autoshutdown" * >AWT Threading Issues</a>. * * @author Thomas Ball * @author Fred Ecks * @author David Mendenhall * * @since 1.1 */ public class EventQueue { // From Thread.java private static int threadInitNumber; private static synchronized int nextThreadNum() { return threadInitNumber++; } private static final int LOW_PRIORITY = 0; private static final int NORM_PRIORITY = 1; private static final int HIGH_PRIORITY = 2; private static final int ULTIMATE_PRIORITY = 3; private static final int NUM_PRIORITIES = ULTIMATE_PRIORITY + 1; /* * We maintain one Queue for each priority that the EventQueue supports. * That is, the EventQueue object is actually implemented as * NUM_PRIORITIES queues and all Events on a particular internal Queue * have identical priority. Events are pulled off the EventQueue starting * with the Queue of highest priority. We progress in decreasing order * across all Queues. */ private Queue[] queues = new Queue[NUM_PRIORITIES]; /* * The next EventQueue on the stack, or null if this EventQueue is * on the top of the stack. If nextQueue is non-null, requests to post * an event are forwarded to nextQueue. */ private EventQueue nextQueue; /* * The previous EventQueue on the stack, or null if this is the * "base" EventQueue. */ private EventQueue previousQueue; private EventDispatchThread dispatchThread; private final ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); private final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); /* * The time stamp of the last dispatched InputEvent or ActionEvent. */ private long mostRecentEventTime = System.currentTimeMillis(); /** {@collect.stats} * The modifiers field of the current event, if the current event is an * InputEvent or ActionEvent. */ private WeakReference currentEvent; /* * Non-zero if a thread is waiting in getNextEvent(int) for an event of * a particular ID to be posted to the queue. */ private int waitForID; private final String name = "AWT-EventQueue-" + nextThreadNum(); private static final Logger eventLog = Logger.getLogger("java.awt.event.EventQueue"); public EventQueue() { for (int i = 0; i < NUM_PRIORITIES; i++) { queues[i] = new Queue(); } /* * NOTE: if you ever have to start the associated event dispatch * thread at this point, be aware of the following problem: * If this EventQueue instance is created in * SunToolkit.createNewAppContext() the started dispatch thread * may call AppContext.getAppContext() before createNewAppContext() * completes thus causing mess in thread group to appcontext mapping. */ } /** {@collect.stats} * Posts a 1.1-style event to the <code>EventQueue</code>. * If there is an existing event on the queue with the same ID * and event source, the source <code>Component</code>'s * <code>coalesceEvents</code> method will be called. * * @param theEvent an instance of <code>java.awt.AWTEvent</code>, * or a subclass of it * @throws NullPointerException if <code>theEvent</code> is <code>null</code> */ public void postEvent(AWTEvent theEvent) { SunToolkit.flushPendingEvents(); postEventPrivate(theEvent); } /** {@collect.stats} * Posts a 1.1-style event to the <code>EventQueue</code>. * If there is an existing event on the queue with the same ID * and event source, the source <code>Component</code>'s * <code>coalesceEvents</code> method will be called. * * @param theEvent an instance of <code>java.awt.AWTEvent</code>, * or a subclass of it */ final void postEventPrivate(AWTEvent theEvent) { theEvent.isPosted = true; synchronized(this) { if (dispatchThread == null && nextQueue == null) { if (theEvent.getSource() == AWTAutoShutdown.getInstance()) { return; } else { initDispatchThread(); } } if (nextQueue != null) { // Forward event to top of EventQueue stack. nextQueue.postEventPrivate(theEvent); return; } postEvent(theEvent, getPriority(theEvent)); } } private static int getPriority(AWTEvent theEvent) { if (theEvent instanceof PeerEvent && (((PeerEvent)theEvent).getFlags() & PeerEvent.ULTIMATE_PRIORITY_EVENT) != 0) { return ULTIMATE_PRIORITY; } if (theEvent instanceof PeerEvent && (((PeerEvent)theEvent).getFlags() & PeerEvent.PRIORITY_EVENT) != 0) { return HIGH_PRIORITY; } if (theEvent instanceof PeerEvent && (((PeerEvent)theEvent).getFlags() & PeerEvent.LOW_PRIORITY_EVENT) != 0) { return LOW_PRIORITY; } int id = theEvent.getID(); if (id == PaintEvent.PAINT || id == PaintEvent.UPDATE) { return LOW_PRIORITY; } return NORM_PRIORITY; } /** {@collect.stats} * Posts the event to the internal Queue of specified priority, * coalescing as appropriate. * * @param theEvent an instance of <code>java.awt.AWTEvent</code>, * or a subclass of it * @param priority the desired priority of the event */ private void postEvent(AWTEvent theEvent, int priority) { if (coalesceEvent(theEvent, priority)) { return; } EventQueueItem newItem = new EventQueueItem(theEvent); cacheEQItem(newItem); boolean notifyID = (theEvent.getID() == this.waitForID); if (queues[priority].head == null) { boolean shouldNotify = noEvents(); queues[priority].head = queues[priority].tail = newItem; if (shouldNotify) { if (theEvent.getSource() != AWTAutoShutdown.getInstance()) { AWTAutoShutdown.getInstance().notifyThreadBusy(dispatchThread); } notifyAll(); } else if (notifyID) { notifyAll(); } } else { // The event was not coalesced or has non-Component source. // Insert it at the end of the appropriate Queue. queues[priority].tail.next = newItem; queues[priority].tail = newItem; if (notifyID) { notifyAll(); } } } private boolean coalescePaintEvent(PaintEvent e) { ComponentPeer sourcePeer = ((Component)e.getSource()).peer; if (sourcePeer != null) { sourcePeer.coalescePaintEvent(e); } EventQueueItem[] cache = ((Component)e.getSource()).eventCache; if (cache == null) { return false; } int index = eventToCacheIndex(e); if (index != -1 && cache[index] != null) { PaintEvent merged = mergePaintEvents(e, (PaintEvent)cache[index].event); if (merged != null) { cache[index].event = merged; return true; } } return false; } private PaintEvent mergePaintEvents(PaintEvent a, PaintEvent b) { Rectangle aRect = a.getUpdateRect(); Rectangle bRect = b.getUpdateRect(); if (bRect.contains(aRect)) { return b; } if (aRect.contains(bRect)) { return a; } return null; } private boolean coalesceMouseEvent(MouseEvent e) { EventQueueItem[] cache = ((Component)e.getSource()).eventCache; if (cache == null) { return false; } int index = eventToCacheIndex(e); if (index != -1 && cache[index] != null) { cache[index].event = e; return true; } return false; } private boolean coalescePeerEvent(PeerEvent e) { EventQueueItem[] cache = ((Component)e.getSource()).eventCache; if (cache == null) { return false; } int index = eventToCacheIndex(e); if (index != -1 && cache[index] != null) { e = e.coalesceEvents((PeerEvent)cache[index].event); if (e != null) { cache[index].event = e; return true; } else { cache[index] = null; } } return false; } /* * Should avoid of calling this method by any means * as it's working time is dependant on EQ length. * In the wors case this method alone can slow down the entire application * 10 times by stalling the Event processing. * Only here by backward compatibility reasons. */ private boolean coalesceOtherEvent(AWTEvent e, int priority) { int id = e.getID(); Component source = (Component)e.getSource(); for (EventQueueItem entry = queues[priority].head; entry != null; entry = entry.next) { // Give Component.coalesceEvents a chance if (entry.event.getSource() == source && entry.id == id) { AWTEvent coalescedEvent = source.coalesceEvents( entry.event, e); if (coalescedEvent != null) { entry.event = coalescedEvent; return true; } } } return false; } private boolean coalesceEvent(AWTEvent e, int priority) { if (!(e.getSource() instanceof Component)) { return false; } if (e instanceof PeerEvent) { return coalescePeerEvent((PeerEvent)e); } // The worst case if (((Component)e.getSource()).isCoalescingEnabled() && coalesceOtherEvent(e, priority)) { return true; } if (e instanceof PaintEvent) { return coalescePaintEvent((PaintEvent)e); } if (e instanceof MouseEvent) { return coalesceMouseEvent((MouseEvent)e); } return false; } private void cacheEQItem(EventQueueItem entry) { int index = eventToCacheIndex(entry.event); if (index != -1 && entry.event.getSource() instanceof Component) { Component source = (Component)entry.event.getSource(); if (source.eventCache == null) { source.eventCache = new EventQueueItem[CACHE_LENGTH]; } source.eventCache[index] = entry; } } private void uncacheEQItem(EventQueueItem entry) { int index = eventToCacheIndex(entry.event); if (index != -1 && entry.event.getSource() instanceof Component) { Component source = (Component)entry.event.getSource(); if (source.eventCache == null) { return; } source.eventCache[index] = null; } } private static final int PAINT = 0; private static final int UPDATE = 1; private static final int MOVE = 2; private static final int DRAG = 3; private static final int PEER = 4; private static final int CACHE_LENGTH = 5; private static int eventToCacheIndex(AWTEvent e) { switch(e.getID()) { case PaintEvent.PAINT: return PAINT; case PaintEvent.UPDATE: return UPDATE; case MouseEvent.MOUSE_MOVED: return MOVE; case MouseEvent.MOUSE_DRAGGED: return DRAG; default: return e instanceof PeerEvent ? PEER : -1; } } /** {@collect.stats} * Returns whether an event is pending on any of the separate * Queues. * @return whether an event is pending on any of the separate Queues */ private boolean noEvents() { for (int i = 0; i < NUM_PRIORITIES; i++) { if (queues[i].head != null) { return false; } } return true; } /** {@collect.stats} * Removes an event from the <code>EventQueue</code> and * returns it. This method will block until an event has * been posted by another thread. * @return the next <code>AWTEvent</code> * @exception InterruptedException * if any thread has interrupted this thread */ public AWTEvent getNextEvent() throws InterruptedException { do { /* * SunToolkit.flushPendingEvents must be called outside * of the synchronized block to avoid deadlock when * event queues are nested with push()/pop(). */ SunToolkit.flushPendingEvents(); synchronized (this) { for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { if (queues[i].head != null) { EventQueueItem entry = queues[i].head; queues[i].head = entry.next; if (entry.next == null) { queues[i].tail = null; } uncacheEQItem(entry); return entry.event; } } AWTAutoShutdown.getInstance().notifyThreadFree(dispatchThread); wait(); } } while(true); } AWTEvent getNextEvent(int id) throws InterruptedException { do { /* * SunToolkit.flushPendingEvents must be called outside * of the synchronized block to avoid deadlock when * event queues are nested with push()/pop(). */ SunToolkit.flushPendingEvents(); synchronized (this) { for (int i = 0; i < NUM_PRIORITIES; i++) { for (EventQueueItem entry = queues[i].head, prev = null; entry != null; prev = entry, entry = entry.next) { if (entry.id == id) { if (prev == null) { queues[i].head = entry.next; } else { prev.next = entry.next; } if (queues[i].tail == entry) { queues[i].tail = prev; } uncacheEQItem(entry); return entry.event; } } } this.waitForID = id; wait(); this.waitForID = 0; } } while(true); } /** {@collect.stats} * Returns the first event on the <code>EventQueue</code> * without removing it. * @return the first event */ public synchronized AWTEvent peekEvent() { for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { if (queues[i].head != null) { return queues[i].head.event; } } return null; } /** {@collect.stats} * Returns the first event with the specified id, if any. * @param id the id of the type of event desired * @return the first event of the specified id or <code>null</code> * if there is no such event */ public synchronized AWTEvent peekEvent(int id) { for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { EventQueueItem q = queues[i].head; for (; q != null; q = q.next) { if (q.id == id) { return q.event; } } } return null; } private static final JavaSecurityAccess javaSecurityAccess = SharedSecrets.getJavaSecurityAccess(); /** {@collect.stats} * Dispatches an event. The manner in which the event is * dispatched depends upon the type of the event and the * type of the event's source object: * <p> </p> * <table border=1 summary="Event types, source types, and dispatch methods"> * <tr> * <th>Event Type</th> * <th>Source Type</th> * <th>Dispatched To</th> * </tr> * <tr> * <td>ActiveEvent</td> * <td>Any</td> * <td>event.dispatch()</td> * </tr> * <tr> * <td>Other</td> * <td>Component</td> * <td>source.dispatchEvent(AWTEvent)</td> * </tr> * <tr> * <td>Other</td> * <td>MenuComponent</td> * <td>source.dispatchEvent(AWTEvent)</td> * </tr> * <tr> * <td>Other</td> * <td>Other</td> * <td>No action (ignored)</td> * </tr> * </table> * <p> </p> * @param event an instance of <code>java.awt.AWTEvent</code>, * or a subclass of it * @throws NullPointerException if <code>event</code> is <code>null</code> * @since 1.2 */ protected void dispatchEvent(final AWTEvent event) { final Object src = event.getSource(); final PrivilegedAction<Void> action = new PrivilegedAction<Void>() { public Void run() { dispatchEventImpl(event, src); return null; } }; final AccessControlContext stack = AccessController.getContext(); final AccessControlContext srcAcc = getAccessControlContextFrom(src); final AccessControlContext eventAcc = event.getAccessControlContext(); if (srcAcc == null) { javaSecurityAccess.doIntersectionPrivilege(action, stack, eventAcc); } else { javaSecurityAccess.doIntersectionPrivilege( new PrivilegedAction<Void>() { public Void run() { javaSecurityAccess.doIntersectionPrivilege(action, eventAcc); return null; } }, stack, srcAcc); } } private static AccessControlContext getAccessControlContextFrom(Object src) { return src instanceof Component ? ((Component)src).getAccessControlContext() : src instanceof MenuComponent ? ((MenuComponent)src).getAccessControlContext() : src instanceof TrayIcon ? ((TrayIcon)src).getAccessControlContext() : null; } /** {@collect.stats} * Called from dispatchEvent() under a correct AccessControlContext */ private void dispatchEventImpl(final AWTEvent event, final Object src) { event.isPosted = true; if (event instanceof ActiveEvent) { // This could become the sole method of dispatching in time. setCurrentEventAndMostRecentTimeImpl(event); ((ActiveEvent)event).dispatch(); } else if (src instanceof Component) { ((Component)src).dispatchEvent(event); event.dispatched(); } else if (src instanceof MenuComponent) { ((MenuComponent)src).dispatchEvent(event); } else if (src instanceof TrayIcon) { ((TrayIcon)src).dispatchEvent(event); } else if (src instanceof AWTAutoShutdown) { if (noEvents()) { dispatchThread.stopDispatching(); } } else { System.err.println("unable to dispatch event: " + event); } } /** {@collect.stats} * Returns the timestamp of the most recent event that had a timestamp, and * that was dispatched from the <code>EventQueue</code> associated with the * calling thread. If an event with a timestamp is currently being * dispatched, its timestamp will be returned. If no events have yet * been dispatched, the EventQueue's initialization time will be * returned instead.In the current version of * the JDK, only <code>InputEvent</code>s, * <code>ActionEvent</code>s, and <code>InvocationEvent</code>s have * timestamps; however, future versions of the JDK may add timestamps to * additional event types. Note that this method should only be invoked * from an application's event dispatching thread. If this method is * invoked from another thread, the current system time (as reported by * <code>System.currentTimeMillis()</code>) will be returned instead. * * @return the timestamp of the last <code>InputEvent</code>, * <code>ActionEvent</code>, or <code>InvocationEvent</code> to be * dispatched, or <code>System.currentTimeMillis()</code> if this * method is invoked on a thread other than an event dispatching * thread * @see java.awt.event.InputEvent#getWhen * @see java.awt.event.ActionEvent#getWhen * @see java.awt.event.InvocationEvent#getWhen * * @since 1.4 */ public static long getMostRecentEventTime() { return Toolkit.getEventQueue().getMostRecentEventTimeImpl(); } private synchronized long getMostRecentEventTimeImpl() { return (Thread.currentThread() == dispatchThread) ? mostRecentEventTime : System.currentTimeMillis(); } /** {@collect.stats} * @return most recent event time on all threads. */ synchronized long getMostRecentEventTimeEx() { return mostRecentEventTime; } /** {@collect.stats} * Returns the the event currently being dispatched by the * <code>EventQueue</code> associated with the calling thread. This is * useful if a method needs access to the event, but was not designed to * receive a reference to it as an argument. Note that this method should * only be invoked from an application's event dispatching thread. If this * method is invoked from another thread, null will be returned. * * @return the event currently being dispatched, or null if this method is * invoked on a thread other than an event dispatching thread * @since 1.4 */ public static AWTEvent getCurrentEvent() { return Toolkit.getEventQueue().getCurrentEventImpl(); } private synchronized AWTEvent getCurrentEventImpl() { return (Thread.currentThread() == dispatchThread) ? ((AWTEvent)currentEvent.get()) : null; } /** {@collect.stats} * Replaces the existing <code>EventQueue</code> with the specified one. * Any pending events are transferred to the new <code>EventQueue</code> * for processing by it. * * @param newEventQueue an <code>EventQueue</code> * (or subclass thereof) instance to be use * @see java.awt.EventQueue#pop * @throws NullPointerException if <code>newEventQueue</code> is <code>null</code> * @since 1.2 */ public synchronized void push(EventQueue newEventQueue) { if (eventLog.isLoggable(Level.FINE)) { eventLog.log(Level.FINE, "EventQueue.push(" + newEventQueue + ")"); } if (nextQueue != null) { nextQueue.push(newEventQueue); return; } synchronized (newEventQueue) { // Transfer all events forward to new EventQueue. while (peekEvent() != null) { try { newEventQueue.postEventPrivate(getNextEvent()); } catch (InterruptedException ie) { if (eventLog.isLoggable(Level.FINE)) { eventLog.log(Level.FINE, "Interrupted push", ie); } } } newEventQueue.previousQueue = this; } /* * Stop the event dispatch thread associated with the currently * active event queue, so that after the new queue is pushed * on the top this event dispatch thread won't prevent AWT from * being automatically shut down. * Use stopDispatchingLater() to avoid deadlock: stopDispatching() * waits for the dispatch thread to exit, so if the dispatch * thread attempts to synchronize on this EventQueue object * it will never exit since we already hold this lock. */ if (dispatchThread != null) { dispatchThread.stopDispatchingLater(); } nextQueue = newEventQueue; AppContext appContext = AppContext.getAppContext(); if (appContext.get(AppContext.EVENT_QUEUE_KEY) == this) { appContext.put(AppContext.EVENT_QUEUE_KEY, newEventQueue); } } /** {@collect.stats} * Stops dispatching events using this <code>EventQueue</code>. * Any pending events are transferred to the previous * <code>EventQueue</code> for processing. * <p> * Warning: To avoid deadlock, do not declare this method * synchronized in a subclass. * * @exception EmptyStackException if no previous push was made * on this <code>EventQueue</code> * @see java.awt.EventQueue#push * @since 1.2 */ protected void pop() throws EmptyStackException { if (eventLog.isLoggable(Level.FINE)) { eventLog.log(Level.FINE, "EventQueue.pop(" + this + ")"); } // To prevent deadlock, we lock on the previous EventQueue before // this one. This uses the same locking order as everything else // in EventQueue.java, so deadlock isn't possible. EventQueue prev = previousQueue; synchronized ((prev != null) ? prev : this) { synchronized(this) { if (nextQueue != null) { nextQueue.pop(); return; } if (previousQueue == null) { throw new EmptyStackException(); } // Transfer all events back to previous EventQueue. previousQueue.nextQueue = null; while (peekEvent() != null) { try { previousQueue.postEventPrivate(getNextEvent()); } catch (InterruptedException ie) { if (eventLog.isLoggable(Level.FINE)) { eventLog.log(Level.FINE, "Interrupted pop", ie); } } } AppContext appContext = AppContext.getAppContext(); if (appContext.get(AppContext.EVENT_QUEUE_KEY) == this) { appContext.put(AppContext.EVENT_QUEUE_KEY, previousQueue); } previousQueue = null; } } EventDispatchThread dt = this.dispatchThread; if (dt != null) { dt.stopDispatching(); // Must be done outside synchronized // block to avoid possible deadlock } } /** {@collect.stats} * Returns true if the calling thread is the current AWT * <code>EventQueue</code>'s dispatch thread. Use this * call the ensure that a given * task is being executed (or not being) on the current AWT * <code>EventDispatchThread</code>. * * @return true if running on the current AWT * <code>EventQueue</code>'s dispatch thread * @since 1.2 */ public static boolean isDispatchThread() { EventQueue eq = Toolkit.getEventQueue(); EventQueue next = eq.nextQueue; while (next != null) { eq = next; next = eq.nextQueue; } return (Thread.currentThread() == eq.dispatchThread); } final void initDispatchThread() { synchronized (this) { if (dispatchThread == null && !threadGroup.isDestroyed()) { dispatchThread = (EventDispatchThread) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { EventDispatchThread t = new EventDispatchThread(threadGroup, name, EventQueue.this); t.setContextClassLoader(classLoader); t.setPriority(Thread.NORM_PRIORITY + 1); t.setDaemon(false); return t; } }); AWTAutoShutdown.getInstance().notifyThreadBusy(dispatchThread); dispatchThread.start(); } } } final void detachDispatchThread() { dispatchThread = null; } /* * Gets the <code>EventDispatchThread</code> for this * <code>EventQueue</code>. * @return the event dispatch thread associated with this event queue * or <code>null</code> if this event queue doesn't have a * working thread associated with it * @see java.awt.EventQueue#initDispatchThread * @see java.awt.EventQueue#detachDispatchThread */ final EventDispatchThread getDispatchThread() { return dispatchThread; } /* * Removes any pending events for the specified source object. * If removeAllEvents parameter is <code>true</code> then all * events for the specified source object are removed, if it * is <code>false</code> then <code>SequencedEvent</code>, <code>SentEvent</code>, * <code>FocusEvent</code>, <code>WindowEvent</code>, <code>KeyEvent</code>, * and <code>InputMethodEvent</code> are kept in the queue, but all other * events are removed. * * This method is normally called by the source's * <code>removeNotify</code> method. */ final void removeSourceEvents(Object source, boolean removeAllEvents) { SunToolkit.flushPendingEvents(); synchronized (this) { for (int i = 0; i < NUM_PRIORITIES; i++) { EventQueueItem entry = queues[i].head; EventQueueItem prev = null; while (entry != null) { if ((entry.event.getSource() == source) && (removeAllEvents || ! (entry.event instanceof SequencedEvent || entry.event instanceof SentEvent || entry.event instanceof FocusEvent || entry.event instanceof WindowEvent || entry.event instanceof KeyEvent || entry.event instanceof InputMethodEvent))) { if (entry.event instanceof SequencedEvent) { ((SequencedEvent)entry.event).dispose(); } if (entry.event instanceof SentEvent) { ((SentEvent)entry.event).dispose(); } if (prev == null) { queues[i].head = entry.next; } else { prev.next = entry.next; } uncacheEQItem(entry); } else { prev = entry; } entry = entry.next; } queues[i].tail = prev; } } } static void setCurrentEventAndMostRecentTime(AWTEvent e) { Toolkit.getEventQueue().setCurrentEventAndMostRecentTimeImpl(e); } private synchronized void setCurrentEventAndMostRecentTimeImpl(AWTEvent e) { if (Thread.currentThread() != dispatchThread) { return; } currentEvent = new WeakReference(e); // This series of 'instanceof' checks should be replaced with a // polymorphic type (for example, an interface which declares a // getWhen() method). However, this would require us to make such // a type public, or to place it in sun.awt. Both of these approaches // have been frowned upon. So for now, we hack. // // In tiger, we will probably give timestamps to all events, so this // will no longer be an issue. long mostRecentEventTime2 = Long.MIN_VALUE; if (e instanceof InputEvent) { InputEvent ie = (InputEvent)e; mostRecentEventTime2 = ie.getWhen(); } else if (e instanceof InputMethodEvent) { InputMethodEvent ime = (InputMethodEvent)e; mostRecentEventTime2 = ime.getWhen(); } else if (e instanceof ActionEvent) { ActionEvent ae = (ActionEvent)e; mostRecentEventTime2 = ae.getWhen(); } else if (e instanceof InvocationEvent) { InvocationEvent ie = (InvocationEvent)e; mostRecentEventTime2 = ie.getWhen(); } mostRecentEventTime = Math.max(mostRecentEventTime, mostRecentEventTime2); } /** {@collect.stats} * Causes <code>runnable</code> to have its <code>run</code> * method called in the dispatch thread of * {@link Toolkit#getSystemEventQueue the system EventQueue}. * This will happen after all pending events are processed. * * @param runnable the <code>Runnable</code> whose <code>run</code> * method should be executed * synchronously on the <code>EventQueue</code> * @see #invokeAndWait * @since 1.2 */ public static void invokeLater(Runnable runnable) { Toolkit.getEventQueue().postEvent( new InvocationEvent(Toolkit.getDefaultToolkit(), runnable)); } /** {@collect.stats} * Causes <code>runnable</code> to have its <code>run</code> * method called in the dispatch thread of * {@link Toolkit#getSystemEventQueue the system EventQueue}. * This will happen after all pending events are processed. * The call blocks until this has happened. This method * will throw an Error if called from the event dispatcher thread. * * @param runnable the <code>Runnable</code> whose <code>run</code> * method should be executed * synchronously on the <code>EventQueue</code> * @exception InterruptedException if any thread has * interrupted this thread * @exception InvocationTargetException if an throwable is thrown * when running <code>runnable</code> * @see #invokeLater * @since 1.2 */ public static void invokeAndWait(Runnable runnable) throws InterruptedException, InvocationTargetException { if (EventQueue.isDispatchThread()) { throw new Error("Cannot call invokeAndWait from the event dispatcher thread"); } class AWTInvocationLock {} Object lock = new AWTInvocationLock(); InvocationEvent event = new InvocationEvent(Toolkit.getDefaultToolkit(), runnable, lock, true); synchronized (lock) { Toolkit.getEventQueue().postEvent(event); lock.wait(); } Throwable eventThrowable = event.getThrowable(); if (eventThrowable != null) { throw new InvocationTargetException(eventThrowable); } } /* * Called from PostEventQueue.postEvent to notify that a new event * appeared. First it proceeds to the EventQueue on the top of the * stack, then notifies the associated dispatch thread if it exists * or starts a new one otherwise. */ private void wakeup(boolean isShutdown) { synchronized(this) { if (nextQueue != null) { // Forward call to the top of EventQueue stack. nextQueue.wakeup(isShutdown); } else if (dispatchThread != null) { notifyAll(); } else if (!isShutdown) { initDispatchThread(); } } } } /** {@collect.stats} * The Queue object holds pointers to the beginning and end of one internal * queue. An EventQueue object is composed of multiple internal Queues, one * for each priority supported by the EventQueue. All Events on a particular * internal Queue have identical priority. */ class Queue { EventQueueItem head; EventQueueItem tail; } class EventQueueItem { AWTEvent event; int id; EventQueueItem next; EventQueueItem(AWTEvent evt) { event = evt; id = evt.getID(); } }
Java
/* * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; /** {@collect.stats} * The {@code GridBagLayoutInfo} is an utility class for * {@code GridBagLayout} layout manager. * It stores align, size and baseline parameters for every component within a container. * <p> * @see java.awt.GridBagLayout * @see java.awt.GridBagConstraints * @since 1.6 */ public class GridBagLayoutInfo implements java.io.Serializable { /* * serialVersionUID */ private static final long serialVersionUID = -4899416460737170217L; int width, height; /* number of cells: horizontal and vertical */ int startx, starty; /* starting point for layout */ int minWidth[]; /* largest minWidth in each column */ int minHeight[]; /* largest minHeight in each row */ double weightX[]; /* largest weight in each column */ double weightY[]; /* largest weight in each row */ boolean hasBaseline; /* Whether or not baseline layout has been * requested and one of the components * has a valid baseline. */ // These are only valid if hasBaseline is true and are indexed by // row. short baselineType[]; /* The type of baseline for a particular * row. A mix of the BaselineResizeBehavior * constants (1 << ordinal()) */ int maxAscent[]; /* Max ascent (baseline). */ int maxDescent[]; /* Max descent (height - baseline) */ /** {@collect.stats} * Creates an instance of GridBagLayoutInfo representing {@code GridBagLayout} * grid cells with it's own parameters. * @param width the columns * @param height the rows * @since 6.0 */ GridBagLayoutInfo(int width, int height) { this.width = width; this.height = height; } /** {@collect.stats} * Returns true if the specified row has any component aligned on the * baseline with a baseline resize behavior of CONSTANT_DESCENT. */ boolean hasConstantDescent(int row) { return ((baselineType[row] & (1 << Component.BaselineResizeBehavior. CONSTANT_DESCENT.ordinal())) != 0); } /** {@collect.stats} * Returns true if there is a baseline for the specified row. */ boolean hasBaseline(int row) { return (hasBaseline && baselineType[row] != 0); } }
Java
/* * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.peer.MenuComponentPeer; import java.awt.event.ActionEvent; import java.io.IOException; import java.io.ObjectInputStream; import sun.awt.AppContext; import sun.awt.SunToolkit; import javax.accessibility.*; import java.security.AccessControlContext; import java.security.AccessController; /** {@collect.stats} * The abstract class <code>MenuComponent</code> is the superclass * of all menu-related components. In this respect, the class * <code>MenuComponent</code> is analogous to the abstract superclass * <code>Component</code> for AWT components. * <p> * Menu components receive and process AWT events, just as components do, * through the method <code>processEvent</code>. * * @author Arthur van Hoff * @since JDK1.0 */ public abstract class MenuComponent implements java.io.Serializable { static { /* ensure that the necessary native libraries are loaded */ Toolkit.loadLibraries(); if (!GraphicsEnvironment.isHeadless()) { initIDs(); } } transient MenuComponentPeer peer; transient MenuContainer parent; /** {@collect.stats} * The <code>AppContext</code> of the <code>MenuComponent</code>. * This is set in the constructor and never changes. */ transient AppContext appContext; /** {@collect.stats} * The menu component's font. This value can be * <code>null</code> at which point a default will be used. * This defaults to <code>null</code>. * * @serial * @see #setFont(Font) * @see #getFont() */ Font font; /** {@collect.stats} * The menu component's name, which defaults to <code>null</code>. * @serial * @see #getName() * @see #setName(String) */ private String name; /** {@collect.stats} * A variable to indicate whether a name is explicitly set. * If <code>true</code> the name will be set explicitly. * This defaults to <code>false</code>. * @serial * @see #setName(String) */ private boolean nameExplicitlySet = false; /** {@collect.stats} * Defaults to <code>false</code>. * @serial * @see #dispatchEvent(AWTEvent) */ boolean newEventsOnly = false; /* * The menu's AccessControlContext. */ private transient volatile AccessControlContext acc = AccessController.getContext(); /* * Returns the acc this menu component was constructed with. */ final AccessControlContext getAccessControlContext() { if (acc == null) { throw new SecurityException( "MenuComponent is missing AccessControlContext"); } return acc; } /* * Internal constants for serialization. */ final static String actionListenerK = Component.actionListenerK; final static String itemListenerK = Component.itemListenerK; /* * JDK 1.1 serialVersionUID */ private static final long serialVersionUID = -4536902356223894379L; /** {@collect.stats} * Creates a <code>MenuComponent</code>. * @exception HeadlessException if * <code>GraphicsEnvironment.isHeadless</code> * returns <code>true</code> * @see java.awt.GraphicsEnvironment#isHeadless */ public MenuComponent() throws HeadlessException { GraphicsEnvironment.checkHeadless(); appContext = AppContext.getAppContext(); } /** {@collect.stats} * Constructs a name for this <code>MenuComponent</code>. * Called by <code>getName</code> when the name is <code>null</code>. * @return a name for this <code>MenuComponent</code> */ String constructComponentName() { return null; // For strict compliance with prior platform versions, a MenuComponent // that doesn't set its name should return null from // getName() } /** {@collect.stats} * Gets the name of the menu component. * @return the name of the menu component * @see java.awt.MenuComponent#setName(java.lang.String) * @since JDK1.1 */ public String getName() { if (name == null && !nameExplicitlySet) { synchronized(this) { if (name == null && !nameExplicitlySet) name = constructComponentName(); } } return name; } /** {@collect.stats} * Sets the name of the component to the specified string. * @param name the name of the menu component * @see java.awt.MenuComponent#getName * @since JDK1.1 */ public void setName(String name) { synchronized(this) { this.name = name; nameExplicitlySet = true; } } /** {@collect.stats} * Returns the parent container for this menu component. * @return the menu component containing this menu component, * or <code>null</code> if this menu component * is the outermost component, the menu bar itself */ public MenuContainer getParent() { return getParent_NoClientCode(); } // NOTE: This method may be called by privileged threads. // This functionality is implemented in a package-private method // to insure that it cannot be overridden by client subclasses. // DO NOT INVOKE CLIENT CODE ON THIS THREAD! final MenuContainer getParent_NoClientCode() { return parent; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * programs should not directly manipulate peers. */ @Deprecated public MenuComponentPeer getPeer() { return peer; } /** {@collect.stats} * Gets the font used for this menu component. * @return the font used in this menu component, if there is one; * <code>null</code> otherwise * @see java.awt.MenuComponent#setFont */ public Font getFont() { Font font = this.font; if (font != null) { return font; } MenuContainer parent = this.parent; if (parent != null) { return parent.getFont(); } return null; } // NOTE: This method may be called by privileged threads. // This functionality is implemented in a package-private method // to insure that it cannot be overridden by client subclasses. // DO NOT INVOKE CLIENT CODE ON THIS THREAD! final Font getFont_NoClientCode() { Font font = this.font; if (font != null) { return font; } // The MenuContainer interface does not have getFont_NoClientCode() // and it cannot, because it must be package-private. Because of // this, we must manually cast classes that implement // MenuContainer. Object parent = this.parent; if (parent != null) { if (parent instanceof Component) { font = ((Component)parent).getFont_NoClientCode(); } else if (parent instanceof MenuComponent) { font = ((MenuComponent)parent).getFont_NoClientCode(); } } return font; } // getFont_NoClientCode() /** {@collect.stats} * Sets the font to be used for this menu component to the specified * font. This font is also used by all subcomponents of this menu * component, unless those subcomponents specify a different font. * <p> * Some platforms may not support setting of all font attributes * of a menu component; in such cases, calling <code>setFont</code> * will have no effect on the unsupported font attributes of this * menu component. Unless subcomponents of this menu component * specify a different font, this font will be used by those * subcomponents if supported by the underlying platform. * * @param f the font to be set * @see #getFont * @see Font#getAttributes * @see java.awt.font.TextAttribute */ public void setFont(Font f) { font = f; //Fixed 6312943: NullPointerException in method MenuComponent.setFont(Font) MenuComponentPeer peer = (MenuComponentPeer)this.peer; if (peer != null) { peer.setFont(f); } } /** {@collect.stats} * Removes the menu component's peer. The peer allows us to modify the * appearance of the menu component without changing the functionality of * the menu component. */ public void removeNotify() { synchronized (getTreeLock()) { MenuComponentPeer p = (MenuComponentPeer)this.peer; if (p != null) { Toolkit.getEventQueue().removeSourceEvents(this, true); this.peer = null; p.dispose(); } } } /** {@collect.stats} * Posts the specified event to the menu. * This method is part of the Java&nbsp;1.0 event system * and it is maintained only for backwards compatibility. * Its use is discouraged, and it may not be supported * in the future. * @param evt the event which is to take place * @deprecated As of JDK version 1.1, replaced by {@link * #dispatchEvent(AWTEvent) dispatchEvent}. */ @Deprecated public boolean postEvent(Event evt) { MenuContainer parent = this.parent; if (parent != null) { parent.postEvent(evt); } return false; } /** {@collect.stats} * Delivers an event to this component or one of its sub components. * @param e the event */ public final void dispatchEvent(AWTEvent e) { dispatchEventImpl(e); } void dispatchEventImpl(AWTEvent e) { EventQueue.setCurrentEventAndMostRecentTime(e); Toolkit.getDefaultToolkit().notifyAWTEventListeners(e); if (newEventsOnly || (parent != null && parent instanceof MenuComponent && ((MenuComponent)parent).newEventsOnly)) { if (eventEnabled(e)) { processEvent(e); } else if (e instanceof ActionEvent && parent != null) { e.setSource(parent); ((MenuComponent)parent).dispatchEvent(e); } } else { // backward compatibility Event olde = e.convertToOld(); if (olde != null) { postEvent(olde); } } } // REMIND: remove when filtering is done at lower level boolean eventEnabled(AWTEvent e) { return false; } /** {@collect.stats} * Processes events occurring on this menu component. * <p>Note that if the event parameter is <code>null</code> * the behavior is unspecified and may result in an * exception. * * @param e the event * @since JDK1.1 */ protected void processEvent(AWTEvent e) { } /** {@collect.stats} * Returns a string representing the state of this * <code>MenuComponent</code>. This method is intended to be used * only for debugging purposes, and the content and format of the * returned string may vary between implementations. The returned * string may be empty but may not be <code>null</code>. * * @return the parameter string of this menu component */ protected String paramString() { String thisName = getName(); return (thisName != null? thisName : ""); } /** {@collect.stats} * Returns a representation of this menu component as a string. * @return a string representation of this menu component */ public String toString() { return getClass().getName() + "[" + paramString() + "]"; } /** {@collect.stats} * Gets this component's locking object (the object that owns the thread * sychronization monitor) for AWT component-tree and layout * operations. * @return this component's locking object */ protected final Object getTreeLock() { return Component.LOCK; } /** {@collect.stats} * Reads the menu component from an object input stream. * * @param s the <code>ObjectInputStream</code> to read * @exception HeadlessException if * <code>GraphicsEnvironment.isHeadless</code> returns * <code>true</code> * @serial * @see java.awt.GraphicsEnvironment#isHeadless */ private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException, HeadlessException { GraphicsEnvironment.checkHeadless(); acc = AccessController.getContext(); s.defaultReadObject(); appContext = AppContext.getAppContext(); } /** {@collect.stats} * Initialize JNI field and method IDs. */ private static native void initIDs(); /* * --- Accessibility Support --- * * MenuComponent will contain all of the methods in interface Accessible, * though it won't actually implement the interface - that will be up * to the individual objects which extend MenuComponent. */ AccessibleContext accessibleContext = null; /** {@collect.stats} * Gets the <code>AccessibleContext</code> associated with * this <code>MenuComponent</code>. * * The method implemented by this base class returns <code>null</code>. * Classes that extend <code>MenuComponent</code> * should implement this method to return the * <code>AccessibleContext</code> associated with the subclass. * * @return the <code>AccessibleContext</code> of this * <code>MenuComponent</code> * @since 1.3 */ public AccessibleContext getAccessibleContext() { return accessibleContext; } /** {@collect.stats} * Inner class of <code>MenuComponent</code> used to provide * default support for accessibility. This class is not meant * to be used directly by application developers, but is instead * meant only to be subclassed by menu component developers. * <p> * The class used to obtain the accessible role for this object. * @since 1.3 */ protected abstract class AccessibleAWTMenuComponent extends AccessibleContext implements java.io.Serializable, AccessibleComponent, AccessibleSelection { /* * JDK 1.3 serialVersionUID */ private static final long serialVersionUID = -4269533416223798698L; /** {@collect.stats} * Although the class is abstract, this should be called by * all sub-classes. */ protected AccessibleAWTMenuComponent() { } // AccessibleContext methods // /** {@collect.stats} * Gets the <code>AccessibleSelection</code> associated with this * object which allows its <code>Accessible</code> children to be selected. * * @return <code>AccessibleSelection</code> if supported by object; * else return <code>null</code> * @see AccessibleSelection */ public AccessibleSelection getAccessibleSelection() { return this; } /** {@collect.stats} * Gets the accessible name of this object. This should almost never * return <code>java.awt.MenuComponent.getName</code>, as that * generally isn't a localized name, and doesn't have meaning for the * user. If the object is fundamentally a text object (e.g. a menu item), the * accessible name should be the text of the object (e.g. "save"). * If the object has a tooltip, the tooltip text may also be an * appropriate String to return. * * @return the localized name of the object -- can be <code>null</code> * if this object does not have a name * @see AccessibleContext#setAccessibleName */ public String getAccessibleName() { return accessibleName; } /** {@collect.stats} * Gets the accessible description of this object. This should be * a concise, localized description of what this object is - what * is its meaning to the user. If the object has a tooltip, the * tooltip text may be an appropriate string to return, assuming * it contains a concise description of the object (instead of just * the name of the object - e.g. a "Save" icon on a toolbar that * had "save" as the tooltip text shouldn't return the tooltip * text as the description, but something like "Saves the current * text document" instead). * * @return the localized description of the object -- can be * <code>null</code> if this object does not have a description * @see AccessibleContext#setAccessibleDescription */ public String getAccessibleDescription() { return accessibleDescription; } /** {@collect.stats} * Gets the role of this object. * * @return an instance of <code>AccessibleRole</code> * describing the role of the object * @see AccessibleRole */ public AccessibleRole getAccessibleRole() { return AccessibleRole.AWT_COMPONENT; // Non-specific -- overridden in subclasses } /** {@collect.stats} * Gets the state of this object. * * @return an instance of <code>AccessibleStateSet</code> * containing the current state set of the object * @see AccessibleState */ public AccessibleStateSet getAccessibleStateSet() { return MenuComponent.this.getAccessibleStateSet(); } /** {@collect.stats} * Gets the <code>Accessible</code> parent of this object. * If the parent of this object implements <code>Accessible</code>, * this method should simply return <code>getParent</code>. * * @return the <code>Accessible</code> parent of this object -- can * be <code>null</code> if this object does not have an * <code>Accessible</code> parent */ public Accessible getAccessibleParent() { if (accessibleParent != null) { return accessibleParent; } else { MenuContainer parent = MenuComponent.this.getParent(); if (parent instanceof Accessible) { return (Accessible) parent; } } return null; } /** {@collect.stats} * Gets the index of this object in its accessible parent. * * @return the index of this object in its parent; -1 if this * object does not have an accessible parent * @see #getAccessibleParent */ public int getAccessibleIndexInParent() { return MenuComponent.this.getAccessibleIndexInParent(); } /** {@collect.stats} * Returns the number of accessible children in the object. If all * of the children of this object implement <code>Accessible</code>, * then this method should return the number of children of this object. * * @return the number of accessible children in the object */ public int getAccessibleChildrenCount() { return 0; // MenuComponents don't have children } /** {@collect.stats} * Returns the nth <code>Accessible</code> child of the object. * * @param i zero-based index of child * @return the nth Accessible child of the object */ public Accessible getAccessibleChild(int i) { return null; // MenuComponents don't have children } /** {@collect.stats} * Returns the locale of this object. * * @return the locale of this object */ public java.util.Locale getLocale() { MenuContainer parent = MenuComponent.this.getParent(); if (parent instanceof Component) return ((Component)parent).getLocale(); else return java.util.Locale.getDefault(); } /** {@collect.stats} * Gets the <code>AccessibleComponent</code> associated with * this object if one exists. Otherwise return <code>null</code>. * * @return the component */ public AccessibleComponent getAccessibleComponent() { return this; } // AccessibleComponent methods // /** {@collect.stats} * Gets the background color of this object. * * @return the background color, if supported, of the object; * otherwise, <code>null</code> */ public Color getBackground() { return null; // Not supported for MenuComponents } /** {@collect.stats} * Sets the background color of this object. * (For transparency, see <code>isOpaque</code>.) * * @param c the new <code>Color</code> for the background * @see Component#isOpaque */ public void setBackground(Color c) { // Not supported for MenuComponents } /** {@collect.stats} * Gets the foreground color of this object. * * @return the foreground color, if supported, of the object; * otherwise, <code>null</code> */ public Color getForeground() { return null; // Not supported for MenuComponents } /** {@collect.stats} * Sets the foreground color of this object. * * @param c the new <code>Color</code> for the foreground */ public void setForeground(Color c) { // Not supported for MenuComponents } /** {@collect.stats} * Gets the <code>Cursor</code> of this object. * * @return the <code>Curso</code>, if supported, of the object; * otherwise, <code>null</code> */ public Cursor getCursor() { return null; // Not supported for MenuComponents } /** {@collect.stats} * Sets the <code>Cursor</code> of this object. * <p> * The method may have no visual effect if the Java platform * implementation and/or the native system do not support * changing the mouse cursor shape. * @param cursor the new <code>Cursor</code> for the object */ public void setCursor(Cursor cursor) { // Not supported for MenuComponents } /** {@collect.stats} * Gets the <code>Font</code> of this object. * * @return the <code>Font</code>,if supported, for the object; * otherwise, <code>null</code> */ public Font getFont() { return MenuComponent.this.getFont(); } /** {@collect.stats} * Sets the <code>Font</code> of this object. * * @param f the new <code>Font</code> for the object */ public void setFont(Font f) { MenuComponent.this.setFont(f); } /** {@collect.stats} * Gets the <code>FontMetrics</code> of this object. * * @param f the <code>Font</code> * @return the FontMetrics, if supported, the object; * otherwise, <code>null</code> * @see #getFont */ public FontMetrics getFontMetrics(Font f) { return null; // Not supported for MenuComponents } /** {@collect.stats} * Determines if the object is enabled. * * @return true if object is enabled; otherwise, false */ public boolean isEnabled() { return true; // Not supported for MenuComponents } /** {@collect.stats} * Sets the enabled state of the object. * * @param b if true, enables this object; otherwise, disables it */ public void setEnabled(boolean b) { // Not supported for MenuComponents } /** {@collect.stats} * Determines if the object is visible. Note: this means that the * object intends to be visible; however, it may not in fact be * showing on the screen because one of the objects that this object * is contained by is not visible. To determine if an object is * showing on the screen, use <code>isShowing</code>. * * @return true if object is visible; otherwise, false */ public boolean isVisible() { return true; // Not supported for MenuComponents } /** {@collect.stats} * Sets the visible state of the object. * * @param b if true, shows this object; otherwise, hides it */ public void setVisible(boolean b) { // Not supported for MenuComponents } /** {@collect.stats} * Determines if the object is showing. This is determined by checking * the visibility of the object and ancestors of the object. Note: * this will return true even if the object is obscured by another * (for example, it happens to be underneath a menu that was pulled * down). * * @return true if object is showing; otherwise, false */ public boolean isShowing() { return true; // Not supported for MenuComponents } /** {@collect.stats} * Checks whether the specified point is within this object's bounds, * where the point's x and y coordinates are defined to be relative to * the coordinate system of the object. * * @param p the <code>Point</code> relative to the coordinate * system of the object * @return true if object contains <code>Point</code>; otherwise false */ public boolean contains(Point p) { return false; // Not supported for MenuComponents } /** {@collect.stats} * Returns the location of the object on the screen. * * @return location of object on screen -- can be <code>null</code> * if this object is not on the screen */ public Point getLocationOnScreen() { return null; // Not supported for MenuComponents } /** {@collect.stats} * Gets the location of the object relative to the parent in the form * of a point specifying the object's top-left corner in the screen's * coordinate space. * * @return an instance of <code>Point</code> representing the * top-left corner of the object's bounds in the coordinate * space of the screen; <code>null</code> if * this object or its parent are not on the screen */ public Point getLocation() { return null; // Not supported for MenuComponents } /** {@collect.stats} * Sets the location of the object relative to the parent. */ public void setLocation(Point p) { // Not supported for MenuComponents } /** {@collect.stats} * Gets the bounds of this object in the form of a * <code>Rectangle</code> object. * The bounds specify this object's width, height, and location * relative to its parent. * * @return a rectangle indicating this component's bounds; * <code>null</code> if this object is not on the screen */ public Rectangle getBounds() { return null; // Not supported for MenuComponents } /** {@collect.stats} * Sets the bounds of this object in the form of a * <code>Rectangle</code> object. * The bounds specify this object's width, height, and location * relative to its parent. * * @param r a rectangle indicating this component's bounds */ public void setBounds(Rectangle r) { // Not supported for MenuComponents } /** {@collect.stats} * Returns the size of this object in the form of a * <code>Dimension</code> object. The height field of * the <code>Dimension</code> object contains this object's * height, and the width field of the <code>Dimension</code> * object contains this object's width. * * @return a <code>Dimension</code> object that indicates the * size of this component; <code>null</code> * if this object is not on the screen */ public Dimension getSize() { return null; // Not supported for MenuComponents } /** {@collect.stats} * Resizes this object. * * @param d - the <code>Dimension</code> specifying the * new size of the object */ public void setSize(Dimension d) { // Not supported for MenuComponents } /** {@collect.stats} * Returns the <code>Accessible</code> child, if one exists, * contained at the local coordinate <code>Point</code>. * If there is no <code>Accessible</code> child, <code>null</code> * is returned. * * @param p the point defining the top-left corner of the * <code>Accessible</code>, given in the coordinate space * of the object's parent * @return the <code>Accessible</code>, if it exists, * at the specified location; else <code>null</code> */ public Accessible getAccessibleAt(Point p) { return null; // MenuComponents don't have children } /** {@collect.stats} * Returns whether this object can accept focus or not. * * @return true if object can accept focus; otherwise false */ public boolean isFocusTraversable() { return true; // Not supported for MenuComponents } /** {@collect.stats} * Requests focus for this object. */ public void requestFocus() { // Not supported for MenuComponents } /** {@collect.stats} * Adds the specified focus listener to receive focus events from this * component. * * @param l the focus listener */ public void addFocusListener(java.awt.event.FocusListener l) { // Not supported for MenuComponents } /** {@collect.stats} * Removes the specified focus listener so it no longer receives focus * events from this component. * * @param l the focus listener */ public void removeFocusListener(java.awt.event.FocusListener l) { // Not supported for MenuComponents } // AccessibleSelection methods // /** {@collect.stats} * Returns the number of <code>Accessible</code> children currently selected. * If no children are selected, the return value will be 0. * * @return the number of items currently selected */ public int getAccessibleSelectionCount() { return 0; // To be fully implemented in a future release } /** {@collect.stats} * Returns an <code>Accessible</code> representing the specified * selected child in the object. If there isn't a selection, or there are * fewer children selected than the integer passed in, the return * value will be <code>null</code>. * <p>Note that the index represents the i-th selected child, which * is different from the i-th child. * * @param i the zero-based index of selected children * @return the i-th selected child * @see #getAccessibleSelectionCount */ public Accessible getAccessibleSelection(int i) { return null; // To be fully implemented in a future release } /** {@collect.stats} * Determines if the current child of this object is selected. * * @return true if the current child of this object is selected; * else false * @param i the zero-based index of the child in this * <code>Accessible</code> object * @see AccessibleContext#getAccessibleChild */ public boolean isAccessibleChildSelected(int i) { return false; // To be fully implemented in a future release } /** {@collect.stats} * Adds the specified <code>Accessible</code> child of the object * to the object's selection. If the object supports multiple selections, * the specified child is added to any existing selection, otherwise * it replaces any existing selection in the object. If the * specified child is already selected, this method has no effect. * * @param i the zero-based index of the child * @see AccessibleContext#getAccessibleChild */ public void addAccessibleSelection(int i) { // To be fully implemented in a future release } /** {@collect.stats} * Removes the specified child of the object from the object's * selection. If the specified item isn't currently selected, this * method has no effect. * * @param i the zero-based index of the child * @see AccessibleContext#getAccessibleChild */ public void removeAccessibleSelection(int i) { // To be fully implemented in a future release } /** {@collect.stats} * Clears the selection in the object, so that no children in the * object are selected. */ public void clearAccessibleSelection() { // To be fully implemented in a future release } /** {@collect.stats} * Causes every child of the object to be selected * if the object supports multiple selections. */ public void selectAllAccessibleSelection() { // To be fully implemented in a future release } } // inner class AccessibleAWTComponent /** {@collect.stats} * Gets the index of this object in its accessible parent. * * @return -1 if this object does not have an accessible parent; * otherwise, the index of the child in its accessible parent. */ int getAccessibleIndexInParent() { MenuContainer localParent = parent; if (!(localParent instanceof MenuComponent)) { // MenuComponents only have accessible index when inside MenuComponents return -1; } MenuComponent localParentMenu = (MenuComponent)localParent; return localParentMenu.getAccessibleChildIndex(this); } /** {@collect.stats} * Gets the index of the child within this MenuComponent. * * @param child MenuComponent whose index we are interested in. * @return -1 if this object doesn't contain the child, * otherwise, index of the child. */ int getAccessibleChildIndex(MenuComponent child) { return -1; // Overridden in subclasses. } /** {@collect.stats} * Gets the state of this object. * * @return an instance of <code>AccessibleStateSet</code> * containing the current state set of the object * @see AccessibleState */ AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet states = new AccessibleStateSet(); return states; } }
Java
/* * Copyright (c) 2006, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.ColorModel; /** {@collect.stats} * The {@code LinearGradientPaint} class provides a way to fill * a {@link java.awt.Shape} with a linear color gradient pattern. The user * may specify two or more gradient colors, and this paint will provide an * interpolation between each color. The user also specifies start and end * points which define where in user space the color gradient should begin * and end. * <p> * The user must provide an array of floats specifying how to distribute the * colors along the gradient. These values should range from 0.0 to 1.0 and * act like keyframes along the gradient (they mark where the gradient should * be exactly a particular color). * <p> * In the event that the user does not set the first keyframe value equal * to 0 and/or the last keyframe value equal to 1, keyframes will be created * at these positions and the first and last colors will be replicated there. * So, if a user specifies the following arrays to construct a gradient:<br> * <pre> * {Color.BLUE, Color.RED}, {.3f, .7f} * </pre> * this will be converted to a gradient with the following keyframes:<br> * <pre> * {Color.BLUE, Color.BLUE, Color.RED, Color.RED}, {0f, .3f, .7f, 1f} * </pre> * * <p> * The user may also select what action the {@code LinearGradientPaint} * should take when filling color outside the start and end points. * If no cycle method is specified, {@code NO_CYCLE} will be chosen by * default, which means the endpoint colors will be used to fill the * remaining area. * <p> * The colorSpace parameter allows the user to specify in which colorspace * the interpolation should be performed, default sRGB or linearized RGB. * * <p> * The following code demonstrates typical usage of * {@code LinearGradientPaint}: * <p> * <pre> * Point2D start = new Point2D.Float(0, 0); * Point2D end = new Point2D.Float(50, 50); * float[] dist = {0.0f, 0.2f, 1.0f}; * Color[] colors = {Color.RED, Color.WHITE, Color.BLUE}; * LinearGradientPaint p = * new LinearGradientPaint(start, end, dist, colors); * </pre> * <p> * This code will create a {@code LinearGradientPaint} which interpolates * between red and white for the first 20% of the gradient and between white * and blue for the remaining 80%. * * <p> * This image demonstrates the example code above for each * of the three cycle methods: * <p> * <center> * <img src = "doc-files/LinearGradientPaint.png"> * </center> * * @see java.awt.Paint * @see java.awt.Graphics2D#setPaint * @author Nicholas Talian, Vincent Hardy, Jim Graham, Jerry Evans * @since 1.6 */ public final class LinearGradientPaint extends MultipleGradientPaint { /** {@collect.stats} Gradient start and end points. */ private final Point2D start, end; /** {@collect.stats} * Constructs a {@code LinearGradientPaint} with a default * {@code NO_CYCLE} repeating method and {@code SRGB} color space. * * @param startX the X coordinate of the gradient axis start point * in user space * @param startY the Y coordinate of the gradient axis start point * in user space * @param endX the X coordinate of the gradient axis end point * in user space * @param endY the Y coordinate of the gradient axis end point * in user space * @param fractions numbers ranging from 0.0 to 1.0 specifying the * distribution of colors along the gradient * @param colors array of colors corresponding to each fractional value * * @throws NullPointerException * if {@code fractions} array is null, * or {@code colors} array is null, * @throws IllegalArgumentException * if start and end points are the same points, * or {@code fractions.length != colors.length}, * or {@code colors} is less than 2 in size, * or a {@code fractions} value is less than 0.0 or greater than 1.0, * or the {@code fractions} are not provided in strictly increasing order */ public LinearGradientPaint(float startX, float startY, float endX, float endY, float[] fractions, Color[] colors) { this(new Point2D.Float(startX, startY), new Point2D.Float(endX, endY), fractions, colors, CycleMethod.NO_CYCLE); } /** {@collect.stats} * Constructs a {@code LinearGradientPaint} with a default {@code SRGB} * color space. * * @param startX the X coordinate of the gradient axis start point * in user space * @param startY the Y coordinate of the gradient axis start point * in user space * @param endX the X coordinate of the gradient axis end point * in user space * @param endY the Y coordinate of the gradient axis end point * in user space * @param fractions numbers ranging from 0.0 to 1.0 specifying the * distribution of colors along the gradient * @param colors array of colors corresponding to each fractional value * @param cycleMethod either {@code NO_CYCLE}, {@code REFLECT}, * or {@code REPEAT} * * @throws NullPointerException * if {@code fractions} array is null, * or {@code colors} array is null, * or {@code cycleMethod} is null * @throws IllegalArgumentException * if start and end points are the same points, * or {@code fractions.length != colors.length}, * or {@code colors} is less than 2 in size, * or a {@code fractions} value is less than 0.0 or greater than 1.0, * or the {@code fractions} are not provided in strictly increasing order */ public LinearGradientPaint(float startX, float startY, float endX, float endY, float[] fractions, Color[] colors, CycleMethod cycleMethod) { this(new Point2D.Float(startX, startY), new Point2D.Float(endX, endY), fractions, colors, cycleMethod); } /** {@collect.stats} * Constructs a {@code LinearGradientPaint} with a default * {@code NO_CYCLE} repeating method and {@code SRGB} color space. * * @param start the gradient axis start {@code Point2D} in user space * @param end the gradient axis end {@code Point2D} in user space * @param fractions numbers ranging from 0.0 to 1.0 specifying the * distribution of colors along the gradient * @param colors array of colors corresponding to each fractional value * * @throws NullPointerException * if one of the points is null, * or {@code fractions} array is null, * or {@code colors} array is null * @throws IllegalArgumentException * if start and end points are the same points, * or {@code fractions.length != colors.length}, * or {@code colors} is less than 2 in size, * or a {@code fractions} value is less than 0.0 or greater than 1.0, * or the {@code fractions} are not provided in strictly increasing order */ public LinearGradientPaint(Point2D start, Point2D end, float[] fractions, Color[] colors) { this(start, end, fractions, colors, CycleMethod.NO_CYCLE); } /** {@collect.stats} * Constructs a {@code LinearGradientPaint} with a default {@code SRGB} * color space. * * @param start the gradient axis start {@code Point2D} in user space * @param end the gradient axis end {@code Point2D} in user space * @param fractions numbers ranging from 0.0 to 1.0 specifying the * distribution of colors along the gradient * @param colors array of colors corresponding to each fractional value * @param cycleMethod either {@code NO_CYCLE}, {@code REFLECT}, * or {@code REPEAT} * * @throws NullPointerException * if one of the points is null, * or {@code fractions} array is null, * or {@code colors} array is null, * or {@code cycleMethod} is null * @throws IllegalArgumentException * if start and end points are the same points, * or {@code fractions.length != colors.length}, * or {@code colors} is less than 2 in size, * or a {@code fractions} value is less than 0.0 or greater than 1.0, * or the {@code fractions} are not provided in strictly increasing order */ public LinearGradientPaint(Point2D start, Point2D end, float[] fractions, Color[] colors, CycleMethod cycleMethod) { this(start, end, fractions, colors, cycleMethod, ColorSpaceType.SRGB, new AffineTransform()); } /** {@collect.stats} * Constructs a {@code LinearGradientPaint}. * * @param start the gradient axis start {@code Point2D} in user space * @param end the gradient axis end {@code Point2D} in user space * @param fractions numbers ranging from 0.0 to 1.0 specifying the * distribution of colors along the gradient * @param colors array of colors corresponding to each fractional value * @param cycleMethod either {@code NO_CYCLE}, {@code REFLECT}, * or {@code REPEAT} * @param colorSpace which color space to use for interpolation, * either {@code SRGB} or {@code LINEAR_RGB} * @param gradientTransform transform to apply to the gradient * * @throws NullPointerException * if one of the points is null, * or {@code fractions} array is null, * or {@code colors} array is null, * or {@code cycleMethod} is null, * or {@code colorSpace} is null, * or {@code gradientTransform} is null * @throws IllegalArgumentException * if start and end points are the same points, * or {@code fractions.length != colors.length}, * or {@code colors} is less than 2 in size, * or a {@code fractions} value is less than 0.0 or greater than 1.0, * or the {@code fractions} are not provided in strictly increasing order */ public LinearGradientPaint(Point2D start, Point2D end, float[] fractions, Color[] colors, CycleMethod cycleMethod, ColorSpaceType colorSpace, AffineTransform gradientTransform) { super(fractions, colors, cycleMethod, colorSpace, gradientTransform); // check input parameters if (start == null || end == null) { throw new NullPointerException("Start and end points must be" + "non-null"); } if (start.equals(end)) { throw new IllegalArgumentException("Start point cannot equal" + "endpoint"); } // copy the points... this.start = new Point2D.Double(start.getX(), start.getY()); this.end = new Point2D.Double(end.getX(), end.getY()); } /** {@collect.stats} * Creates and returns a {@link PaintContext} used to * generate a linear color gradient pattern. * See the {@link Paint#createContext specification} of the * method in the {@link Paint} interface for information * on null parameter handling. * * @param cm the preferred {@link ColorModel} which represents the most convenient * format for the caller to receive the pixel data, or {@code null} * if there is no preference. * @param deviceBounds the device space bounding box * of the graphics primitive being rendered. * @param userBounds the user space bounding box * of the graphics primitive being rendered. * @param transform the {@link AffineTransform} from user * space into device space. * @param hints the set of hints that the context object can use to * choose between rendering alternatives. * @return the {@code PaintContext} for * generating color patterns. * @see Paint * @see PaintContext * @see ColorModel * @see Rectangle * @see Rectangle2D * @see AffineTransform * @see RenderingHints */ public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform transform, RenderingHints hints) { // avoid modifying the user's transform... transform = new AffineTransform(transform); // incorporate the gradient transform transform.concatenate(gradientTransform); if ((fractions.length == 2) && (cycleMethod != CycleMethod.REPEAT) && (colorSpace == ColorSpaceType.SRGB)) { // faster to use the basic GradientPaintContext for this // common case boolean cyclic = (cycleMethod != CycleMethod.NO_CYCLE); return new GradientPaintContext(cm, start, end, transform, colors[0], colors[1], cyclic); } else { return new LinearGradientPaintContext(this, cm, deviceBounds, userBounds, transform, hints, start, end, fractions, colors, cycleMethod, colorSpace); } } /** {@collect.stats} * Returns a copy of the start point of the gradient axis. * * @return a {@code Point2D} object that is a copy of the point * that anchors the first color of this {@code LinearGradientPaint} */ public Point2D getStartPoint() { return new Point2D.Double(start.getX(), start.getY()); } /** {@collect.stats} * Returns a copy of the end point of the gradient axis. * * @return a {@code Point2D} object that is a copy of the point * that anchors the last color of this {@code LinearGradientPaint} */ public Point2D getEndPoint() { return new Point2D.Double(end.getX(), end.getY()); } }
Java
/* * Copyright (c) 1995, 1997, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; /** {@collect.stats} * Signals that an Absract Window Toolkit exception has occurred. * * @author Arthur van Hoff */ public class AWTException extends Exception { /* * JDK 1.1 serialVersionUID */ private static final long serialVersionUID = -1900414231151323879L; /** {@collect.stats} * Constructs an instance of <code>AWTException</code> with the * specified detail message. A detail message is an * instance of <code>String</code> that describes this particular * exception. * @param msg the detail message * @since JDK1.0 */ public AWTException(String msg) { super(msg); } }
Java
/* * Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.io.ObjectStreamException; /** {@collect.stats} * A class to encapsulate symbolic colors representing the color of * native GUI objects on a system. For systems which support the dynamic * update of the system colors (when the user changes the colors) * the actual RGB values of these symbolic colors will also change * dynamically. In order to compare the "current" RGB value of a * <code>SystemColor</code> object with a non-symbolic Color object, * <code>getRGB</code> should be used rather than <code>equals</code>. * <p> * Note that the way in which these system colors are applied to GUI objects * may vary slightly from platform to platform since GUI objects may be * rendered differently on each platform. * <p> * System color values may also be available through the <code>getDesktopProperty</code> * method on <code>java.awt.Toolkit</code>. * * @see Toolkit#getDesktopProperty * * @author Carl Quinn * @author Amy Fowler */ public final class SystemColor extends Color implements java.io.Serializable { /** {@collect.stats} * The array index for the * {@link #desktop} system color. * @see SystemColor#desktop */ public final static int DESKTOP = 0; /** {@collect.stats} * The array index for the * {@link #activeCaption} system color. * @see SystemColor#activeCaption */ public final static int ACTIVE_CAPTION = 1; /** {@collect.stats} * The array index for the * {@link #activeCaptionText} system color. * @see SystemColor#activeCaptionText */ public final static int ACTIVE_CAPTION_TEXT = 2; /** {@collect.stats} * The array index for the * {@link #activeCaptionBorder} system color. * @see SystemColor#activeCaptionBorder */ public final static int ACTIVE_CAPTION_BORDER = 3; /** {@collect.stats} * The array index for the * {@link #inactiveCaption} system color. * @see SystemColor#inactiveCaption */ public final static int INACTIVE_CAPTION = 4; /** {@collect.stats} * The array index for the * {@link #inactiveCaptionText} system color. * @see SystemColor#inactiveCaptionText */ public final static int INACTIVE_CAPTION_TEXT = 5; /** {@collect.stats} * The array index for the * {@link #inactiveCaptionBorder} system color. * @see SystemColor#inactiveCaptionBorder */ public final static int INACTIVE_CAPTION_BORDER = 6; /** {@collect.stats} * The array index for the * {@link #window} system color. * @see SystemColor#window */ public final static int WINDOW = 7; /** {@collect.stats} * The array index for the * {@link #windowBorder} system color. * @see SystemColor#windowBorder */ public final static int WINDOW_BORDER = 8; /** {@collect.stats} * The array index for the * {@link #windowText} system color. * @see SystemColor#windowText */ public final static int WINDOW_TEXT = 9; /** {@collect.stats} * The array index for the * {@link #menu} system color. * @see SystemColor#menu */ public final static int MENU = 10; /** {@collect.stats} * The array index for the * {@link #menuText} system color. * @see SystemColor#menuText */ public final static int MENU_TEXT = 11; /** {@collect.stats} * The array index for the * {@link #text} system color. * @see SystemColor#text */ public final static int TEXT = 12; /** {@collect.stats} * The array index for the * {@link #textText} system color. * @see SystemColor#textText */ public final static int TEXT_TEXT = 13; /** {@collect.stats} * The array index for the * {@link #textHighlight} system color. * @see SystemColor#textHighlight */ public final static int TEXT_HIGHLIGHT = 14; /** {@collect.stats} * The array index for the * {@link #textHighlightText} system color. * @see SystemColor#textHighlightText */ public final static int TEXT_HIGHLIGHT_TEXT = 15; /** {@collect.stats} * The array index for the * {@link #textInactiveText} system color. * @see SystemColor#textInactiveText */ public final static int TEXT_INACTIVE_TEXT = 16; /** {@collect.stats} * The array index for the * {@link #control} system color. * @see SystemColor#control */ public final static int CONTROL = 17; /** {@collect.stats} * The array index for the * {@link #controlText} system color. * @see SystemColor#controlText */ public final static int CONTROL_TEXT = 18; /** {@collect.stats} * The array index for the * {@link #controlHighlight} system color. * @see SystemColor#controlHighlight */ public final static int CONTROL_HIGHLIGHT = 19; /** {@collect.stats} * The array index for the * {@link #controlLtHighlight} system color. * @see SystemColor#controlLtHighlight */ public final static int CONTROL_LT_HIGHLIGHT = 20; /** {@collect.stats} * The array index for the * {@link #controlShadow} system color. * @see SystemColor#controlShadow */ public final static int CONTROL_SHADOW = 21; /** {@collect.stats} * The array index for the * {@link #controlDkShadow} system color. * @see SystemColor#controlDkShadow */ public final static int CONTROL_DK_SHADOW = 22; /** {@collect.stats} * The array index for the * {@link #scrollbar} system color. * @see SystemColor#scrollbar */ public final static int SCROLLBAR = 23; /** {@collect.stats} * The array index for the * {@link #info} system color. * @see SystemColor#info */ public final static int INFO = 24; /** {@collect.stats} * The array index for the * {@link #infoText} system color. * @see SystemColor#infoText */ public final static int INFO_TEXT = 25; /** {@collect.stats} * The number of system colors in the array. */ public final static int NUM_COLORS = 26; /** {@collect.stats} ****************************************************************************************/ /* * System colors with default initial values, overwritten by toolkit if * system values differ and are available. * Should put array initialization above first field that is using * SystemColor constructor to initialize. */ private static int[] systemColors = { 0xFF005C5C, // desktop = new Color(0,92,92); 0xFF000080, // activeCaption = new Color(0,0,128); 0xFFFFFFFF, // activeCaptionText = Color.white; 0xFFC0C0C0, // activeCaptionBorder = Color.lightGray; 0xFF808080, // inactiveCaption = Color.gray; 0xFFC0C0C0, // inactiveCaptionText = Color.lightGray; 0xFFC0C0C0, // inactiveCaptionBorder = Color.lightGray; 0xFFFFFFFF, // window = Color.white; 0xFF000000, // windowBorder = Color.black; 0xFF000000, // windowText = Color.black; 0xFFC0C0C0, // menu = Color.lightGray; 0xFF000000, // menuText = Color.black; 0xFFC0C0C0, // text = Color.lightGray; 0xFF000000, // textText = Color.black; 0xFF000080, // textHighlight = new Color(0,0,128); 0xFFFFFFFF, // textHighlightText = Color.white; 0xFF808080, // textInactiveText = Color.gray; 0xFFC0C0C0, // control = Color.lightGray; 0xFF000000, // controlText = Color.black; 0xFFFFFFFF, // controlHighlight = Color.white; 0xFFE0E0E0, // controlLtHighlight = new Color(224,224,224); 0xFF808080, // controlShadow = Color.gray; 0xFF000000, // controlDkShadow = Color.black; 0xFFE0E0E0, // scrollbar = new Color(224,224,224); 0xFFE0E000, // info = new Color(224,224,0); 0xFF000000, // infoText = Color.black; }; /** {@collect.stats} * The color rendered for the background of the desktop. */ public final static SystemColor desktop = new SystemColor((byte)DESKTOP); /** {@collect.stats} * The color rendered for the window-title background of the currently active window. */ public final static SystemColor activeCaption = new SystemColor((byte)ACTIVE_CAPTION); /** {@collect.stats} * The color rendered for the window-title text of the currently active window. */ public final static SystemColor activeCaptionText = new SystemColor((byte)ACTIVE_CAPTION_TEXT); /** {@collect.stats} * The color rendered for the border around the currently active window. */ public final static SystemColor activeCaptionBorder = new SystemColor((byte)ACTIVE_CAPTION_BORDER); /** {@collect.stats} * The color rendered for the window-title background of inactive windows. */ public final static SystemColor inactiveCaption = new SystemColor((byte)INACTIVE_CAPTION); /** {@collect.stats} * The color rendered for the window-title text of inactive windows. */ public final static SystemColor inactiveCaptionText = new SystemColor((byte)INACTIVE_CAPTION_TEXT); /** {@collect.stats} * The color rendered for the border around inactive windows. */ public final static SystemColor inactiveCaptionBorder = new SystemColor((byte)INACTIVE_CAPTION_BORDER); /** {@collect.stats} * The color rendered for the background of interior regions inside windows. */ public final static SystemColor window = new SystemColor((byte)WINDOW); /** {@collect.stats} * The color rendered for the border around interior regions inside windows. */ public final static SystemColor windowBorder = new SystemColor((byte)WINDOW_BORDER); /** {@collect.stats} * The color rendered for text of interior regions inside windows. */ public final static SystemColor windowText = new SystemColor((byte)WINDOW_TEXT); /** {@collect.stats} * The color rendered for the background of menus. */ public final static SystemColor menu = new SystemColor((byte)MENU); /** {@collect.stats} * The color rendered for the text of menus. */ public final static SystemColor menuText = new SystemColor((byte)MENU_TEXT); /** {@collect.stats} * The color rendered for the background of text control objects, such as * textfields and comboboxes. */ public final static SystemColor text = new SystemColor((byte)TEXT); /** {@collect.stats} * The color rendered for the text of text control objects, such as textfields * and comboboxes. */ public final static SystemColor textText = new SystemColor((byte)TEXT_TEXT); /** {@collect.stats} * The color rendered for the background of selected items, such as in menus, * comboboxes, and text. */ public final static SystemColor textHighlight = new SystemColor((byte)TEXT_HIGHLIGHT); /** {@collect.stats} * The color rendered for the text of selected items, such as in menus, comboboxes, * and text. */ public final static SystemColor textHighlightText = new SystemColor((byte)TEXT_HIGHLIGHT_TEXT); /** {@collect.stats} * The color rendered for the text of inactive items, such as in menus. */ public final static SystemColor textInactiveText = new SystemColor((byte)TEXT_INACTIVE_TEXT); /** {@collect.stats} * The color rendered for the background of control panels and control objects, * such as pushbuttons. */ public final static SystemColor control = new SystemColor((byte)CONTROL); /** {@collect.stats} * The color rendered for the text of control panels and control objects, * such as pushbuttons. */ public final static SystemColor controlText = new SystemColor((byte)CONTROL_TEXT); /** {@collect.stats} * The color rendered for light areas of 3D control objects, such as pushbuttons. * This color is typically derived from the <code>control</code> background color * to provide a 3D effect. */ public final static SystemColor controlHighlight = new SystemColor((byte)CONTROL_HIGHLIGHT); /** {@collect.stats} * The color rendered for highlight areas of 3D control objects, such as pushbuttons. * This color is typically derived from the <code>control</code> background color * to provide a 3D effect. */ public final static SystemColor controlLtHighlight = new SystemColor((byte)CONTROL_LT_HIGHLIGHT); /** {@collect.stats} * The color rendered for shadow areas of 3D control objects, such as pushbuttons. * This color is typically derived from the <code>control</code> background color * to provide a 3D effect. */ public final static SystemColor controlShadow = new SystemColor((byte)CONTROL_SHADOW); /** {@collect.stats} * The color rendered for dark shadow areas on 3D control objects, such as pushbuttons. * This color is typically derived from the <code>control</code> background color * to provide a 3D effect. */ public final static SystemColor controlDkShadow = new SystemColor((byte)CONTROL_DK_SHADOW); /** {@collect.stats} * The color rendered for the background of scrollbars. */ public final static SystemColor scrollbar = new SystemColor((byte)SCROLLBAR); /** {@collect.stats} * The color rendered for the background of tooltips or spot help. */ public final static SystemColor info = new SystemColor((byte)INFO); /** {@collect.stats} * The color rendered for the text of tooltips or spot help. */ public final static SystemColor infoText = new SystemColor((byte)INFO_TEXT); /* * JDK 1.1 serialVersionUID. */ private static final long serialVersionUID = 4503142729533789064L; /* * An index into either array of SystemColor objects or values. */ private transient int index; private static SystemColor systemColorObjects [] = { SystemColor.desktop, SystemColor.activeCaption, SystemColor.activeCaptionText, SystemColor.activeCaptionBorder, SystemColor.inactiveCaption, SystemColor.inactiveCaptionText, SystemColor.inactiveCaptionBorder, SystemColor.window, SystemColor.windowBorder, SystemColor.windowText, SystemColor.menu, SystemColor.menuText, SystemColor.text, SystemColor.textText, SystemColor.textHighlight, SystemColor.textHighlightText, SystemColor.textInactiveText, SystemColor.control, SystemColor.controlText, SystemColor.controlHighlight, SystemColor.controlLtHighlight, SystemColor.controlShadow, SystemColor.controlDkShadow, SystemColor.scrollbar, SystemColor.info, SystemColor.infoText }; static { updateSystemColors(); } /** {@collect.stats} * Called from <init> & toolkit to update the above systemColors cache. */ private static void updateSystemColors() { if (!GraphicsEnvironment.isHeadless()) { Toolkit.getDefaultToolkit().loadSystemColors(systemColors); } for (int i = 0; i < systemColors.length; i++) { systemColorObjects[i].value = systemColors[i]; } } /** {@collect.stats} * Creates a symbolic color that represents an indexed entry into system * color cache. Used by above static system colors. */ private SystemColor(byte index) { super(systemColors[index]); this.index = index; } /** {@collect.stats} * Returns a string representation of this <code>Color</code>'s values. * This method is intended to be used only for debugging purposes, * and the content and format of the returned string may vary between * implementations. * The returned string may be empty but may not be <code>null</code>. * * @return a string representation of this <code>Color</code> */ public String toString() { return getClass().getName() + "[i=" + (index) + "]"; } /** {@collect.stats} * The design of the {@code SystemColor} class assumes that * the {@code SystemColor} object instances stored in the * static final fields above are the only instances that can * be used by developers. * This method helps maintain those limits on instantiation * by using the index stored in the value field of the * serialized form of the object to replace the serialized * object with the equivalent static object constant field * of {@code SystemColor}. * See the {@link #writeReplace} method for more information * on the serialized form of these objects. * @return one of the {@code SystemColor} static object * fields that refers to the same system color. */ private Object readResolve() { // The instances of SystemColor are tightly controlled and // only the canonical instances appearing above as static // constants are allowed. The serial form of SystemColor // objects stores the color index as the value. Here we // map that index back into the canonical instance. return systemColorObjects[value]; } /** {@collect.stats} * Returns a specialized version of the {@code SystemColor} * object for writing to the serialized stream. * @serialData * The value field of a serialized {@code SystemColor} object * contains the array index of the system color instead of the * rgb data for the system color. * This index is used by the {@link #readResolve} method to * resolve the deserialized objects back to the original * static constant versions to ensure unique instances of * each {@code SystemColor} object. * @return a proxy {@code SystemColor} object with its value * replaced by the corresponding system color index. */ private Object writeReplace() throws ObjectStreamException { // we put an array index in the SystemColor.value while serialize // to keep compatibility. SystemColor color = new SystemColor((byte)index); color.value = index; return color; } }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import sun.awt.image.IntegerComponentRaster; import java.util.Arrays; class ColorPaintContext implements PaintContext { int color; WritableRaster savedTile; protected ColorPaintContext(int color, ColorModel cm) { this.color = color; } public void dispose() { } /* * Returns the RGB value representing the color in the default sRGB * {@link ColorModel}. * (Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are * blue). * @return the RGB value of the color in the default sRGB * <code>ColorModel</code>. * @see java.awt.image.ColorModel#getRGBdefault * @see #getRed * @see #getGreen * @see #getBlue */ int getRGB() { return color; } public ColorModel getColorModel() { return ColorModel.getRGBdefault(); } public synchronized Raster getRaster(int x, int y, int w, int h) { WritableRaster t = savedTile; if (t == null || w > t.getWidth() || h > t.getHeight()) { t = getColorModel().createCompatibleWritableRaster(w, h); IntegerComponentRaster icr = (IntegerComponentRaster) t; Arrays.fill(icr.getDataStorage(), color); // Note - markDirty is probably unnecessary since icr is brand new icr.markDirty(); if (w <= 64 && h <= 64) { savedTile = t; } } return t; } }
Java
/* * Copyright (c) 1995, 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.event.*; import java.io.*; /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * <code>Event</code> is a platform-independent class that * encapsulates events from the platform's Graphical User * Interface in the Java&nbsp;1.0 event model. In Java&nbsp;1.1 * and later versions, the <code>Event</code> class is maintained * only for backwards compatibilty. The information in this * class description is provided to assist programmers in * converting Java&nbsp;1.0 programs to the new event model. * <p> * In the Java&nbsp;1.0 event model, an event contains an * {@link Event#id} field * that indicates what type of event it is and which other * <code>Event</code> variables are relevant for the event. * <p> * For keyboard events, {@link Event#key} * contains a value indicating which key was activated, and * {@link Event#modifiers} contains the * modifiers for that event. For the KEY_PRESS and KEY_RELEASE * event ids, the value of <code>key</code> is the unicode * character code for the key. For KEY_ACTION and * KEY_ACTION_RELEASE, the value of <code>key</code> is * one of the defined action-key identifiers in the * <code>Event</code> class (<code>PGUP</code>, * <code>PGDN</code>, <code>F1</code>, <code>F2</code>, etc). * * @author Sami Shaio * @since JDK1.0 */ public class Event implements java.io.Serializable { private transient long data; /* Modifier constants */ /** {@collect.stats} * This flag indicates that the Shift key was down when the event * occurred. */ public static final int SHIFT_MASK = 1 << 0; /** {@collect.stats} * This flag indicates that the Control key was down when the event * occurred. */ public static final int CTRL_MASK = 1 << 1; /** {@collect.stats} * This flag indicates that the Meta key was down when the event * occurred. For mouse events, this flag indicates that the right * button was pressed or released. */ public static final int META_MASK = 1 << 2; /** {@collect.stats} * This flag indicates that the Alt key was down when * the event occurred. For mouse events, this flag indicates that the * middle mouse button was pressed or released. */ public static final int ALT_MASK = 1 << 3; /* Action keys */ /** {@collect.stats} * The Home key, a non-ASCII action key. */ public static final int HOME = 1000; /** {@collect.stats} * The End key, a non-ASCII action key. */ public static final int END = 1001; /** {@collect.stats} * The Page Up key, a non-ASCII action key. */ public static final int PGUP = 1002; /** {@collect.stats} * The Page Down key, a non-ASCII action key. */ public static final int PGDN = 1003; /** {@collect.stats} * The Up Arrow key, a non-ASCII action key. */ public static final int UP = 1004; /** {@collect.stats} * The Down Arrow key, a non-ASCII action key. */ public static final int DOWN = 1005; /** {@collect.stats} * The Left Arrow key, a non-ASCII action key. */ public static final int LEFT = 1006; /** {@collect.stats} * The Right Arrow key, a non-ASCII action key. */ public static final int RIGHT = 1007; /** {@collect.stats} * The F1 function key, a non-ASCII action key. */ public static final int F1 = 1008; /** {@collect.stats} * The F2 function key, a non-ASCII action key. */ public static final int F2 = 1009; /** {@collect.stats} * The F3 function key, a non-ASCII action key. */ public static final int F3 = 1010; /** {@collect.stats} * The F4 function key, a non-ASCII action key. */ public static final int F4 = 1011; /** {@collect.stats} * The F5 function key, a non-ASCII action key. */ public static final int F5 = 1012; /** {@collect.stats} * The F6 function key, a non-ASCII action key. */ public static final int F6 = 1013; /** {@collect.stats} * The F7 function key, a non-ASCII action key. */ public static final int F7 = 1014; /** {@collect.stats} * The F8 function key, a non-ASCII action key. */ public static final int F8 = 1015; /** {@collect.stats} * The F9 function key, a non-ASCII action key. */ public static final int F9 = 1016; /** {@collect.stats} * The F10 function key, a non-ASCII action key. */ public static final int F10 = 1017; /** {@collect.stats} * The F11 function key, a non-ASCII action key. */ public static final int F11 = 1018; /** {@collect.stats} * The F12 function key, a non-ASCII action key. */ public static final int F12 = 1019; /** {@collect.stats} * The Print Screen key, a non-ASCII action key. */ public static final int PRINT_SCREEN = 1020; /** {@collect.stats} * The Scroll Lock key, a non-ASCII action key. */ public static final int SCROLL_LOCK = 1021; /** {@collect.stats} * The Caps Lock key, a non-ASCII action key. */ public static final int CAPS_LOCK = 1022; /** {@collect.stats} * The Num Lock key, a non-ASCII action key. */ public static final int NUM_LOCK = 1023; /** {@collect.stats} * The Pause key, a non-ASCII action key. */ public static final int PAUSE = 1024; /** {@collect.stats} * The Insert key, a non-ASCII action key. */ public static final int INSERT = 1025; /* Non-action keys */ /** {@collect.stats} * The Enter key. */ public static final int ENTER = '\n'; /** {@collect.stats} * The BackSpace key. */ public static final int BACK_SPACE = '\b'; /** {@collect.stats} * The Tab key. */ public static final int TAB = '\t'; /** {@collect.stats} * The Escape key. */ public static final int ESCAPE = 27; /** {@collect.stats} * The Delete key. */ public static final int DELETE = 127; /* Base for all window events. */ private static final int WINDOW_EVENT = 200; /** {@collect.stats} * The user has asked the window manager to kill the window. */ public static final int WINDOW_DESTROY = 1 + WINDOW_EVENT; /** {@collect.stats} * The user has asked the window manager to expose the window. */ public static final int WINDOW_EXPOSE = 2 + WINDOW_EVENT; /** {@collect.stats} * The user has asked the window manager to iconify the window. */ public static final int WINDOW_ICONIFY = 3 + WINDOW_EVENT; /** {@collect.stats} * The user has asked the window manager to de-iconify the window. */ public static final int WINDOW_DEICONIFY = 4 + WINDOW_EVENT; /** {@collect.stats} * The user has asked the window manager to move the window. */ public static final int WINDOW_MOVED = 5 + WINDOW_EVENT; /* Base for all keyboard events. */ private static final int KEY_EVENT = 400; /** {@collect.stats} * The user has pressed a normal key. */ public static final int KEY_PRESS = 1 + KEY_EVENT; /** {@collect.stats} * The user has released a normal key. */ public static final int KEY_RELEASE = 2 + KEY_EVENT; /** {@collect.stats} * The user has pressed a non-ASCII <em>action</em> key. * The <code>key</code> field contains a value that indicates * that the event occurred on one of the action keys, which * comprise the 12 function keys, the arrow (cursor) keys, * Page Up, Page Down, Home, End, Print Screen, Scroll Lock, * Caps Lock, Num Lock, Pause, and Insert. */ public static final int KEY_ACTION = 3 + KEY_EVENT; /** {@collect.stats} * The user has released a non-ASCII <em>action</em> key. * The <code>key</code> field contains a value that indicates * that the event occurred on one of the action keys, which * comprise the 12 function keys, the arrow (cursor) keys, * Page Up, Page Down, Home, End, Print Screen, Scroll Lock, * Caps Lock, Num Lock, Pause, and Insert. */ public static final int KEY_ACTION_RELEASE = 4 + KEY_EVENT; /* Base for all mouse events. */ private static final int MOUSE_EVENT = 500; /** {@collect.stats} * The user has pressed the mouse button. The <code>ALT_MASK</code> * flag indicates that the middle button has been pressed. * The <code>META_MASK</code>flag indicates that the * right button has been pressed. * @see java.awt.Event#ALT_MASK * @see java.awt.Event#META_MASK */ public static final int MOUSE_DOWN = 1 + MOUSE_EVENT; /** {@collect.stats} * The user has released the mouse button. The <code>ALT_MASK</code> * flag indicates that the middle button has been released. * The <code>META_MASK</code>flag indicates that the * right button has been released. * @see java.awt.Event#ALT_MASK * @see java.awt.Event#META_MASK */ public static final int MOUSE_UP = 2 + MOUSE_EVENT; /** {@collect.stats} * The mouse has moved with no button pressed. */ public static final int MOUSE_MOVE = 3 + MOUSE_EVENT; /** {@collect.stats} * The mouse has entered a component. */ public static final int MOUSE_ENTER = 4 + MOUSE_EVENT; /** {@collect.stats} * The mouse has exited a component. */ public static final int MOUSE_EXIT = 5 + MOUSE_EVENT; /** {@collect.stats} * The user has moved the mouse with a button pressed. The * <code>ALT_MASK</code> flag indicates that the middle * button is being pressed. The <code>META_MASK</code> flag indicates * that the right button is being pressed. * @see java.awt.Event#ALT_MASK * @see java.awt.Event#META_MASK */ public static final int MOUSE_DRAG = 6 + MOUSE_EVENT; /* Scrolling events */ private static final int SCROLL_EVENT = 600; /** {@collect.stats} * The user has activated the <em>line up</em> * area of a scroll bar. */ public static final int SCROLL_LINE_UP = 1 + SCROLL_EVENT; /** {@collect.stats} * The user has activated the <em>line down</em> * area of a scroll bar. */ public static final int SCROLL_LINE_DOWN = 2 + SCROLL_EVENT; /** {@collect.stats} * The user has activated the <em>page up</em> * area of a scroll bar. */ public static final int SCROLL_PAGE_UP = 3 + SCROLL_EVENT; /** {@collect.stats} * The user has activated the <em>page down</em> * area of a scroll bar. */ public static final int SCROLL_PAGE_DOWN = 4 + SCROLL_EVENT; /** {@collect.stats} * The user has moved the bubble (thumb) in a scroll bar, * moving to an "absolute" position, rather than to * an offset from the last postion. */ public static final int SCROLL_ABSOLUTE = 5 + SCROLL_EVENT; /** {@collect.stats} * The scroll begin event. */ public static final int SCROLL_BEGIN = 6 + SCROLL_EVENT; /** {@collect.stats} * The scroll end event. */ public static final int SCROLL_END = 7 + SCROLL_EVENT; /* List Events */ private static final int LIST_EVENT = 700; /** {@collect.stats} * An item in a list has been selected. */ public static final int LIST_SELECT = 1 + LIST_EVENT; /** {@collect.stats} * An item in a list has been deselected. */ public static final int LIST_DESELECT = 2 + LIST_EVENT; /* Misc Event */ private static final int MISC_EVENT = 1000; /** {@collect.stats} * This event indicates that the user wants some action to occur. */ public static final int ACTION_EVENT = 1 + MISC_EVENT; /** {@collect.stats} * A file loading event. */ public static final int LOAD_FILE = 2 + MISC_EVENT; /** {@collect.stats} * A file saving event. */ public static final int SAVE_FILE = 3 + MISC_EVENT; /** {@collect.stats} * A component gained the focus. */ public static final int GOT_FOCUS = 4 + MISC_EVENT; /** {@collect.stats} * A component lost the focus. */ public static final int LOST_FOCUS = 5 + MISC_EVENT; /** {@collect.stats} * The target component. This indicates the component over which the * event occurred or with which the event is associated. * This object has been replaced by AWTEvent.getSource() * * @serial * @see java.awt.AWTEvent#getSource() */ public Object target; /** {@collect.stats} * The time stamp. * Replaced by InputEvent.getWhen(). * * @serial * @see java.awt.event.InputEvent#getWhen() */ public long when; /** {@collect.stats} * Indicates which type of event the event is, and which * other <code>Event</code> variables are relevant for the event. * This has been replaced by AWTEvent.getID() * * @serial * @see java.awt.AWTEvent#getID() */ public int id; /** {@collect.stats} * The <i>x</i> coordinate of the event. * Replaced by MouseEvent.getX() * * @serial * @see java.awt.event.MouseEvent#getX() */ public int x; /** {@collect.stats} * The <i>y</i> coordinate of the event. * Replaced by MouseEvent.getY() * * @serial * @see java.awt.event.MouseEvent#getY() */ public int y; /** {@collect.stats} * The key code of the key that was pressed in a keyboard event. * This has been replaced by KeyEvent.getKeyCode() * * @serial * @see java.awt.event.KeyEvent#getKeyCode() */ public int key; /** {@collect.stats} * The key character that was pressed in a keyboard event. */ // public char keyChar; /** {@collect.stats} * The state of the modifier keys. * This is replaced with InputEvent.getModifiers() * In java 1.1 MouseEvent and KeyEvent are subclasses * of InputEvent. * * @serial * @see java.awt.event.InputEvent#getModifiers() */ public int modifiers; /** {@collect.stats} * For <code>MOUSE_DOWN</code> events, this field indicates the * number of consecutive clicks. For other events, its value is * <code>0</code>. * This field has been replaced by MouseEvent.getClickCount(). * * @serial * @see java.awt.event.MouseEvent#getClickCount(). */ public int clickCount; /** {@collect.stats} * An arbitrary argument of the event. The value of this field * depends on the type of event. * <code>arg</code> has been replaced by event specific property. * * @serial */ public Object arg; /** {@collect.stats} * The next event. This field is set when putting events into a * linked list. * This has been replaced by EventQueue. * * @serial * @see java.awt.EventQueue */ public Event evt; /* table for mapping old Event action keys to KeyEvent virtual keys. */ private static final int actionKeyCodes[][] = { /* virtual key action key */ { KeyEvent.VK_HOME, Event.HOME }, { KeyEvent.VK_END, Event.END }, { KeyEvent.VK_PAGE_UP, Event.PGUP }, { KeyEvent.VK_PAGE_DOWN, Event.PGDN }, { KeyEvent.VK_UP, Event.UP }, { KeyEvent.VK_DOWN, Event.DOWN }, { KeyEvent.VK_LEFT, Event.LEFT }, { KeyEvent.VK_RIGHT, Event.RIGHT }, { KeyEvent.VK_F1, Event.F1 }, { KeyEvent.VK_F2, Event.F2 }, { KeyEvent.VK_F3, Event.F3 }, { KeyEvent.VK_F4, Event.F4 }, { KeyEvent.VK_F5, Event.F5 }, { KeyEvent.VK_F6, Event.F6 }, { KeyEvent.VK_F7, Event.F7 }, { KeyEvent.VK_F8, Event.F8 }, { KeyEvent.VK_F9, Event.F9 }, { KeyEvent.VK_F10, Event.F10 }, { KeyEvent.VK_F11, Event.F11 }, { KeyEvent.VK_F12, Event.F12 }, { KeyEvent.VK_PRINTSCREEN, Event.PRINT_SCREEN }, { KeyEvent.VK_SCROLL_LOCK, Event.SCROLL_LOCK }, { KeyEvent.VK_CAPS_LOCK, Event.CAPS_LOCK }, { KeyEvent.VK_NUM_LOCK, Event.NUM_LOCK }, { KeyEvent.VK_PAUSE, Event.PAUSE }, { KeyEvent.VK_INSERT, Event.INSERT } }; /** {@collect.stats} * This field controls whether or not the event is sent back * down to the peer once the target has processed it - * false means it's sent to the peer, true means it's not. * * @serial * @see #isConsumed() */ private boolean consumed = false; /* * JDK 1.1 serialVersionUID */ private static final long serialVersionUID = 5488922509400504703L; static { /* ensure that the necessary native libraries are loaded */ Toolkit.loadLibraries(); if (!GraphicsEnvironment.isHeadless()) { initIDs(); } } /** {@collect.stats} * Initialize JNI field and method IDs for fields that may be accessed from C. */ private static native void initIDs(); /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * Creates an instance of <code>Event</code> with the specified target * component, time stamp, event type, <i>x</i> and <i>y</i> * coordinates, keyboard key, state of the modifier keys, and * argument. * @param target the target component. * @param when the time stamp. * @param id the event type. * @param x the <i>x</i> coordinate. * @param y the <i>y</i> coordinate. * @param key the key pressed in a keyboard event. * @param modifiers the state of the modifier keys. * @param arg the specified argument. */ public Event(Object target, long when, int id, int x, int y, int key, int modifiers, Object arg) { this.target = target; this.when = when; this.id = id; this.x = x; this.y = y; this.key = key; this.modifiers = modifiers; this.arg = arg; this.data = 0; this.clickCount = 0; switch(id) { case ACTION_EVENT: case WINDOW_DESTROY: case WINDOW_ICONIFY: case WINDOW_DEICONIFY: case WINDOW_MOVED: case SCROLL_LINE_UP: case SCROLL_LINE_DOWN: case SCROLL_PAGE_UP: case SCROLL_PAGE_DOWN: case SCROLL_ABSOLUTE: case SCROLL_BEGIN: case SCROLL_END: case LIST_SELECT: case LIST_DESELECT: consumed = true; // these types are not passed back to peer break; default: } } /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * Creates an instance of <code>Event</code>, with the specified target * component, time stamp, event type, <i>x</i> and <i>y</i> * coordinates, keyboard key, state of the modifier keys, and an * argument set to <code>null</code>. * @param target the target component. * @param when the time stamp. * @param id the event type. * @param x the <i>x</i> coordinate. * @param y the <i>y</i> coordinate. * @param key the key pressed in a keyboard event. * @param modifiers the state of the modifier keys. */ public Event(Object target, long when, int id, int x, int y, int key, int modifiers) { this(target, when, id, x, y, key, modifiers, null); } /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * Creates an instance of <code>Event</code> with the specified * target component, event type, and argument. * @param target the target component. * @param id the event type. * @param arg the specified argument. */ public Event(Object target, int id, Object arg) { this(target, 0, id, 0, 0, 0, 0, arg); } /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * Translates this event so that its <i>x</i> and <i>y</i> * coordinates are increased by <i>dx</i> and <i>dy</i>, * respectively. * <p> * This method translates an event relative to the given component. * This involves, at a minimum, translating the coordinates into the * local coordinate system of the given component. It may also involve * translating a region in the case of an expose event. * @param dx the distance to translate the <i>x</i> coordinate. * @param dy the distance to translate the <i>y</i> coordinate. */ public void translate(int dx, int dy) { this.x += dx; this.y += dy; } /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * Checks if the Shift key is down. * @return <code>true</code> if the key is down; * <code>false</code> otherwise. * @see java.awt.Event#modifiers * @see java.awt.Event#controlDown * @see java.awt.Event#metaDown */ public boolean shiftDown() { return (modifiers & SHIFT_MASK) != 0; } /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * Checks if the Control key is down. * @return <code>true</code> if the key is down; * <code>false</code> otherwise. * @see java.awt.Event#modifiers * @see java.awt.Event#shiftDown * @see java.awt.Event#metaDown */ public boolean controlDown() { return (modifiers & CTRL_MASK) != 0; } /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * Checks if the Meta key is down. * * @return <code>true</code> if the key is down; * <code>false</code> otherwise. * @see java.awt.Event#modifiers * @see java.awt.Event#shiftDown * @see java.awt.Event#controlDown */ public boolean metaDown() { return (modifiers & META_MASK) != 0; } /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. */ void consume() { switch(id) { case KEY_PRESS: case KEY_RELEASE: case KEY_ACTION: case KEY_ACTION_RELEASE: consumed = true; break; default: // event type cannot be consumed } } /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. */ boolean isConsumed() { return consumed; } /* * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * Returns the integer key-code associated with the key in this event, * as described in java.awt.Event. */ static int getOldEventKey(KeyEvent e) { int keyCode = e.getKeyCode(); for (int i = 0; i < actionKeyCodes.length; i++) { if (actionKeyCodes[i][0] == keyCode) { return actionKeyCodes[i][1]; } } return (int)e.getKeyChar(); } /* * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * Returns a new KeyEvent char which corresponds to the int key * of this old event. */ char getKeyEventChar() { for (int i = 0; i < actionKeyCodes.length; i++) { if (actionKeyCodes[i][1] == key) { return KeyEvent.CHAR_UNDEFINED; } } return (char)key; } /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * Returns a string representing the state of this <code>Event</code>. * This method is intended to be used only for debugging purposes, and the * content and format of the returned string may vary between * implementations. The returned string may be empty but may not be * <code>null</code>. * * @return the parameter string of this event */ protected String paramString() { String str = "id=" + id + ",x=" + x + ",y=" + y; if (key != 0) { str += ",key=" + key; } if (shiftDown()) { str += ",shift"; } if (controlDown()) { str += ",control"; } if (metaDown()) { str += ",meta"; } if (target != null) { str += ",target=" + target; } if (arg != null) { str += ",arg=" + arg; } return str; } /** {@collect.stats} * <b>NOTE:</b> The <code>Event</code> class is obsolete and is * available only for backwards compatilibility. It has been replaced * by the <code>AWTEvent</code> class and its subclasses. * <p> * Returns a representation of this event's values as a string. * @return a string that represents the event and the values * of its member fields. * @see java.awt.Event#paramString * @since JDK1.1 */ public String toString() { return getClass().getName() + "[" + paramString() + "]"; } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; /** {@collect.stats} * The <code>DisplayMode</code> class encapsulates the bit depth, height, * width, and refresh rate of a <code>GraphicsDevice</code>. The ability to * change graphics device's display mode is platform- and * configuration-dependent and may not always be available * (see {@link GraphicsDevice#isDisplayChangeSupported}). * <p> * For more information on full-screen exclusive mode API, see the * <a href="http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html"> * Full-Screen Exclusive Mode API Tutorial</a>. * * @see GraphicsDevice * @see GraphicsDevice#isDisplayChangeSupported * @see GraphicsDevice#getDisplayModes * @see GraphicsDevice#setDisplayMode * @author Michael Martak * @since 1.4 */ public final class DisplayMode { private Dimension size; private int bitDepth; private int refreshRate; /** {@collect.stats} * Create a new display mode object with the supplied parameters. * @param width the width of the display, in pixels * @param height the height of the display, in pixels * @param bitDepth the bit depth of the display, in bits per * pixel. This can be <code>BIT_DEPTH_MULTI</code> if multiple * bit depths are available. * @param refreshRate the refresh rate of the display, in hertz. * This can be <code>REFRESH_RATE_UNKNOWN</code> if the * information is not available. * @see #BIT_DEPTH_MULTI * @see #REFRESH_RATE_UNKNOWN */ public DisplayMode(int width, int height, int bitDepth, int refreshRate) { this.size = new Dimension(width, height); this.bitDepth = bitDepth; this.refreshRate = refreshRate; } /** {@collect.stats} * Returns the height of the display, in pixels. * @return the height of the display, in pixels */ public int getHeight() { return size.height; } /** {@collect.stats} * Returns the width of the display, in pixels. * @return the width of the display, in pixels */ public int getWidth() { return size.width; } /** {@collect.stats} * Value of the bit depth if multiple bit depths are supported in this * display mode. * @see #getBitDepth */ public final static int BIT_DEPTH_MULTI = -1; /** {@collect.stats} * Returns the bit depth of the display, in bits per pixel. This may be * <code>BIT_DEPTH_MULTI</code> if multiple bit depths are supported in * this display mode. * * @return the bit depth of the display, in bits per pixel. * @see #BIT_DEPTH_MULTI */ public int getBitDepth() { return bitDepth; } /** {@collect.stats} * Value of the refresh rate if not known. * @see #getRefreshRate */ public final static int REFRESH_RATE_UNKNOWN = 0; /** {@collect.stats} * Returns the refresh rate of the display, in hertz. This may be * <code>REFRESH_RATE_UNKNOWN</code> if the information is not available. * * @return the refresh rate of the display, in hertz. * @see #REFRESH_RATE_UNKNOWN */ public int getRefreshRate() { return refreshRate; } /** {@collect.stats} * Returns whether the two display modes are equal. * @return whether the two display modes are equal */ public boolean equals(DisplayMode dm) { if (dm == null) { return false; } return (getHeight() == dm.getHeight() && getWidth() == dm.getWidth() && getBitDepth() == dm.getBitDepth() && getRefreshRate() == dm.getRefreshRate()); } /** {@collect.stats} * {@inheritDoc} */ public boolean equals(Object dm) { if (dm instanceof DisplayMode) { return equals((DisplayMode)dm); } else { return false; } } /** {@collect.stats} * {@inheritDoc} */ public int hashCode() { return getWidth() + getHeight() + getBitDepth() * 7 + getRefreshRate() * 13; } }
Java
/* * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.io.PrintStream; import java.io.PrintWriter; import java.util.Vector; import java.util.Locale; import java.util.EventListener; import java.util.Iterator; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Collections; import java.awt.peer.ComponentPeer; import java.awt.peer.ContainerPeer; import java.awt.peer.LightweightPeer; import java.awt.image.BufferStrategy; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; import java.awt.image.ColorModel; import java.awt.image.VolatileImage; import java.awt.event.*; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.awt.event.InputMethodListener; import java.awt.event.InputMethodEvent; import java.awt.im.InputContext; import java.awt.im.InputMethodRequests; import java.awt.dnd.DropTarget; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.AccessControlContext; import javax.accessibility.*; import java.util.logging.*; import java.applet.Applet; import sun.awt.AWTAccessor; import sun.security.action.GetPropertyAction; import sun.awt.AppContext; import sun.awt.ConstrainableGraphics; import sun.awt.SubRegionShowable; import sun.awt.WindowClosingListener; import sun.awt.CausedFocusEvent; import sun.awt.EmbeddedFrame; import sun.awt.dnd.SunDropTargetEvent; import sun.awt.im.CompositionArea; import sun.java2d.SunGraphics2D; import sun.java2d.pipe.Region; import sun.awt.RequestFocusController; /** {@collect.stats} * A <em>component</em> is an object having a graphical representation * that can be displayed on the screen and that can interact with the * user. Examples of components are the buttons, checkboxes, and scrollbars * of a typical graphical user interface. <p> * The <code>Component</code> class is the abstract superclass of * the nonmenu-related Abstract Window Toolkit components. Class * <code>Component</code> can also be extended directly to create a * lightweight component. A lightweight component is a component that is * not associated with a native opaque window. * <p> * <h3>Serialization</h3> * It is important to note that only AWT listeners which conform * to the <code>Serializable</code> protocol will be saved when * the object is stored. If an AWT object has listeners that * aren't marked serializable, they will be dropped at * <code>writeObject</code> time. Developers will need, as always, * to consider the implications of making an object serializable. * One situation to watch out for is this: * <pre> * import java.awt.*; * import java.awt.event.*; * import java.io.Serializable; * * class MyApp implements ActionListener, Serializable * { * BigObjectThatShouldNotBeSerializedWithAButton bigOne; * Button aButton = new Button(); * * MyApp() * { * // Oops, now aButton has a listener with a reference * // to bigOne! * aButton.addActionListener(this); * } * * public void actionPerformed(ActionEvent e) * { * System.out.println("Hello There"); * } * } * </pre> * In this example, serializing <code>aButton</code> by itself * will cause <code>MyApp</code> and everything it refers to * to be serialized as well. The problem is that the listener * is serializable by coincidence, not by design. To separate * the decisions about <code>MyApp</code> and the * <code>ActionListener</code> being serializable one can use a * nested class, as in the following example: * <pre> * import java.awt.*; * import java.awt.event.*; * import java.io.Serializable; * * class MyApp java.io.Serializable * { * BigObjectThatShouldNotBeSerializedWithAButton bigOne; * Button aButton = new Button(); * * static class MyActionListener implements ActionListener * { * public void actionPerformed(ActionEvent e) * { * System.out.println("Hello There"); * } * } * * MyApp() * { * aButton.addActionListener(new MyActionListener()); * } * } * </pre> * <p> * <b>Note</b>: For more information on the paint mechanisms utilitized * by AWT and Swing, including information on how to write the most * efficient painting code, see * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. * <p> * For details on the focus subsystem, see * <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html"> * How to Use the Focus Subsystem</a>, * a section in <em>The Java Tutorial</em>, and the * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> * for more information. * * @author Arthur van Hoff * @author Sami Shaio */ public abstract class Component implements ImageObserver, MenuContainer, Serializable { private static final Logger log = Logger.getLogger("java.awt.Component"); private static final Logger eventLog = Logger.getLogger("java.awt.event.Component"); private static final Logger focusLog = Logger.getLogger("java.awt.focus.Component"); private static final Logger mixingLog = Logger.getLogger("java.awt.mixing.Component"); /** {@collect.stats} * The peer of the component. The peer implements the component's * behavior. The peer is set when the <code>Component</code> is * added to a container that also is a peer. * @see #addNotify * @see #removeNotify */ transient ComponentPeer peer; /** {@collect.stats} * The parent of the object. It may be <code>null</code> * for top-level components. * @see #getParent */ transient Container parent; /** {@collect.stats} * The <code>AppContext</code> of the component. Applets/Plugin may * change the AppContext. */ transient AppContext appContext; /** {@collect.stats} * The x position of the component in the parent's coordinate system. * * @serial * @see #getLocation */ int x; /** {@collect.stats} * The y position of the component in the parent's coordinate system. * * @serial * @see #getLocation */ int y; /** {@collect.stats} * The width of the component. * * @serial * @see #getSize */ int width; /** {@collect.stats} * The height of the component. * * @serial * @see #getSize */ int height; /** {@collect.stats} * The foreground color for this component. * <code>foreground</code> can be <code>null</code>. * * @serial * @see #getForeground * @see #setForeground */ Color foreground; /** {@collect.stats} * The background color for this component. * <code>background</code> can be <code>null</code>. * * @serial * @see #getBackground * @see #setBackground */ Color background; /** {@collect.stats} * The font used by this component. * The <code>font</code> can be <code>null</code>. * * @serial * @see #getFont * @see #setFont */ Font font; /** {@collect.stats} * The font which the peer is currently using. * (<code>null</code> if no peer exists.) */ Font peerFont; /** {@collect.stats} * The cursor displayed when pointer is over this component. * This value can be <code>null</code>. * * @serial * @see #getCursor * @see #setCursor */ Cursor cursor; /** {@collect.stats} * The locale for the component. * * @serial * @see #getLocale * @see #setLocale */ Locale locale; /** {@collect.stats} * A reference to a <code>GraphicsConfiguration</code> object * used to describe the characteristics of a graphics * destination. * This value can be <code>null</code>. * * @since 1.3 * @serial * @see GraphicsConfiguration * @see #getGraphicsConfiguration */ transient GraphicsConfiguration graphicsConfig = null; /** {@collect.stats} * A reference to a <code>BufferStrategy</code> object * used to manipulate the buffers on this component. * * @since 1.4 * @see java.awt.image.BufferStrategy * @see #getBufferStrategy() */ transient BufferStrategy bufferStrategy = null; /** {@collect.stats} * True when the object should ignore all repaint events. * * @since 1.4 * @serial * @see #setIgnoreRepaint * @see #getIgnoreRepaint */ boolean ignoreRepaint = false; /** {@collect.stats} * True when the object is visible. An object that is not * visible is not drawn on the screen. * * @serial * @see #isVisible * @see #setVisible */ boolean visible = true; /** {@collect.stats} * True when the object is enabled. An object that is not * enabled does not interact with the user. * * @serial * @see #isEnabled * @see #setEnabled */ boolean enabled = true; /** {@collect.stats} * True when the object is valid. An invalid object needs to * be layed out. This flag is set to false when the object * size is changed. * * @serial * @see #isValid * @see #validate * @see #invalidate */ volatile boolean valid = false; /** {@collect.stats} * The <code>DropTarget</code> associated with this component. * * @since 1.2 * @serial * @see #setDropTarget * @see #getDropTarget */ DropTarget dropTarget; /** {@collect.stats} * @serial * @see #add */ Vector popups; /** {@collect.stats} * A component's name. * This field can be <code>null</code>. * * @serial * @see #getName * @see #setName(String) */ private String name; /** {@collect.stats} * A bool to determine whether the name has * been set explicitly. <code>nameExplicitlySet</code> will * be false if the name has not been set and * true if it has. * * @serial * @see #getName * @see #setName(String) */ private boolean nameExplicitlySet = false; /** {@collect.stats} * Indicates whether this Component can be focused. * * @serial * @see #setFocusable * @see #isFocusable * @since 1.4 */ private boolean focusable = true; private static final int FOCUS_TRAVERSABLE_UNKNOWN = 0; private static final int FOCUS_TRAVERSABLE_DEFAULT = 1; private static final int FOCUS_TRAVERSABLE_SET = 2; /** {@collect.stats} * Tracks whether this Component is relying on default focus travesability. * * @serial * @since 1.4 */ private int isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN; /** {@collect.stats} * The focus traversal keys. These keys will generate focus traversal * behavior for Components for which focus traversal keys are enabled. If a * value of null is specified for a traversal key, this Component inherits * that traversal key from its parent. If all ancestors of this Component * have null specified for that traversal key, then the current * KeyboardFocusManager's default traversal key is used. * * @serial * @see #setFocusTraversalKeys * @see #getFocusTraversalKeys * @since 1.4 */ Set[] focusTraversalKeys; private static final String[] focusTraversalKeyPropertyNames = { "forwardFocusTraversalKeys", "backwardFocusTraversalKeys", "upCycleFocusTraversalKeys", "downCycleFocusTraversalKeys" }; /** {@collect.stats} * Indicates whether focus traversal keys are enabled for this Component. * Components for which focus traversal keys are disabled receive key * events for focus traversal keys. Components for which focus traversal * keys are enabled do not see these events; instead, the events are * automatically converted to traversal operations. * * @serial * @see #setFocusTraversalKeysEnabled * @see #getFocusTraversalKeysEnabled * @since 1.4 */ private boolean focusTraversalKeysEnabled = true; /** {@collect.stats} * The locking object for AWT component-tree and layout operations. * * @see #getTreeLock */ static final Object LOCK = new AWTTreeLock(); static class AWTTreeLock {} /* * The component's AccessControlContext. */ private transient volatile AccessControlContext acc = AccessController.getContext(); /** {@collect.stats} * Minimum size. * (This field perhaps should have been transient). * * @serial */ Dimension minSize; /** {@collect.stats} * Whether or not setMinimumSize has been invoked with a non-null value. */ boolean minSizeSet; /** {@collect.stats} * Preferred size. * (This field perhaps should have been transient). * * @serial */ Dimension prefSize; /** {@collect.stats} * Whether or not setPreferredSize has been invoked with a non-null value. */ boolean prefSizeSet; /** {@collect.stats} * Maximum size * * @serial */ Dimension maxSize; /** {@collect.stats} * Whether or not setMaximumSize has been invoked with a non-null value. */ boolean maxSizeSet; /** {@collect.stats} * The orientation for this component. * @see #getComponentOrientation * @see #setComponentOrientation */ transient ComponentOrientation componentOrientation = ComponentOrientation.UNKNOWN; /** {@collect.stats} * <code>newEventsOnly</code> will be true if the event is * one of the event types enabled for the component. * It will then allow for normal processing to * continue. If it is false the event is passed * to the component's parent and up the ancestor * tree until the event has been consumed. * * @serial * @see #dispatchEvent */ boolean newEventsOnly = false; transient ComponentListener componentListener; transient FocusListener focusListener; transient HierarchyListener hierarchyListener; transient HierarchyBoundsListener hierarchyBoundsListener; transient KeyListener keyListener; transient MouseListener mouseListener; transient MouseMotionListener mouseMotionListener; transient MouseWheelListener mouseWheelListener; transient InputMethodListener inputMethodListener; transient RuntimeException windowClosingException = null; /** {@collect.stats} Internal, constants for serialization */ final static String actionListenerK = "actionL"; final static String adjustmentListenerK = "adjustmentL"; final static String componentListenerK = "componentL"; final static String containerListenerK = "containerL"; final static String focusListenerK = "focusL"; final static String itemListenerK = "itemL"; final static String keyListenerK = "keyL"; final static String mouseListenerK = "mouseL"; final static String mouseMotionListenerK = "mouseMotionL"; final static String mouseWheelListenerK = "mouseWheelL"; final static String textListenerK = "textL"; final static String ownedWindowK = "ownedL"; final static String windowListenerK = "windowL"; final static String inputMethodListenerK = "inputMethodL"; final static String hierarchyListenerK = "hierarchyL"; final static String hierarchyBoundsListenerK = "hierarchyBoundsL"; final static String windowStateListenerK = "windowStateL"; final static String windowFocusListenerK = "windowFocusL"; /** {@collect.stats} * The <code>eventMask</code> is ONLY set by subclasses via * <code>enableEvents</code>. * The mask should NOT be set when listeners are registered * so that we can distinguish the difference between when * listeners request events and subclasses request them. * One bit is used to indicate whether input methods are * enabled; this bit is set by <code>enableInputMethods</code> and is * on by default. * * @serial * @see #enableInputMethods * @see AWTEvent */ long eventMask = AWTEvent.INPUT_METHODS_ENABLED_MASK; /** {@collect.stats} * Static properties for incremental drawing. * @see #imageUpdate */ static boolean isInc; static int incRate; static { /* ensure that the necessary native libraries are loaded */ Toolkit.loadLibraries(); /* initialize JNI field and method ids */ if (!GraphicsEnvironment.isHeadless()) { initIDs(); } String s = (String) java.security.AccessController.doPrivileged( new GetPropertyAction("awt.image.incrementaldraw")); isInc = (s == null || s.equals("true")); s = (String) java.security.AccessController.doPrivileged( new GetPropertyAction("awt.image.redrawrate")); incRate = (s != null) ? Integer.parseInt(s) : 100; } /** {@collect.stats} * Ease-of-use constant for <code>getAlignmentY()</code>. * Specifies an alignment to the top of the component. * @see #getAlignmentY */ public static final float TOP_ALIGNMENT = 0.0f; /** {@collect.stats} * Ease-of-use constant for <code>getAlignmentY</code> and * <code>getAlignmentX</code>. Specifies an alignment to * the center of the component * @see #getAlignmentX * @see #getAlignmentY */ public static final float CENTER_ALIGNMENT = 0.5f; /** {@collect.stats} * Ease-of-use constant for <code>getAlignmentY</code>. * Specifies an alignment to the bottom of the component. * @see #getAlignmentY */ public static final float BOTTOM_ALIGNMENT = 1.0f; /** {@collect.stats} * Ease-of-use constant for <code>getAlignmentX</code>. * Specifies an alignment to the left side of the component. * @see #getAlignmentX */ public static final float LEFT_ALIGNMENT = 0.0f; /** {@collect.stats} * Ease-of-use constant for <code>getAlignmentX</code>. * Specifies an alignment to the right side of the component. * @see #getAlignmentX */ public static final float RIGHT_ALIGNMENT = 1.0f; /* * JDK 1.1 serialVersionUID */ private static final long serialVersionUID = -7644114512714619750L; /** {@collect.stats} * If any <code>PropertyChangeListeners</code> have been registered, * the <code>changeSupport</code> field describes them. * * @serial * @since 1.2 * @see #addPropertyChangeListener * @see #removePropertyChangeListener * @see #firePropertyChange */ private PropertyChangeSupport changeSupport; // Note: this field is considered final, though readObject() prohibits // initializing final fields. private transient Object changeSupportLock = new Object(); private Object getChangeSupportLock() { return changeSupportLock; } /* * Returns the acc this component was constructed with. */ final AccessControlContext getAccessControlContext() { if (acc == null) { throw new SecurityException("Component is missing AccessControlContext"); } return acc; } boolean isPacked = false; /** {@collect.stats} * Pseudoparameter for direct Geometry API (setLocation, setBounds setSize * to signal setBounds what's changing. Should be used under TreeLock. * This is only needed due to the inability to change the cross-calling * order of public and deprecated methods. */ private int boundsOp = ComponentPeer.DEFAULT_OPERATION; /** {@collect.stats} * Enumeration of the common ways the baseline of a component can * change as the size changes. The baseline resize behavior is * primarily for layout managers that need to know how the * position of the baseline changes as the component size changes. * In general the baseline resize behavior will be valid for sizes * greater than or equal to the minimum size (the actual minimum * size; not a developer specified minimum size). For sizes * smaller than the minimum size the baseline may change in a way * other than the baseline resize behavior indicates. Similarly, * as the size approaches <code>Integer.MAX_VALUE</code> and/or * <code>Short.MAX_VALUE</code> the baseline may change in a way * other than the baseline resize behavior indicates. * * @see #getBaselineResizeBehavior * @see #getBaseline(int,int) * @since 1.6 */ public enum BaselineResizeBehavior { /** {@collect.stats} * Indicates the baseline remains fixed relative to the * y-origin. That is, <code>getBaseline</code> returns * the same value regardless of the height or width. For example, a * <code>JLabel</code> containing non-empty text with a * vertical alignment of <code>TOP</code> should have a * baseline type of <code>CONSTANT_ASCENT</code>. */ CONSTANT_ASCENT, /** {@collect.stats} * Indicates the baseline remains fixed relative to the height * and does not change as the width is varied. That is, for * any height H the difference between H and * <code>getBaseline(w, H)</code> is the same. For example, a * <code>JLabel</code> containing non-empty text with a * vertical alignment of <code>BOTTOM</code> should have a * baseline type of <code>CONSTANT_DESCENT</code>. */ CONSTANT_DESCENT, /** {@collect.stats} * Indicates the baseline remains a fixed distance from * the center of the component. That is, for any height H the * difference between <code>getBaseline(w, H)</code> and * <code>H / 2</code> is the same (plus or minus one depending upon * rounding error). * <p> * Because of possible rounding errors it is recommended * you ask for the baseline with two consecutive heights and use * the return value to determine if you need to pad calculations * by 1. The following shows how to calculate the baseline for * any height: * <pre> * Dimension preferredSize = component.getPreferredSize(); * int baseline = getBaseline(preferredSize.width, * preferredSize.height); * int nextBaseline = getBaseline(preferredSize.width, * preferredSize.height + 1); * // Amount to add to height when calculating where baseline * // lands for a particular height: * int padding = 0; * // Where the baseline is relative to the mid point * int baselineOffset = baseline - height / 2; * if (preferredSize.height % 2 == 0 &amp;&amp; * baseline != nextBaseline) { * padding = 1; * } * else if (preferredSize.height % 2 == 1 &amp;&amp; * baseline == nextBaseline) { * baselineOffset--; * padding = 1; * } * // The following calculates where the baseline lands for * // the height z: * int calculatedBaseline = (z + padding) / 2 + baselineOffset; * </pre> */ CENTER_OFFSET, /** {@collect.stats} * Indicates the baseline resize behavior can not be expressed using * any of the other constants. This may also indicate the baseline * varies with the width of the component. This is also returned * by components that do not have a baseline. */ OTHER } /* * The shape set with the applyCompoundShape() method. It uncludes the result * of the HW/LW mixing related shape computation. It may also include * the user-specified shape of the component. */ private transient Region compoundShape = null; /* * Indicates whether addNotify() is complete * (i.e. the peer is created). */ private transient boolean isAddNotifyComplete = false; private static final PropertyChangeListener opaquePropertyChangeListener = new PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { ((Component)evt.getSource()).mixOnOpaqueChanging(); } }; /** {@collect.stats} * Should only be used in subclass getBounds to check that part of bounds * is actualy changing */ int getBoundsOp() { assert Thread.holdsLock(getTreeLock()); return boundsOp; } void setBoundsOp(int op) { assert Thread.holdsLock(getTreeLock()); if (op == ComponentPeer.RESET_OPERATION) { boundsOp = ComponentPeer.DEFAULT_OPERATION; } else if (boundsOp == ComponentPeer.DEFAULT_OPERATION) { boundsOp = op; } } static { AWTAccessor.setComponentAccessor(new AWTAccessor.ComponentAccessor() { public AccessControlContext getAccessControlContext(Component comp) { return comp.getAccessControlContext(); } }); } /** {@collect.stats} * Constructs a new component. Class <code>Component</code> can be * extended directly to create a lightweight component that does not * utilize an opaque native window. A lightweight component must be * hosted by a native container somewhere higher up in the component * tree (for example, by a <code>Frame</code> object). */ protected Component() { appContext = AppContext.getAppContext(); } void initializeFocusTraversalKeys() { focusTraversalKeys = new Set[3]; } /** {@collect.stats} * Constructs a name for this component. Called by <code>getName</code> * when the name is <code>null</code>. */ String constructComponentName() { return null; // For strict compliance with prior platform versions, a Component // that doesn't set its name should return null from // getName() } /** {@collect.stats} * Gets the name of the component. * @return this component's name * @see #setName * @since JDK1.1 */ public String getName() { if (name == null && !nameExplicitlySet) { synchronized(this) { if (name == null && !nameExplicitlySet) name = constructComponentName(); } } return name; } /** {@collect.stats} * Sets the name of the component to the specified string. * @param name the string that is to be this * component's name * @see #getName * @since JDK1.1 */ public void setName(String name) { String oldName; synchronized(this) { oldName = this.name; this.name = name; nameExplicitlySet = true; } firePropertyChange("name", oldName, name); } /** {@collect.stats} * Gets the parent of this component. * @return the parent container of this component * @since JDK1.0 */ public Container getParent() { return getParent_NoClientCode(); } // NOTE: This method may be called by privileged threads. // This functionality is implemented in a package-private method // to insure that it cannot be overridden by client subclasses. // DO NOT INVOKE CLIENT CODE ON THIS THREAD! final Container getParent_NoClientCode() { return parent; } // This method is overriden in the Window class to return null, // because the parent field of the Window object contains // the owner of the window, not its parent. Container getContainer() { return getParent(); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * programs should not directly manipulate peers; * replaced by <code>boolean isDisplayable()</code>. */ @Deprecated public ComponentPeer getPeer() { return peer; } /** {@collect.stats} * Associate a <code>DropTarget</code> with this component. * The <code>Component</code> will receive drops only if it * is enabled. * * @see #isEnabled * @param dt The DropTarget */ public synchronized void setDropTarget(DropTarget dt) { if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt))) return; DropTarget old; if ((old = dropTarget) != null) { if (peer != null) dropTarget.removeNotify(peer); DropTarget t = dropTarget; dropTarget = null; try { t.setComponent(null); } catch (IllegalArgumentException iae) { // ignore it. } } // if we have a new one, and we have a peer, add it! if ((dropTarget = dt) != null) { try { dropTarget.setComponent(this); if (peer != null) dropTarget.addNotify(peer); } catch (IllegalArgumentException iae) { if (old != null) { try { old.setComponent(this); if (peer != null) dropTarget.addNotify(peer); } catch (IllegalArgumentException iae1) { // ignore it! } } } } } /** {@collect.stats} * Gets the <code>DropTarget</code> associated with this * <code>Component</code>. */ public synchronized DropTarget getDropTarget() { return dropTarget; } /** {@collect.stats} * Gets the <code>GraphicsConfiguration</code> associated with this * <code>Component</code>. * If the <code>Component</code> has not been assigned a specific * <code>GraphicsConfiguration</code>, * the <code>GraphicsConfiguration</code> of the * <code>Component</code> object's top-level container is * returned. * If the <code>Component</code> has been created, but not yet added * to a <code>Container</code>, this method returns <code>null</code>. * * @return the <code>GraphicsConfiguration</code> used by this * <code>Component</code> or <code>null</code> * @since 1.3 */ public GraphicsConfiguration getGraphicsConfiguration() { synchronized(getTreeLock()) { if (graphicsConfig != null) { return graphicsConfig; } else if (getParent() != null) { return getParent().getGraphicsConfiguration(); } else { return null; } } } final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() { GraphicsConfiguration graphicsConfig = this.graphicsConfig; Container parent = this.parent; if (graphicsConfig != null) { return graphicsConfig; } else if (parent != null) { return parent.getGraphicsConfiguration_NoClientCode(); } else { return null; } } /** {@collect.stats} * Resets this <code>Component</code>'s * <code>GraphicsConfiguration</code> back to a default * value. For most componenets, this is <code>null</code>. * Called from the Toolkit thread, so NO CLIENT CODE. */ void resetGC() { synchronized(getTreeLock()) { graphicsConfig = null; } } /* * Not called on Component, but needed for Canvas and Window */ void setGCFromPeer() { synchronized(getTreeLock()) { if (peer != null) { // can't imagine how this will be false, // but just in case graphicsConfig = peer.getGraphicsConfiguration(); } else { graphicsConfig = null; } } } /** {@collect.stats} * Checks that this component's <code>GraphicsDevice</code> * <code>idString</code> matches the string argument. */ void checkGD(String stringID) { if (graphicsConfig != null) { if (!graphicsConfig.getDevice().getIDstring().equals(stringID)) { throw new IllegalArgumentException( "adding a container to a container on a different GraphicsDevice"); } } } /** {@collect.stats} * Gets this component's locking object (the object that owns the thread * sychronization monitor) for AWT component-tree and layout * operations. * @return this component's locking object */ public final Object getTreeLock() { return LOCK; } final void checkTreeLock() { if (!Thread.holdsLock(getTreeLock())) { throw new IllegalStateException("This function should be called while holding treeLock"); } } /** {@collect.stats} * Gets the toolkit of this component. Note that * the frame that contains a component controls which * toolkit is used by that component. Therefore if the component * is moved from one frame to another, the toolkit it uses may change. * @return the toolkit of this component * @since JDK1.0 */ public Toolkit getToolkit() { return getToolkitImpl(); } /* * This is called by the native code, so client code can't * be called on the toolkit thread. */ final Toolkit getToolkitImpl() { ComponentPeer peer = this.peer; if ((peer != null) && ! (peer instanceof LightweightPeer)){ return peer.getToolkit(); } Container parent = this.parent; if (parent != null) { return parent.getToolkitImpl(); } return Toolkit.getDefaultToolkit(); } /** {@collect.stats} * Determines whether this component is valid. A component is valid * when it is correctly sized and positioned within its parent * container and all its children are also valid. * In order to account for peers' size requirements, components are invalidated * before they are first shown on the screen. By the time the parent container * is fully realized, all its components will be valid. * @return <code>true</code> if the component is valid, <code>false</code> * otherwise * @see #validate * @see #invalidate * @since JDK1.0 */ public boolean isValid() { return (peer != null) && valid; } /** {@collect.stats} * Determines whether this component is displayable. A component is * displayable when it is connected to a native screen resource. * <p> * A component is made displayable either when it is added to * a displayable containment hierarchy or when its containment * hierarchy is made displayable. * A containment hierarchy is made displayable when its ancestor * window is either packed or made visible. * <p> * A component is made undisplayable either when it is removed from * a displayable containment hierarchy or when its containment hierarchy * is made undisplayable. A containment hierarchy is made * undisplayable when its ancestor window is disposed. * * @return <code>true</code> if the component is displayable, * <code>false</code> otherwise * @see Container#add(Component) * @see Window#pack * @see Window#show * @see Container#remove(Component) * @see Window#dispose * @since 1.2 */ public boolean isDisplayable() { return getPeer() != null; } /** {@collect.stats} * Determines whether this component should be visible when its * parent is visible. Components are * initially visible, with the exception of top level components such * as <code>Frame</code> objects. * @return <code>true</code> if the component is visible, * <code>false</code> otherwise * @see #setVisible * @since JDK1.0 */ public boolean isVisible() { return isVisible_NoClientCode(); } final boolean isVisible_NoClientCode() { return visible; } /** {@collect.stats} * Determines whether this component will be displayed on the screen. * @return <code>true</code> if the component and all of its ancestors * until a toplevel window or null parent are visible, * <code>false</code> otherwise */ boolean isRecursivelyVisible() { return visible && (parent == null || parent.isRecursivelyVisible()); } /** {@collect.stats} * Translates absolute coordinates into coordinates in the coordinate * space of this component. */ Point pointRelativeToComponent(Point absolute) { Point compCoords = getLocationOnScreen(); return new Point(absolute.x - compCoords.x, absolute.y - compCoords.y); } /** {@collect.stats} * Assuming that mouse location is stored in PointerInfo passed * to this method, it finds a Component that is in the same * Window as this Component and is located under the mouse pointer. * If no such Component exists, null is returned. * NOTE: this method should be called under the protection of * tree lock, as it is done in Component.getMousePosition() and * Container.getMousePosition(boolean). */ Component findUnderMouseInWindow(PointerInfo pi) { if (!isShowing()) { return null; } Window win = getContainingWindow(); if (!Toolkit.getDefaultToolkit().getMouseInfoPeer().isWindowUnderMouse(win)) { return null; } final boolean INCLUDE_DISABLED = true; Point relativeToWindow = win.pointRelativeToComponent(pi.getLocation()); Component inTheSameWindow = win.findComponentAt(relativeToWindow.x, relativeToWindow.y, INCLUDE_DISABLED); return inTheSameWindow; } /** {@collect.stats} * Returns the position of the mouse pointer in this <code>Component</code>'s * coordinate space if the <code>Component</code> is directly under the mouse * pointer, otherwise returns <code>null</code>. * If the <code>Component</code> is not showing on the screen, this method * returns <code>null</code> even if the mouse pointer is above the area * where the <code>Component</code> would be displayed. * If the <code>Component</code> is partially or fully obscured by other * <code>Component</code>s or native windows, this method returns a non-null * value only if the mouse pointer is located above the unobscured part of the * <code>Component</code>. * <p> * For <code>Container</code>s it returns a non-null value if the mouse is * above the <code>Container</code> itself or above any of its descendants. * Use {@link Container#getMousePosition(boolean)} if you need to exclude children. * <p> * Sometimes the exact mouse coordinates are not important, and the only thing * that matters is whether a specific <code>Component</code> is under the mouse * pointer. If the return value of this method is <code>null</code>, mouse * pointer is not directly above the <code>Component</code>. * * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true * @see #isShowing * @see Container#getMousePosition * @return mouse coordinates relative to this <code>Component</code>, or null * @since 1.5 */ public Point getMousePosition() throws HeadlessException { if (GraphicsEnvironment.isHeadless()) { throw new HeadlessException(); } PointerInfo pi = (PointerInfo)java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Object run() { return MouseInfo.getPointerInfo(); } } ); synchronized (getTreeLock()) { Component inTheSameWindow = findUnderMouseInWindow(pi); if (!isSameOrAncestorOf(inTheSameWindow, true)) { return null; } return pointRelativeToComponent(pi.getLocation()); } } /** {@collect.stats} * Overridden in Container. Must be called under TreeLock. */ boolean isSameOrAncestorOf(Component comp, boolean allowChildren) { return comp == this; } /** {@collect.stats} * Determines whether this component is showing on screen. This means * that the component must be visible, and it must be in a container * that is visible and showing. * <p> * <strong>Note:</strong> sometimes there is no way to detect whether the * {@code Component} is actually visible to the user. This can happen when: * <ul> * <li>the component has been added to a visible {@code ScrollPane} but * the {@code Component} is not currently in the scroll pane's view port. * <li>the {@code Component} is obscured by another {@code Component} or * {@code Container}. * </ul> * @return <code>true</code> if the component is showing, * <code>false</code> otherwise * @see #setVisible * @since JDK1.0 */ public boolean isShowing() { if (visible && (peer != null)) { Container parent = this.parent; return (parent == null) || parent.isShowing(); } return false; } /** {@collect.stats} * Determines whether this component is enabled. An enabled component * can respond to user input and generate events. Components are * enabled initially by default. A component may be enabled or disabled by * calling its <code>setEnabled</code> method. * @return <code>true</code> if the component is enabled, * <code>false</code> otherwise * @see #setEnabled * @since JDK1.0 */ public boolean isEnabled() { return isEnabledImpl(); } /* * This is called by the native code, so client code can't * be called on the toolkit thread. */ final boolean isEnabledImpl() { return enabled; } /** {@collect.stats} * Enables or disables this component, depending on the value of the * parameter <code>b</code>. An enabled component can respond to user * input and generate events. Components are enabled initially by default. * * <p>Note: Disabling a lightweight component does not prevent it from * receiving MouseEvents. * <p>Note: Disabling a heavyweight container prevents all components * in this container from receiving any input events. But disabling a * lightweight container affects only this container. * * @param b If <code>true</code>, this component is * enabled; otherwise this component is disabled * @see #isEnabled * @see #isLightweight * @since JDK1.1 */ public void setEnabled(boolean b) { enable(b); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>setEnabled(boolean)</code>. */ @Deprecated public void enable() { if (!enabled) { synchronized (getTreeLock()) { enabled = true; ComponentPeer peer = this.peer; if (peer != null) { peer.enable(); if (visible) { updateCursorImmediately(); } } } if (accessibleContext != null) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_STATE_PROPERTY, null, AccessibleState.ENABLED); } } } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>setEnabled(boolean)</code>. */ @Deprecated public void enable(boolean b) { if (b) { enable(); } else { disable(); } } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>setEnabled(boolean)</code>. */ @Deprecated public void disable() { if (enabled) { KeyboardFocusManager.clearMostRecentFocusOwner(this); synchronized (getTreeLock()) { enabled = false; if (isFocusOwner()) { // Don't clear the global focus owner. If transferFocus // fails, we want the focus to stay on the disabled // Component so that keyboard traversal, et. al. still // makes sense to the user. autoTransferFocus(false); } ComponentPeer peer = this.peer; if (peer != null) { peer.disable(); if (visible) { updateCursorImmediately(); } } } if (accessibleContext != null) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_STATE_PROPERTY, null, AccessibleState.ENABLED); } } } /** {@collect.stats} * Returns true if this component is painted to an offscreen image * ("buffer") that's copied to the screen later. Component * subclasses that support double buffering should override this * method to return true if double buffering is enabled. * * @return false by default */ public boolean isDoubleBuffered() { return false; } /** {@collect.stats} * Enables or disables input method support for this component. If input * method support is enabled and the component also processes key events, * incoming events are offered to * the current input method and will only be processed by the component or * dispatched to its listeners if the input method does not consume them. * By default, input method support is enabled. * * @param enable true to enable, false to disable * @see #processKeyEvent * @since 1.2 */ public void enableInputMethods(boolean enable) { if (enable) { if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) return; // If this component already has focus, then activate the // input method by dispatching a synthesized focus gained // event. if (isFocusOwner()) { InputContext inputContext = getInputContext(); if (inputContext != null) { FocusEvent focusGainedEvent = new FocusEvent(this, FocusEvent.FOCUS_GAINED); inputContext.dispatchEvent(focusGainedEvent); } } eventMask |= AWTEvent.INPUT_METHODS_ENABLED_MASK; } else { if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) { InputContext inputContext = getInputContext(); if (inputContext != null) { inputContext.endComposition(); inputContext.removeNotify(this); } } eventMask &= ~AWTEvent.INPUT_METHODS_ENABLED_MASK; } } /** {@collect.stats} * Shows or hides this component depending on the value of parameter * <code>b</code>. * @param b if <code>true</code>, shows this component; * otherwise, hides this component * @see #isVisible * @since JDK1.1 */ public void setVisible(boolean b) { show(b); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>setVisible(boolean)</code>. */ @Deprecated public void show() { if (!visible) { synchronized (getTreeLock()) { visible = true; mixOnShowing(); ComponentPeer peer = this.peer; if (peer != null) { peer.show(); createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, this, parent, HierarchyEvent.SHOWING_CHANGED, Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)); if (peer instanceof LightweightPeer) { repaint(); } updateCursorImmediately(); } if (componentListener != null || (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) { ComponentEvent e = new ComponentEvent(this, ComponentEvent.COMPONENT_SHOWN); Toolkit.getEventQueue().postEvent(e); } } Container parent = this.parent; if (parent != null) { parent.invalidate(); } } } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>setVisible(boolean)</code>. */ @Deprecated public void show(boolean b) { if (b) { show(); } else { hide(); } } boolean containsFocus() { return isFocusOwner(); } void clearMostRecentFocusOwnerOnHide() { KeyboardFocusManager.clearMostRecentFocusOwner(this); } void clearCurrentFocusCycleRootOnHide() { /* do nothing */ } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>setVisible(boolean)</code>. */ @Deprecated public void hide() { isPacked = false; if (visible) { clearCurrentFocusCycleRootOnHide(); clearMostRecentFocusOwnerOnHide(); synchronized (getTreeLock()) { visible = false; mixOnHiding(isLightweight()); if (containsFocus()) { autoTransferFocus(true); } ComponentPeer peer = this.peer; if (peer != null) { peer.hide(); createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, this, parent, HierarchyEvent.SHOWING_CHANGED, Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)); if (peer instanceof LightweightPeer) { repaint(); } updateCursorImmediately(); } if (componentListener != null || (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) { ComponentEvent e = new ComponentEvent(this, ComponentEvent.COMPONENT_HIDDEN); Toolkit.getEventQueue().postEvent(e); } } Container parent = this.parent; if (parent != null) { parent.invalidate(); } } } /** {@collect.stats} * Gets the foreground color of this component. * @return this component's foreground color; if this component does * not have a foreground color, the foreground color of its parent * is returned * @see #setForeground * @since JDK1.0 * @beaninfo * bound: true */ public Color getForeground() { Color foreground = this.foreground; if (foreground != null) { return foreground; } Container parent = this.parent; return (parent != null) ? parent.getForeground() : null; } /** {@collect.stats} * Sets the foreground color of this component. * @param c the color to become this component's * foreground color; if this parameter is <code>null</code> * then this component will inherit * the foreground color of its parent * @see #getForeground * @since JDK1.0 */ public void setForeground(Color c) { Color oldColor = foreground; ComponentPeer peer = this.peer; foreground = c; if (peer != null) { c = getForeground(); if (c != null) { peer.setForeground(c); } } // This is a bound property, so report the change to // any registered listeners. (Cheap if there are none.) firePropertyChange("foreground", oldColor, c); } /** {@collect.stats} * Returns whether the foreground color has been explicitly set for this * Component. If this method returns <code>false</code>, this Component is * inheriting its foreground color from an ancestor. * * @return <code>true</code> if the foreground color has been explicitly * set for this Component; <code>false</code> otherwise. * @since 1.4 */ public boolean isForegroundSet() { return (foreground != null); } /** {@collect.stats} * Gets the background color of this component. * @return this component's background color; if this component does * not have a background color, * the background color of its parent is returned * @see #setBackground * @since JDK1.0 */ public Color getBackground() { Color background = this.background; if (background != null) { return background; } Container parent = this.parent; return (parent != null) ? parent.getBackground() : null; } /** {@collect.stats} * Sets the background color of this component. * <p> * The background color affects each component differently and the * parts of the component that are affected by the background color * may differ between operating systems. * * @param c the color to become this component's color; * if this parameter is <code>null</code>, then this * component will inherit the background color of its parent * @see #getBackground * @since JDK1.0 * @beaninfo * bound: true */ public void setBackground(Color c) { Color oldColor = background; ComponentPeer peer = this.peer; background = c; if (peer != null) { c = getBackground(); if (c != null) { peer.setBackground(c); } } // This is a bound property, so report the change to // any registered listeners. (Cheap if there are none.) firePropertyChange("background", oldColor, c); } /** {@collect.stats} * Returns whether the background color has been explicitly set for this * Component. If this method returns <code>false</code>, this Component is * inheriting its background color from an ancestor. * * @return <code>true</code> if the background color has been explicitly * set for this Component; <code>false</code> otherwise. * @since 1.4 */ public boolean isBackgroundSet() { return (background != null); } /** {@collect.stats} * Gets the font of this component. * @return this component's font; if a font has not been set * for this component, the font of its parent is returned * @see #setFont * @since JDK1.0 */ public Font getFont() { return getFont_NoClientCode(); } // NOTE: This method may be called by privileged threads. // This functionality is implemented in a package-private method // to insure that it cannot be overridden by client subclasses. // DO NOT INVOKE CLIENT CODE ON THIS THREAD! final Font getFont_NoClientCode() { Font font = this.font; if (font != null) { return font; } Container parent = this.parent; return (parent != null) ? parent.getFont_NoClientCode() : null; } /** {@collect.stats} * Sets the font of this component. * @param f the font to become this component's font; * if this parameter is <code>null</code> then this * component will inherit the font of its parent * @see #getFont * @since JDK1.0 * @beaninfo * bound: true */ public void setFont(Font f) { Font oldFont, newFont; synchronized(getTreeLock()) { synchronized (this) { oldFont = font; newFont = font = f; } ComponentPeer peer = this.peer; if (peer != null) { f = getFont(); if (f != null) { peer.setFont(f); peerFont = f; } } } // This is a bound property, so report the change to // any registered listeners. (Cheap if there are none.) firePropertyChange("font", oldFont, newFont); // This could change the preferred size of the Component. // Fix for 6213660. Should compare old and new fonts and do not // call invalidate() if they are equal. if (valid && f != oldFont && (oldFont == null || !oldFont.equals(f))) { invalidate(); } } /** {@collect.stats} * Returns whether the font has been explicitly set for this Component. If * this method returns <code>false</code>, this Component is inheriting its * font from an ancestor. * * @return <code>true</code> if the font has been explicitly set for this * Component; <code>false</code> otherwise. * @since 1.4 */ public boolean isFontSet() { return (font != null); } /** {@collect.stats} * Gets the locale of this component. * @return this component's locale; if this component does not * have a locale, the locale of its parent is returned * @see #setLocale * @exception IllegalComponentStateException if the <code>Component</code> * does not have its own locale and has not yet been added to * a containment hierarchy such that the locale can be determined * from the containing parent * @since JDK1.1 */ public Locale getLocale() { Locale locale = this.locale; if (locale != null) { return locale; } Container parent = this.parent; if (parent == null) { throw new IllegalComponentStateException("This component must have a parent in order to determine its locale"); } else { return parent.getLocale(); } } /** {@collect.stats} * Sets the locale of this component. This is a bound property. * @param l the locale to become this component's locale * @see #getLocale * @since JDK1.1 */ public void setLocale(Locale l) { Locale oldValue = locale; locale = l; // This is a bound property, so report the change to // any registered listeners. (Cheap if there are none.) firePropertyChange("locale", oldValue, l); // This could change the preferred size of the Component. if (valid) { invalidate(); } } /** {@collect.stats} * Gets the instance of <code>ColorModel</code> used to display * the component on the output device. * @return the color model used by this component * @see java.awt.image.ColorModel * @see java.awt.peer.ComponentPeer#getColorModel() * @see Toolkit#getColorModel() * @since JDK1.0 */ public ColorModel getColorModel() { ComponentPeer peer = this.peer; if ((peer != null) && ! (peer instanceof LightweightPeer)) { return peer.getColorModel(); } else if (GraphicsEnvironment.isHeadless()) { return ColorModel.getRGBdefault(); } // else return getToolkit().getColorModel(); } /** {@collect.stats} * Gets the location of this component in the form of a * point specifying the component's top-left corner. * The location will be relative to the parent's coordinate space. * <p> * Due to the asynchronous nature of native event handling, this * method can return outdated values (for instance, after several calls * of <code>setLocation()</code> in rapid succession). For this * reason, the recommended method of obtaining a component's position is * within <code>java.awt.event.ComponentListener.componentMoved()</code>, * which is called after the operating system has finished moving the * component. * </p> * @return an instance of <code>Point</code> representing * the top-left corner of the component's bounds in * the coordinate space of the component's parent * @see #setLocation * @see #getLocationOnScreen * @since JDK1.1 */ public Point getLocation() { return location(); } /** {@collect.stats} * Gets the location of this component in the form of a point * specifying the component's top-left corner in the screen's * coordinate space. * @return an instance of <code>Point</code> representing * the top-left corner of the component's bounds in the * coordinate space of the screen * @throws <code>IllegalComponentStateException</code> if the * component is not showing on the screen * @see #setLocation * @see #getLocation */ public Point getLocationOnScreen() { synchronized (getTreeLock()) { return getLocationOnScreen_NoTreeLock(); } } /* * a package private version of getLocationOnScreen * used by GlobalCursormanager to update cursor */ final Point getLocationOnScreen_NoTreeLock() { if (peer != null && isShowing()) { if (peer instanceof LightweightPeer) { // lightweight component location needs to be translated // relative to a native component. Container host = getNativeContainer(); Point pt = host.peer.getLocationOnScreen(); for(Component c = this; c != host; c = c.getParent()) { pt.x += c.x; pt.y += c.y; } return pt; } else { Point pt = peer.getLocationOnScreen(); return pt; } } else { throw new IllegalComponentStateException("component must be showing on the screen to determine its location"); } } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>getLocation()</code>. */ @Deprecated public Point location() { return location_NoClientCode(); } private Point location_NoClientCode() { return new Point(x, y); } /** {@collect.stats} * Moves this component to a new location. The top-left corner of * the new location is specified by the <code>x</code> and <code>y</code> * parameters in the coordinate space of this component's parent. * @param x the <i>x</i>-coordinate of the new location's * top-left corner in the parent's coordinate space * @param y the <i>y</i>-coordinate of the new location's * top-left corner in the parent's coordinate space * @see #getLocation * @see #setBounds * @since JDK1.1 */ public void setLocation(int x, int y) { move(x, y); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>setLocation(int, int)</code>. */ @Deprecated public void move(int x, int y) { synchronized(getTreeLock()) { setBoundsOp(ComponentPeer.SET_LOCATION); setBounds(x, y, width, height); } } /** {@collect.stats} * Moves this component to a new location. The top-left corner of * the new location is specified by point <code>p</code>. Point * <code>p</code> is given in the parent's coordinate space. * @param p the point defining the top-left corner * of the new location, given in the coordinate space of this * component's parent * @see #getLocation * @see #setBounds * @since JDK1.1 */ public void setLocation(Point p) { setLocation(p.x, p.y); } /** {@collect.stats} * Returns the size of this component in the form of a * <code>Dimension</code> object. The <code>height</code> * field of the <code>Dimension</code> object contains * this component's height, and the <code>width</code> * field of the <code>Dimension</code> object contains * this component's width. * @return a <code>Dimension</code> object that indicates the * size of this component * @see #setSize * @since JDK1.1 */ public Dimension getSize() { return size(); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>getSize()</code>. */ @Deprecated public Dimension size() { return new Dimension(width, height); } /** {@collect.stats} * Resizes this component so that it has width <code>width</code> * and height <code>height</code>. * @param width the new width of this component in pixels * @param height the new height of this component in pixels * @see #getSize * @see #setBounds * @since JDK1.1 */ public void setSize(int width, int height) { resize(width, height); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>setSize(int, int)</code>. */ @Deprecated public void resize(int width, int height) { synchronized(getTreeLock()) { setBoundsOp(ComponentPeer.SET_SIZE); setBounds(x, y, width, height); } } /** {@collect.stats} * Resizes this component so that it has width <code>d.width</code> * and height <code>d.height</code>. * @param d the dimension specifying the new size * of this component * @see #setSize * @see #setBounds * @since JDK1.1 */ public void setSize(Dimension d) { resize(d); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>setSize(Dimension)</code>. */ @Deprecated public void resize(Dimension d) { setSize(d.width, d.height); } /** {@collect.stats} * Gets the bounds of this component in the form of a * <code>Rectangle</code> object. The bounds specify this * component's width, height, and location relative to * its parent. * @return a rectangle indicating this component's bounds * @see #setBounds * @see #getLocation * @see #getSize */ public Rectangle getBounds() { return bounds(); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>getBounds()</code>. */ @Deprecated public Rectangle bounds() { return new Rectangle(x, y, width, height); } /** {@collect.stats} * Moves and resizes this component. The new location of the top-left * corner is specified by <code>x</code> and <code>y</code>, and the * new size is specified by <code>width</code> and <code>height</code>. * @param x the new <i>x</i>-coordinate of this component * @param y the new <i>y</i>-coordinate of this component * @param width the new <code>width</code> of this component * @param height the new <code>height</code> of this * component * @see #getBounds * @see #setLocation(int, int) * @see #setLocation(Point) * @see #setSize(int, int) * @see #setSize(Dimension) * @since JDK1.1 */ public void setBounds(int x, int y, int width, int height) { reshape(x, y, width, height); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>setBounds(int, int, int, int)</code>. */ @Deprecated public void reshape(int x, int y, int width, int height) { synchronized (getTreeLock()) { try { setBoundsOp(ComponentPeer.SET_BOUNDS); boolean resized = (this.width != width) || (this.height != height); boolean moved = (this.x != x) || (this.y != y); if (!resized && !moved) { return; } int oldX = this.x; int oldY = this.y; int oldWidth = this.width; int oldHeight = this.height; this.x = x; this.y = y; this.width = width; this.height = height; if (resized) { isPacked = false; } boolean needNotify = true; mixOnReshaping(); if (peer != null) { // LightwightPeer is an empty stub so can skip peer.reshape if (!(peer instanceof LightweightPeer)) { reshapeNativePeer(x, y, width, height, getBoundsOp()); // Check peer actualy changed coordinates resized = (oldWidth != this.width) || (oldHeight != this.height); moved = (oldX != this.x) || (oldY != this.y); // fix for 5025858: do not send ComponentEvents for toplevel // windows here as it is done from peer or native code when // the window is really resized or moved, otherwise some // events may be sent twice if (this instanceof Window) { needNotify = false; } } if (resized) { invalidate(); } if (parent != null && parent.valid) { parent.invalidate(); } } if (needNotify) { notifyNewBounds(resized, moved); } repaintParentIfNeeded(oldX, oldY, oldWidth, oldHeight); } finally { setBoundsOp(ComponentPeer.RESET_OPERATION); } } } private void repaintParentIfNeeded(int oldX, int oldY, int oldWidth, int oldHeight) { if (parent != null && peer instanceof LightweightPeer && isShowing()) { // Have the parent redraw the area this component occupied. parent.repaint(oldX, oldY, oldWidth, oldHeight); // Have the parent redraw the area this component *now* occupies. repaint(); } } private void reshapeNativePeer(int x, int y, int width, int height, int op) { // native peer might be offset by more than direct // parent since parent might be lightweight. int nativeX = x; int nativeY = y; for (Component c = parent; (c != null) && (c.peer instanceof LightweightPeer); c = c.parent) { nativeX += c.x; nativeY += c.y; } peer.setBounds(nativeX, nativeY, width, height, op); } private void notifyNewBounds(boolean resized, boolean moved) { if (componentListener != null || (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) { if (resized) { ComponentEvent e = new ComponentEvent(this, ComponentEvent.COMPONENT_RESIZED); Toolkit.getEventQueue().postEvent(e); } if (moved) { ComponentEvent e = new ComponentEvent(this, ComponentEvent.COMPONENT_MOVED); Toolkit.getEventQueue().postEvent(e); } } else { if (this instanceof Container && ((Container)this).ncomponents > 0) { boolean enabledOnToolkit = Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK); if (resized) { ((Container)this).createChildHierarchyEvents( HierarchyEvent.ANCESTOR_RESIZED, 0, enabledOnToolkit); } if (moved) { ((Container)this).createChildHierarchyEvents( HierarchyEvent.ANCESTOR_MOVED, 0, enabledOnToolkit); } } } } /** {@collect.stats} * Moves and resizes this component to conform to the new * bounding rectangle <code>r</code>. This component's new * position is specified by <code>r.x</code> and <code>r.y</code>, * and its new size is specified by <code>r.width</code> and * <code>r.height</code> * @param r the new bounding rectangle for this component * @see #getBounds * @see #setLocation(int, int) * @see #setLocation(Point) * @see #setSize(int, int) * @see #setSize(Dimension) * @since JDK1.1 */ public void setBounds(Rectangle r) { setBounds(r.x, r.y, r.width, r.height); } /** {@collect.stats} * Returns the current x coordinate of the components origin. * This method is preferable to writing * <code>component.getBounds().x</code>, * or <code>component.getLocation().x</code> because it doesn't * cause any heap allocations. * * @return the current x coordinate of the components origin * @since 1.2 */ public int getX() { return x; } /** {@collect.stats} * Returns the current y coordinate of the components origin. * This method is preferable to writing * <code>component.getBounds().y</code>, * or <code>component.getLocation().y</code> because it * doesn't cause any heap allocations. * * @return the current y coordinate of the components origin * @since 1.2 */ public int getY() { return y; } /** {@collect.stats} * Returns the current width of this component. * This method is preferable to writing * <code>component.getBounds().width</code>, * or <code>component.getSize().width</code> because it * doesn't cause any heap allocations. * * @return the current width of this component * @since 1.2 */ public int getWidth() { return width; } /** {@collect.stats} * Returns the current height of this component. * This method is preferable to writing * <code>component.getBounds().height</code>, * or <code>component.getSize().height</code> because it * doesn't cause any heap allocations. * * @return the current height of this component * @since 1.2 */ public int getHeight() { return height; } /** {@collect.stats} * Stores the bounds of this component into "return value" <b>rv</b> and * return <b>rv</b>. If rv is <code>null</code> a new * <code>Rectangle</code> is allocated. * This version of <code>getBounds</code> is useful if the caller * wants to avoid allocating a new <code>Rectangle</code> object * on the heap. * * @param rv the return value, modified to the components bounds * @return rv */ public Rectangle getBounds(Rectangle rv) { if (rv == null) { return new Rectangle(getX(), getY(), getWidth(), getHeight()); } else { rv.setBounds(getX(), getY(), getWidth(), getHeight()); return rv; } } /** {@collect.stats} * Stores the width/height of this component into "return value" <b>rv</b> * and return <b>rv</b>. If rv is <code>null</code> a new * <code>Dimension</code> object is allocated. This version of * <code>getSize</code> is useful if the caller wants to avoid * allocating a new <code>Dimension</code> object on the heap. * * @param rv the return value, modified to the components size * @return rv */ public Dimension getSize(Dimension rv) { if (rv == null) { return new Dimension(getWidth(), getHeight()); } else { rv.setSize(getWidth(), getHeight()); return rv; } } /** {@collect.stats} * Stores the x,y origin of this component into "return value" <b>rv</b> * and return <b>rv</b>. If rv is <code>null</code> a new * <code>Point</code> is allocated. * This version of <code>getLocation</code> is useful if the * caller wants to avoid allocating a new <code>Point</code> * object on the heap. * * @param rv the return value, modified to the components location * @return rv */ public Point getLocation(Point rv) { if (rv == null) { return new Point(getX(), getY()); } else { rv.setLocation(getX(), getY()); return rv; } } /** {@collect.stats} * Returns true if this component is completely opaque, returns * false by default. * <p> * An opaque component paints every pixel within its * rectangular region. A non-opaque component paints only some of * its pixels, allowing the pixels underneath it to "show through". * A component that does not fully paint its pixels therefore * provides a degree of transparency. Only lightweight * components can be transparent. * <p> * Subclasses that guarantee to always completely paint their * contents should override this method and return true. All * of the "heavyweight" AWT components are opaque. * * @return true if this component is completely opaque * @see #isLightweight * @since 1.2 */ public boolean isOpaque() { if (getPeer() == null) { return false; } else { return !isLightweight(); } } /** {@collect.stats} * A lightweight component doesn't have a native toolkit peer. * Subclasses of <code>Component</code> and <code>Container</code>, * other than the ones defined in this package like <code>Button</code> * or <code>Scrollbar</code>, are lightweight. * All of the Swing components are lightweights. * <p> * This method will always return <code>false</code> if this component * is not displayable because it is impossible to determine the * weight of an undisplayable component. * * @return true if this component has a lightweight peer; false if * it has a native peer or no peer * @see #isDisplayable * @since 1.2 */ public boolean isLightweight() { return getPeer() instanceof LightweightPeer; } /** {@collect.stats} * Sets the preferred size of this component to a constant * value. Subsequent calls to <code>getPreferredSize</code> will always * return this value. Setting the preferred size to <code>null</code> * restores the default behavior. * * @param preferredSize The new preferred size, or null * @see #getPreferredSize * @see #isPreferredSizeSet * @since 1.5 */ public void setPreferredSize(Dimension preferredSize) { Dimension old; // If the preferred size was set, use it as the old value, otherwise // use null to indicate we didn't previously have a set preferred // size. if (prefSizeSet) { old = this.prefSize; } else { old = null; } this.prefSize = preferredSize; prefSizeSet = (preferredSize != null); firePropertyChange("preferredSize", old, preferredSize); } /** {@collect.stats} * Returns true if the preferred size has been set to a * non-<code>null</code> value otherwise returns false. * * @return true if <code>setPreferredSize</code> has been invoked * with a non-null value. * @since 1.5 */ public boolean isPreferredSizeSet() { return prefSizeSet; } /** {@collect.stats} * Gets the preferred size of this component. * @return a dimension object indicating this component's preferred size * @see #getMinimumSize * @see LayoutManager */ public Dimension getPreferredSize() { return preferredSize(); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>getPreferredSize()</code>. */ @Deprecated public Dimension preferredSize() { /* Avoid grabbing the lock if a reasonable cached size value * is available. */ Dimension dim = prefSize; if (dim == null || !(isPreferredSizeSet() || isValid())) { synchronized (getTreeLock()) { prefSize = (peer != null) ? peer.preferredSize() : getMinimumSize(); dim = prefSize; } } return new Dimension(dim); } /** {@collect.stats} * Sets the minimum size of this component to a constant * value. Subsequent calls to <code>getMinimumSize</code> will always * return this value. Setting the minimum size to <code>null</code> * restores the default behavior. * * @param minimumSize the new minimum size of this component * @see #getMinimumSize * @see #isMinimumSizeSet * @since 1.5 */ public void setMinimumSize(Dimension minimumSize) { Dimension old; // If the minimum size was set, use it as the old value, otherwise // use null to indicate we didn't previously have a set minimum // size. if (minSizeSet) { old = this.minSize; } else { old = null; } this.minSize = minimumSize; minSizeSet = (minimumSize != null); firePropertyChange("minimumSize", old, minimumSize); } /** {@collect.stats} * Returns whether or not <code>setMinimumSize</code> has been * invoked with a non-null value. * * @return true if <code>setMinimumSize</code> has been invoked with a * non-null value. * @since 1.5 */ public boolean isMinimumSizeSet() { return minSizeSet; } /** {@collect.stats} * Gets the mininimum size of this component. * @return a dimension object indicating this component's minimum size * @see #getPreferredSize * @see LayoutManager */ public Dimension getMinimumSize() { return minimumSize(); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>getMinimumSize()</code>. */ @Deprecated public Dimension minimumSize() { /* Avoid grabbing the lock if a reasonable cached size value * is available. */ Dimension dim = minSize; if (dim == null || !(isMinimumSizeSet() || isValid())) { synchronized (getTreeLock()) { minSize = (peer != null) ? peer.minimumSize() : size(); dim = minSize; } } return new Dimension(dim); } /** {@collect.stats} * Sets the maximum size of this component to a constant * value. Subsequent calls to <code>getMaximumSize</code> will always * return this value. Setting the maximum size to <code>null</code> * restores the default behavior. * * @param maximumSize a <code>Dimension</code> containing the * desired maximum allowable size * @see #getMaximumSize * @see #isMaximumSizeSet * @since 1.5 */ public void setMaximumSize(Dimension maximumSize) { // If the maximum size was set, use it as the old value, otherwise // use null to indicate we didn't previously have a set maximum // size. Dimension old; if (maxSizeSet) { old = this.maxSize; } else { old = null; } this.maxSize = maximumSize; maxSizeSet = (maximumSize != null); firePropertyChange("maximumSize", old, maximumSize); } /** {@collect.stats} * Returns true if the maximum size has been set to a non-<code>null</code> * value otherwise returns false. * * @return true if <code>maximumSize</code> is non-<code>null</code>, * false otherwise * @since 1.5 */ public boolean isMaximumSizeSet() { return maxSizeSet; } /** {@collect.stats} * Gets the maximum size of this component. * @return a dimension object indicating this component's maximum size * @see #getMinimumSize * @see #getPreferredSize * @see LayoutManager */ public Dimension getMaximumSize() { if (isMaximumSizeSet()) { return new Dimension(maxSize); } return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE); } /** {@collect.stats} * Returns the alignment along the x axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getAlignmentX() { return CENTER_ALIGNMENT; } /** {@collect.stats} * Returns the alignment along the y axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getAlignmentY() { return CENTER_ALIGNMENT; } /** {@collect.stats} * Returns the baseline. The baseline is measured from the top of * the component. This method is primarily meant for * <code>LayoutManager</code>s to align components along their * baseline. A return value less than 0 indicates this component * does not have a reasonable baseline and that * <code>LayoutManager</code>s should not align this component on * its baseline. * <p> * The default implementation returns -1. Subclasses that support * baseline should override appropriately. If a value &gt;= 0 is * returned, then the component has a valid baseline for any * size &gt;= the minimum size and <code>getBaselineResizeBehavior</code> * can be used to determine how the baseline changes with size. * * @param width the width to get the baseline for * @param height the height to get the baseline for * @return the baseline or &lt; 0 indicating there is no reasonable * baseline * @throws IllegalArgumentException if width or height is &lt; 0 * @see #getBaselineResizeBehavior * @see java.awt.FontMetrics * @since 1.6 */ public int getBaseline(int width, int height) { if (width < 0 || height < 0) { throw new IllegalArgumentException( "Width and height must be >= 0"); } return -1; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. This method is primarily meant for * layout managers and GUI builders. * <p> * The default implementation returns * <code>BaselineResizeBehavior.OTHER</code>. Subclasses that have a * baseline should override appropriately. Subclasses should * never return <code>null</code>; if the baseline can not be * calculated return <code>BaselineResizeBehavior.OTHER</code>. Callers * should first ask for the baseline using * <code>getBaseline</code> and if a value &gt;= 0 is returned use * this method. It is acceptable for this method to return a * value other than <code>BaselineResizeBehavior.OTHER</code> even if * <code>getBaseline</code> returns a value less than 0. * * @return an enum indicating how the baseline changes as the component * size changes * @see #getBaseline(int, int) * @since 1.6 */ public BaselineResizeBehavior getBaselineResizeBehavior() { return BaselineResizeBehavior.OTHER; } /** {@collect.stats} * Prompts the layout manager to lay out this component. This is * usually called when the component (more specifically, container) * is validated. * @see #validate * @see LayoutManager */ public void doLayout() { layout(); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>doLayout()</code>. */ @Deprecated public void layout() { } /** {@collect.stats} * Ensures that this component has a valid layout. This method is * primarily intended to operate on instances of <code>Container</code>. * @see #invalidate * @see #doLayout() * @see LayoutManager * @see Container#validate * @since JDK1.0 */ public void validate() { synchronized (getTreeLock()) { ComponentPeer peer = this.peer; if (!valid && peer != null) { Font newfont = getFont(); Font oldfont = peerFont; if (newfont != oldfont && (oldfont == null || !oldfont.equals(newfont))) { peer.setFont(newfont); peerFont = newfont; } peer.layout(); } valid = true; } } /** {@collect.stats} * Invalidates this component. This component and all parents * above it are marked as needing to be laid out. This method can * be called often, so it needs to execute quickly. * @see #validate * @see #doLayout * @see LayoutManager * @since JDK1.0 */ public void invalidate() { synchronized (getTreeLock()) { /* Nullify cached layout and size information. * For efficiency, propagate invalidate() upwards only if * some other component hasn't already done so first. */ valid = false; if (!isPreferredSizeSet()) { prefSize = null; } if (!isMinimumSizeSet()) { minSize = null; } if (!isMaximumSizeSet()) { maxSize = null; } if (parent != null && parent.valid) { parent.invalidate(); } } } /** {@collect.stats} * Creates a graphics context for this component. This method will * return <code>null</code> if this component is currently not * displayable. * @return a graphics context for this component, or <code>null</code> * if it has none * @see #paint * @since JDK1.0 */ public Graphics getGraphics() { if (peer instanceof LightweightPeer) { // This is for a lightweight component, need to // translate coordinate spaces and clip relative // to the parent. if (parent == null) return null; Graphics g = parent.getGraphics(); if (g == null) return null; if (g instanceof ConstrainableGraphics) { ((ConstrainableGraphics) g).constrain(x, y, width, height); } else { g.translate(x,y); g.setClip(0, 0, width, height); } g.setFont(getFont()); return g; } else { ComponentPeer peer = this.peer; return (peer != null) ? peer.getGraphics() : null; } } final Graphics getGraphics_NoClientCode() { ComponentPeer peer = this.peer; if (peer instanceof LightweightPeer) { // This is for a lightweight component, need to // translate coordinate spaces and clip relative // to the parent. Container parent = this.parent; if (parent == null) return null; Graphics g = parent.getGraphics_NoClientCode(); if (g == null) return null; if (g instanceof ConstrainableGraphics) { ((ConstrainableGraphics) g).constrain(x, y, width, height); } else { g.translate(x,y); g.setClip(0, 0, width, height); } g.setFont(getFont_NoClientCode()); return g; } else { return (peer != null) ? peer.getGraphics() : null; } } /** {@collect.stats} * Gets the font metrics for the specified font. * Warning: Since Font metrics are affected by the * {@link java.awt.font.FontRenderContext FontRenderContext} and * this method does not provide one, it can return only metrics for * the default render context which may not match that used when * rendering on the Component if {@link Graphics2D} functionality is being * used. Instead metrics can be obtained at rendering time by calling * {@link Graphics#getFontMetrics()} or text measurement APIs on the * {@link Font Font} class. * @param font the font for which font metrics is to be * obtained * @return the font metrics for <code>font</code> * @see #getFont * @see #getPeer * @see java.awt.peer.ComponentPeer#getFontMetrics(Font) * @see Toolkit#getFontMetrics(Font) * @since JDK1.0 */ public FontMetrics getFontMetrics(Font font) { // REMIND: PlatformFont flag should be obsolete soon... if (sun.font.FontManager.usePlatformFontMetrics()) { if (peer != null && !(peer instanceof LightweightPeer)) { return peer.getFontMetrics(font); } } return sun.font.FontDesignMetrics.getMetrics(font); } /** {@collect.stats} * Sets the cursor image to the specified cursor. This cursor * image is displayed when the <code>contains</code> method for * this component returns true for the current cursor location, and * this Component is visible, displayable, and enabled. Setting the * cursor of a <code>Container</code> causes that cursor to be displayed * within all of the container's subcomponents, except for those * that have a non-<code>null</code> cursor. * <p> * The method may have no visual effect if the Java platform * implementation and/or the native system do not support * changing the mouse cursor shape. * @param cursor One of the constants defined * by the <code>Cursor</code> class; * if this parameter is <code>null</code> * then this component will inherit * the cursor of its parent * @see #isEnabled * @see #isShowing * @see #getCursor * @see #contains * @see Toolkit#createCustomCursor * @see Cursor * @since JDK1.1 */ public void setCursor(Cursor cursor) { this.cursor = cursor; updateCursorImmediately(); } /** {@collect.stats} * Updates the cursor. May not be invoked from the native * message pump. */ final void updateCursorImmediately() { if (peer instanceof LightweightPeer) { Container nativeContainer = getNativeContainer(); if (nativeContainer == null) return; ComponentPeer cPeer = nativeContainer.getPeer(); if (cPeer != null) { cPeer.updateCursorImmediately(); } } else if (peer != null) { peer.updateCursorImmediately(); } } /** {@collect.stats} * Gets the cursor set in the component. If the component does * not have a cursor set, the cursor of its parent is returned. * If no cursor is set in the entire hierarchy, * <code>Cursor.DEFAULT_CURSOR</code> is returned. * @see #setCursor * @since JDK1.1 */ public Cursor getCursor() { return getCursor_NoClientCode(); } final Cursor getCursor_NoClientCode() { Cursor cursor = this.cursor; if (cursor != null) { return cursor; } Container parent = this.parent; if (parent != null) { return parent.getCursor_NoClientCode(); } else { return Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); } } /** {@collect.stats} * Returns whether the cursor has been explicitly set for this Component. * If this method returns <code>false</code>, this Component is inheriting * its cursor from an ancestor. * * @return <code>true</code> if the cursor has been explicitly set for this * Component; <code>false</code> otherwise. * @since 1.4 */ public boolean isCursorSet() { return (cursor != null); } /** {@collect.stats} * Paints this component. * <p> * This method is called when the contents of the component should * be painted; such as when the component is first being shown or * is damaged and in need of repair. The clip rectangle in the * <code>Graphics</code> parameter is set to the area * which needs to be painted. * Subclasses of <code>Component</code> that override this * method need not call <code>super.paint(g)</code>. * <p> * For performance reasons, <code>Component</code>s with zero width * or height aren't considered to need painting when they are first shown, * and also aren't considered to need repair. * <p> * <b>Note</b>: For more information on the paint mechanisms utilitized * by AWT and Swing, including information on how to write the most * efficient painting code, see * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. * * @param g the graphics context to use for painting * @see #update * @since JDK1.0 */ public void paint(Graphics g) { } /** {@collect.stats} * Updates this component. * <p> * If this component is not a lightweight component, the * AWT calls the <code>update</code> method in response to * a call to <code>repaint</code>. You can assume that * the background is not cleared. * <p> * The <code>update</code> method of <code>Component</code> * calls this component's <code>paint</code> method to redraw * this component. This method is commonly overridden by subclasses * which need to do additional work in response to a call to * <code>repaint</code>. * Subclasses of Component that override this method should either * call <code>super.update(g)</code>, or call <code>paint(g)</code> * directly from their <code>update</code> method. * <p> * The origin of the graphics context, its * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the * top-left corner of this component. The clipping region of the * graphics context is the bounding rectangle of this component. * * <p> * <b>Note</b>: For more information on the paint mechanisms utilitized * by AWT and Swing, including information on how to write the most * efficient painting code, see * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. * * @param g the specified context to use for updating * @see #paint * @see #repaint() * @since JDK1.0 */ public void update(Graphics g) { paint(g); } /** {@collect.stats} * Paints this component and all of its subcomponents. * <p> * The origin of the graphics context, its * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the * top-left corner of this component. The clipping region of the * graphics context is the bounding rectangle of this component. * * @param g the graphics context to use for painting * @see #paint * @since JDK1.0 */ public void paintAll(Graphics g) { if (isShowing()) { GraphicsCallback.PeerPaintCallback.getInstance(). runOneComponent(this, new Rectangle(0, 0, width, height), g, g.getClip(), GraphicsCallback.LIGHTWEIGHTS | GraphicsCallback.HEAVYWEIGHTS); } } /** {@collect.stats} * Simulates the peer callbacks into java.awt for painting of * lightweight Components. * @param g the graphics context to use for painting * @see #paintAll */ void lightweightPaint(Graphics g) { paint(g); } /** {@collect.stats} * Paints all the heavyweight subcomponents. */ void paintHeavyweightComponents(Graphics g) { } /** {@collect.stats} * Repaints this component. * <p> * If this component is a lightweight component, this method * causes a call to this component's <code>paint</code> * method as soon as possible. Otherwise, this method causes * a call to this component's <code>update</code> method as soon * as possible. * <p> * <b>Note</b>: For more information on the paint mechanisms utilitized * by AWT and Swing, including information on how to write the most * efficient painting code, see * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. * * @see #update(Graphics) * @since JDK1.0 */ public void repaint() { repaint(0, 0, 0, width, height); } /** {@collect.stats} * Repaints the component. If this component is a lightweight * component, this results in a call to <code>paint</code> * within <code>tm</code> milliseconds. * <p> * <b>Note</b>: For more information on the paint mechanisms utilitized * by AWT and Swing, including information on how to write the most * efficient painting code, see * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. * * @param tm maximum time in milliseconds before update * @see #paint * @see #update(Graphics) * @since JDK1.0 */ public void repaint(long tm) { repaint(tm, 0, 0, width, height); } /** {@collect.stats} * Repaints the specified rectangle of this component. * <p> * If this component is a lightweight component, this method * causes a call to this component's <code>paint</code> method * as soon as possible. Otherwise, this method causes a call to * this component's <code>update</code> method as soon as possible. * <p> * <b>Note</b>: For more information on the paint mechanisms utilitized * by AWT and Swing, including information on how to write the most * efficient painting code, see * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. * * @param x the <i>x</i> coordinate * @param y the <i>y</i> coordinate * @param width the width * @param height the height * @see #update(Graphics) * @since JDK1.0 */ public void repaint(int x, int y, int width, int height) { repaint(0, x, y, width, height); } /** {@collect.stats} * Repaints the specified rectangle of this component within * <code>tm</code> milliseconds. * <p> * If this component is a lightweight component, this method causes * a call to this component's <code>paint</code> method. * Otherwise, this method causes a call to this component's * <code>update</code> method. * <p> * <b>Note</b>: For more information on the paint mechanisms utilitized * by AWT and Swing, including information on how to write the most * efficient painting code, see * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. * * @param tm maximum time in milliseconds before update * @param x the <i>x</i> coordinate * @param y the <i>y</i> coordinate * @param width the width * @param height the height * @see #update(Graphics) * @since JDK1.0 */ public void repaint(long tm, int x, int y, int width, int height) { if (this.peer instanceof LightweightPeer) { // Needs to be translated to parent coordinates since // a parent native container provides the actual repaint // services. Additionally, the request is restricted to // the bounds of the component. if (parent != null) { int px = this.x + ((x < 0) ? 0 : x); int py = this.y + ((y < 0) ? 0 : y); int pwidth = (width > this.width) ? this.width : width; int pheight = (height > this.height) ? this.height : height; parent.repaint(tm, px, py, pwidth, pheight); } } else { if (isVisible() && (this.peer != null) && (width > 0) && (height > 0)) { PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE, new Rectangle(x, y, width, height)); Toolkit.getEventQueue().postEvent(e); } } } /** {@collect.stats} * Prints this component. Applications should override this method * for components that must do special processing before being * printed or should be printed differently than they are painted. * <p> * The default implementation of this method calls the * <code>paint</code> method. * <p> * The origin of the graphics context, its * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the * top-left corner of this component. The clipping region of the * graphics context is the bounding rectangle of this component. * @param g the graphics context to use for printing * @see #paint(Graphics) * @since JDK1.0 */ public void print(Graphics g) { paint(g); } /** {@collect.stats} * Prints this component and all of its subcomponents. * <p> * The origin of the graphics context, its * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the * top-left corner of this component. The clipping region of the * graphics context is the bounding rectangle of this component. * @param g the graphics context to use for printing * @see #print(Graphics) * @since JDK1.0 */ public void printAll(Graphics g) { if (isShowing()) { GraphicsCallback.PeerPrintCallback.getInstance(). runOneComponent(this, new Rectangle(0, 0, width, height), g, g.getClip(), GraphicsCallback.LIGHTWEIGHTS | GraphicsCallback.HEAVYWEIGHTS); } } /** {@collect.stats} * Simulates the peer callbacks into java.awt for printing of * lightweight Components. * @param g the graphics context to use for printing * @see #printAll */ void lightweightPrint(Graphics g) { print(g); } /** {@collect.stats} * Prints all the heavyweight subcomponents. */ void printHeavyweightComponents(Graphics g) { } private Insets getInsets_NoClientCode() { ComponentPeer peer = this.peer; if (peer instanceof ContainerPeer) { return (Insets)((ContainerPeer)peer).insets().clone(); } return new Insets(0, 0, 0, 0); } /** {@collect.stats} * Repaints the component when the image has changed. * This <code>imageUpdate</code> method of an <code>ImageObserver</code> * is called when more information about an * image which had been previously requested using an asynchronous * routine such as the <code>drawImage</code> method of * <code>Graphics</code> becomes available. * See the definition of <code>imageUpdate</code> for * more information on this method and its arguments. * <p> * The <code>imageUpdate</code> method of <code>Component</code> * incrementally draws an image on the component as more of the bits * of the image are available. * <p> * If the system property <code>awt.image.incrementaldraw</code> * is missing or has the value <code>true</code>, the image is * incrementally drawn. If the system property has any other value, * then the image is not drawn until it has been completely loaded. * <p> * Also, if incremental drawing is in effect, the value of the * system property <code>awt.image.redrawrate</code> is interpreted * as an integer to give the maximum redraw rate, in milliseconds. If * the system property is missing or cannot be interpreted as an * integer, the redraw rate is once every 100ms. * <p> * The interpretation of the <code>x</code>, <code>y</code>, * <code>width</code>, and <code>height</code> arguments depends on * the value of the <code>infoflags</code> argument. * * @param img the image being observed * @param infoflags see <code>imageUpdate</code> for more information * @param x the <i>x</i> coordinate * @param y the <i>y</i> coordinate * @param w the width * @param h the height * @return <code>false</code> if the infoflags indicate that the * image is completely loaded; <code>true</code> otherwise. * * @see java.awt.image.ImageObserver * @see Graphics#drawImage(Image, int, int, Color, java.awt.image.ImageObserver) * @see Graphics#drawImage(Image, int, int, java.awt.image.ImageObserver) * @see Graphics#drawImage(Image, int, int, int, int, Color, java.awt.image.ImageObserver) * @see Graphics#drawImage(Image, int, int, int, int, java.awt.image.ImageObserver) * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) * @since JDK1.0 */ public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) { int rate = -1; if ((infoflags & (FRAMEBITS|ALLBITS)) != 0) { rate = 0; } else if ((infoflags & SOMEBITS) != 0) { if (isInc) { rate = incRate; if (rate < 0) { rate = 0; } } } if (rate >= 0) { repaint(rate, 0, 0, width, height); } return (infoflags & (ALLBITS|ABORT)) == 0; } /** {@collect.stats} * Creates an image from the specified image producer. * @param producer the image producer * @return the image produced * @since JDK1.0 */ public Image createImage(ImageProducer producer) { ComponentPeer peer = this.peer; if ((peer != null) && ! (peer instanceof LightweightPeer)) { return peer.createImage(producer); } return getToolkit().createImage(producer); } /** {@collect.stats} * Creates an off-screen drawable image * to be used for double buffering. * @param width the specified width * @param height the specified height * @return an off-screen drawable image, which can be used for double * buffering. The return value may be <code>null</code> if the * component is not displayable. This will always happen if * <code>GraphicsEnvironment.isHeadless()</code> returns * <code>true</code>. * @see #isDisplayable * @see GraphicsEnvironment#isHeadless * @since JDK1.0 */ public Image createImage(int width, int height) { ComponentPeer peer = this.peer; if (peer instanceof LightweightPeer) { if (parent != null) { return parent.createImage(width, height); } else { return null;} } else { return (peer != null) ? peer.createImage(width, height) : null; } } /** {@collect.stats} * Creates a volatile off-screen drawable image * to be used for double buffering. * @param width the specified width. * @param height the specified height. * @return an off-screen drawable image, which can be used for double * buffering. The return value may be <code>null</code> if the * component is not displayable. This will always happen if * <code>GraphicsEnvironment.isHeadless()</code> returns * <code>true</code>. * @see java.awt.image.VolatileImage * @see #isDisplayable * @see GraphicsEnvironment#isHeadless * @since 1.4 */ public VolatileImage createVolatileImage(int width, int height) { ComponentPeer peer = this.peer; if (peer instanceof LightweightPeer) { if (parent != null) { return parent.createVolatileImage(width, height); } else { return null;} } else { return (peer != null) ? peer.createVolatileImage(width, height) : null; } } /** {@collect.stats} * Creates a volatile off-screen drawable image, with the given capabilities. * The contents of this image may be lost at any time due * to operating system issues, so the image must be managed * via the <code>VolatileImage</code> interface. * @param width the specified width. * @param height the specified height. * @param caps the image capabilities * @exception AWTException if an image with the specified capabilities cannot * be created * @return a VolatileImage object, which can be used * to manage surface contents loss and capabilities. * @see java.awt.image.VolatileImage * @since 1.4 */ public VolatileImage createVolatileImage(int width, int height, ImageCapabilities caps) throws AWTException { // REMIND : check caps return createVolatileImage(width, height); } /** {@collect.stats} * Prepares an image for rendering on this component. The image * data is downloaded asynchronously in another thread and the * appropriate screen representation of the image is generated. * @param image the <code>Image</code> for which to * prepare a screen representation * @param observer the <code>ImageObserver</code> object * to be notified as the image is being prepared * @return <code>true</code> if the image has already been fully * prepared; <code>false</code> otherwise * @since JDK1.0 */ public boolean prepareImage(Image image, ImageObserver observer) { return prepareImage(image, -1, -1, observer); } /** {@collect.stats} * Prepares an image for rendering on this component at the * specified width and height. * <p> * The image data is downloaded asynchronously in another thread, * and an appropriately scaled screen representation of the image is * generated. * @param image the instance of <code>Image</code> * for which to prepare a screen representation * @param width the width of the desired screen representation * @param height the height of the desired screen representation * @param observer the <code>ImageObserver</code> object * to be notified as the image is being prepared * @return <code>true</code> if the image has already been fully * prepared; <code>false</code> otherwise * @see java.awt.image.ImageObserver * @since JDK1.0 */ public boolean prepareImage(Image image, int width, int height, ImageObserver observer) { ComponentPeer peer = this.peer; if (peer instanceof LightweightPeer) { return (parent != null) ? parent.prepareImage(image, width, height, observer) : getToolkit().prepareImage(image, width, height, observer); } else { return (peer != null) ? peer.prepareImage(image, width, height, observer) : getToolkit().prepareImage(image, width, height, observer); } } /** {@collect.stats} * Returns the status of the construction of a screen representation * of the specified image. * <p> * This method does not cause the image to begin loading. An * application must use the <code>prepareImage</code> method * to force the loading of an image. * <p> * Information on the flags returned by this method can be found * with the discussion of the <code>ImageObserver</code> interface. * @param image the <code>Image</code> object whose status * is being checked * @param observer the <code>ImageObserver</code> * object to be notified as the image is being prepared * @return the bitwise inclusive <b>OR</b> of * <code>ImageObserver</code> flags indicating what * information about the image is currently available * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver) * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver) * @see java.awt.image.ImageObserver * @since JDK1.0 */ public int checkImage(Image image, ImageObserver observer) { return checkImage(image, -1, -1, observer); } /** {@collect.stats} * Returns the status of the construction of a screen representation * of the specified image. * <p> * This method does not cause the image to begin loading. An * application must use the <code>prepareImage</code> method * to force the loading of an image. * <p> * The <code>checkImage</code> method of <code>Component</code> * calls its peer's <code>checkImage</code> method to calculate * the flags. If this component does not yet have a peer, the * component's toolkit's <code>checkImage</code> method is called * instead. * <p> * Information on the flags returned by this method can be found * with the discussion of the <code>ImageObserver</code> interface. * @param image the <code>Image</code> object whose status * is being checked * @param width the width of the scaled version * whose status is to be checked * @param height the height of the scaled version * whose status is to be checked * @param observer the <code>ImageObserver</code> object * to be notified as the image is being prepared * @return the bitwise inclusive <b>OR</b> of * <code>ImageObserver</code> flags indicating what * information about the image is currently available * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver) * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver) * @see java.awt.image.ImageObserver * @since JDK1.0 */ public int checkImage(Image image, int width, int height, ImageObserver observer) { ComponentPeer peer = this.peer; if (peer instanceof LightweightPeer) { return (parent != null) ? parent.checkImage(image, width, height, observer) : getToolkit().checkImage(image, width, height, observer); } else { return (peer != null) ? peer.checkImage(image, width, height, observer) : getToolkit().checkImage(image, width, height, observer); } } /** {@collect.stats} * Creates a new strategy for multi-buffering on this component. * Multi-buffering is useful for rendering performance. This method * attempts to create the best strategy available with the number of * buffers supplied. It will always create a <code>BufferStrategy</code> * with that number of buffers. * A page-flipping strategy is attempted first, then a blitting strategy * using accelerated buffers. Finally, an unaccelerated blitting * strategy is used. * <p> * Each time this method is called, * the existing buffer strategy for this component is discarded. * @param numBuffers number of buffers to create, including the front buffer * @exception IllegalArgumentException if numBuffers is less than 1. * @exception IllegalStateException if the component is not displayable * @see #isDisplayable * @see Window#getBufferStrategy() * @see Canvas#getBufferStrategy() * @since 1.4 */ void createBufferStrategy(int numBuffers) { BufferCapabilities bufferCaps; if (numBuffers > 1) { // Try to create a page-flipping strategy bufferCaps = new BufferCapabilities(new ImageCapabilities(true), new ImageCapabilities(true), BufferCapabilities.FlipContents.UNDEFINED); try { createBufferStrategy(numBuffers, bufferCaps); return; // Success } catch (AWTException e) { // Failed } } // Try a blitting (but still accelerated) strategy bufferCaps = new BufferCapabilities(new ImageCapabilities(true), new ImageCapabilities(true), null); try { createBufferStrategy(numBuffers, bufferCaps); return; // Success } catch (AWTException e) { // Failed } // Try an unaccelerated blitting strategy bufferCaps = new BufferCapabilities(new ImageCapabilities(false), new ImageCapabilities(false), null); try { createBufferStrategy(numBuffers, bufferCaps); return; // Success } catch (AWTException e) { // Failed } // Code should never reach here (an unaccelerated blitting // strategy should always work) throw new InternalError("Could not create a buffer strategy"); } /** {@collect.stats} * Creates a new strategy for multi-buffering on this component with the * required buffer capabilities. This is useful, for example, if only * accelerated memory or page flipping is desired (as specified by the * buffer capabilities). * <p> * Each time this method * is called, <code>dispose</code> will be invoked on the existing * <code>BufferStrategy</code>. * @param numBuffers number of buffers to create * @param caps the required capabilities for creating the buffer strategy; * cannot be <code>null</code> * @exception AWTException if the capabilities supplied could not be * supported or met; this may happen, for example, if there is not enough * accelerated memory currently available, or if page flipping is specified * but not possible. * @exception IllegalArgumentException if numBuffers is less than 1, or if * caps is <code>null</code> * @see Window#getBufferStrategy() * @see Canvas#getBufferStrategy() * @since 1.4 */ void createBufferStrategy(int numBuffers, BufferCapabilities caps) throws AWTException { // Check arguments if (numBuffers < 1) { throw new IllegalArgumentException( "Number of buffers must be at least 1"); } if (caps == null) { throw new IllegalArgumentException("No capabilities specified"); } // Destroy old buffers if (bufferStrategy != null) { bufferStrategy.dispose(); } if (numBuffers == 1) { bufferStrategy = new SingleBufferStrategy(caps); } else { // assert numBuffers > 1; if (caps.isPageFlipping()) { bufferStrategy = new FlipSubRegionBufferStrategy(numBuffers, caps); } else { bufferStrategy = new BltSubRegionBufferStrategy(numBuffers, caps); } } } /** {@collect.stats} * @return the buffer strategy used by this component * @see Window#createBufferStrategy * @see Canvas#createBufferStrategy * @since 1.4 */ BufferStrategy getBufferStrategy() { return bufferStrategy; } /** {@collect.stats} * @return the back buffer currently used by this component's * BufferStrategy. If there is no BufferStrategy or no * back buffer, this method returns null. */ Image getBackBuffer() { if (bufferStrategy != null) { if (bufferStrategy instanceof BltBufferStrategy) { BltBufferStrategy bltBS = (BltBufferStrategy)bufferStrategy; return bltBS.getBackBuffer(); } else if (bufferStrategy instanceof FlipBufferStrategy) { FlipBufferStrategy flipBS = (FlipBufferStrategy)bufferStrategy; return flipBS.getBackBuffer(); } } return null; } /** {@collect.stats} * Inner class for flipping buffers on a component. That component must * be a <code>Canvas</code> or <code>Window</code>. * @see Canvas * @see Window * @see java.awt.image.BufferStrategy * @author Michael Martak * @since 1.4 */ protected class FlipBufferStrategy extends BufferStrategy { /** {@collect.stats} * The number of buffers */ protected int numBuffers; // = 0 /** {@collect.stats} * The buffering capabilities */ protected BufferCapabilities caps; // = null /** {@collect.stats} * The drawing buffer */ protected Image drawBuffer; // = null /** {@collect.stats} * The drawing buffer as a volatile image */ protected VolatileImage drawVBuffer; // = null /** {@collect.stats} * Whether or not the drawing buffer has been recently restored from * a lost state. */ protected boolean validatedContents; // = false /** {@collect.stats} * Size of the back buffers. (Note: these fields were added in 6.0 * but kept package-private to avoid exposing them in the spec. * None of these fields/methods really should have been marked * protected when they were introduced in 1.4, but now we just have * to live with that decision.) */ int width; int height; /** {@collect.stats} * Creates a new flipping buffer strategy for this component. * The component must be a <code>Canvas</code> or <code>Window</code>. * @see Canvas * @see Window * @param numBuffers the number of buffers * @param caps the capabilities of the buffers * @exception AWTException if the capabilities supplied could not be * supported or met * @exception ClassCastException if the component is not a canvas or * window. */ protected FlipBufferStrategy(int numBuffers, BufferCapabilities caps) throws AWTException { if (!(Component.this instanceof Window) && !(Component.this instanceof Canvas)) { throw new ClassCastException( "Component must be a Canvas or Window"); } this.numBuffers = numBuffers; this.caps = caps; createBuffers(numBuffers, caps); } /** {@collect.stats} * Creates one or more complex, flipping buffers with the given * capabilities. * @param numBuffers number of buffers to create; must be greater than * one * @param caps the capabilities of the buffers. * <code>BufferCapabilities.isPageFlipping</code> must be * <code>true</code>. * @exception AWTException if the capabilities supplied could not be * supported or met * @exception IllegalStateException if the component has no peer * @exception IllegalArgumentException if numBuffers is less than two, * or if <code>BufferCapabilities.isPageFlipping</code> is not * <code>true</code>. * @see java.awt.BufferCapabilities#isPageFlipping() */ protected void createBuffers(int numBuffers, BufferCapabilities caps) throws AWTException { if (numBuffers < 2) { throw new IllegalArgumentException( "Number of buffers cannot be less than two"); } else if (peer == null) { throw new IllegalStateException( "Component must have a valid peer"); } else if (caps == null || !caps.isPageFlipping()) { throw new IllegalArgumentException( "Page flipping capabilities must be specified"); } // save the current bounds width = getWidth(); height = getHeight(); if (drawBuffer == null) { peer.createBuffers(numBuffers, caps); } else { // dispose the existing backbuffers drawBuffer = null; drawVBuffer = null; destroyBuffers(); // ... then recreate the backbuffers peer.createBuffers(numBuffers, caps); } updateInternalBuffers(); } /** {@collect.stats} * Updates internal buffers (both volatile and non-volatile) * by requesting the back-buffer from the peer. */ private void updateInternalBuffers() { // get the images associated with the draw buffer drawBuffer = getBackBuffer(); if (drawBuffer instanceof VolatileImage) { drawVBuffer = (VolatileImage)drawBuffer; } else { drawVBuffer = null; } } /** {@collect.stats} * @return direct access to the back buffer, as an image. * @exception IllegalStateException if the buffers have not yet * been created */ protected Image getBackBuffer() { if (peer != null) { return peer.getBackBuffer(); } else { throw new IllegalStateException( "Component must have a valid peer"); } } /** {@collect.stats} * Flipping moves the contents of the back buffer to the front buffer, * either by copying or by moving the video pointer. * @param flipAction an integer value describing the flipping action * for the contents of the back buffer. This should be one of the * values of the <code>BufferCapabilities.FlipContents</code> * property. * @exception IllegalStateException if the buffers have not yet * been created * @see java.awt.BufferCapabilities#getFlipContents() */ protected void flip(BufferCapabilities.FlipContents flipAction) { if (peer != null) { peer.flip(flipAction); } else { throw new IllegalStateException( "Component must have a valid peer"); } } /** {@collect.stats} * Destroys the buffers created through this object */ protected void destroyBuffers() { if (peer != null) { peer.destroyBuffers(); } else { throw new IllegalStateException( "Component must have a valid peer"); } } /** {@collect.stats} * @return the buffering capabilities of this strategy */ public BufferCapabilities getCapabilities() { return caps; } /** {@collect.stats} * @return the graphics on the drawing buffer. This method may not * be synchronized for performance reasons; use of this method by multiple * threads should be handled at the application level. Disposal of the * graphics object must be handled by the application. */ public Graphics getDrawGraphics() { revalidate(); return drawBuffer.getGraphics(); } /** {@collect.stats} * Restore the drawing buffer if it has been lost */ protected void revalidate() { revalidate(true); } void revalidate(boolean checkSize) { validatedContents = false; if (checkSize && (getWidth() != width || getHeight() != height)) { // component has been resized; recreate the backbuffers try { createBuffers(numBuffers, caps); } catch (AWTException e) { // shouldn't be possible } validatedContents = true; } // get the buffers from the peer every time since they // might have been replaced in response to a display change event updateInternalBuffers(); // now validate the backbuffer if (drawVBuffer != null) { GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode(); int returnCode = drawVBuffer.validate(gc); if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) { try { createBuffers(numBuffers, caps); } catch (AWTException e) { // shouldn't be possible } if (drawVBuffer != null) { // backbuffers were recreated, so validate again drawVBuffer.validate(gc); } validatedContents = true; } else if (returnCode == VolatileImage.IMAGE_RESTORED) { validatedContents = true; } } } /** {@collect.stats} * @return whether the drawing buffer was lost since the last call to * <code>getDrawGraphics</code> */ public boolean contentsLost() { if (drawVBuffer == null) { return false; } return drawVBuffer.contentsLost(); } /** {@collect.stats} * @return whether the drawing buffer was recently restored from a lost * state and reinitialized to the default background color (white) */ public boolean contentsRestored() { return validatedContents; } /** {@collect.stats} * Makes the next available buffer visible by either blitting or * flipping. */ public void show() { flip(caps.getFlipContents()); } /** {@collect.stats} * {@inheritDoc} * @since 1.6 */ public void dispose() { if (Component.this.bufferStrategy == this) { Component.this.bufferStrategy = null; if (peer != null) { destroyBuffers(); } } } } // Inner class FlipBufferStrategy /** {@collect.stats} * Inner class for blitting offscreen surfaces to a component. * * @author Michael Martak * @since 1.4 */ protected class BltBufferStrategy extends BufferStrategy { /** {@collect.stats} * The buffering capabilities */ protected BufferCapabilities caps; // = null /** {@collect.stats} * The back buffers */ protected VolatileImage[] backBuffers; // = null /** {@collect.stats} * Whether or not the drawing buffer has been recently restored from * a lost state. */ protected boolean validatedContents; // = false /** {@collect.stats} * Size of the back buffers */ protected int width; protected int height; /** {@collect.stats} * Insets for the hosting Component. The size of the back buffer * is constrained by these. */ private Insets insets; /** {@collect.stats} * Creates a new blt buffer strategy around a component * @param numBuffers number of buffers to create, including the * front buffer * @param caps the capabilities of the buffers */ protected BltBufferStrategy(int numBuffers, BufferCapabilities caps) { this.caps = caps; createBackBuffers(numBuffers - 1); } /** {@collect.stats} * {@inheritDoc} * @since 1.6 */ public void dispose() { if (backBuffers != null) { for (int counter = backBuffers.length - 1; counter >= 0; counter--) { if (backBuffers[counter] != null) { backBuffers[counter].flush(); backBuffers[counter] = null; } } } if (Component.this.bufferStrategy == this) { Component.this.bufferStrategy = null; } } /** {@collect.stats} * Creates the back buffers */ protected void createBackBuffers(int numBuffers) { if (numBuffers == 0) { backBuffers = null; } else { // save the current bounds width = getWidth(); height = getHeight(); insets = getInsets_NoClientCode(); int iWidth = width - insets.left - insets.right; int iHeight = height - insets.top - insets.bottom; // It is possible for the component's width and/or height // to be 0 here. Force the size of the backbuffers to // be > 0 so that creating the image won't fail. iWidth = Math.max(1, iWidth); iHeight = Math.max(1, iHeight); if (backBuffers == null) { backBuffers = new VolatileImage[numBuffers]; } else { // flush any existing backbuffers for (int i = 0; i < numBuffers; i++) { if (backBuffers[i] != null) { backBuffers[i].flush(); backBuffers[i] = null; } } } // create the backbuffers for (int i = 0; i < numBuffers; i++) { backBuffers[i] = createVolatileImage(iWidth, iHeight); } } } /** {@collect.stats} * @return the buffering capabilities of this strategy */ public BufferCapabilities getCapabilities() { return caps; } /** {@collect.stats} * @return the draw graphics */ public Graphics getDrawGraphics() { revalidate(); Image backBuffer = getBackBuffer(); if (backBuffer == null) { return getGraphics(); } SunGraphics2D g = (SunGraphics2D)backBuffer.getGraphics(); g.constrain(-insets.left, -insets.top, backBuffer.getWidth(null) + insets.left, backBuffer.getHeight(null) + insets.top); return g; } /** {@collect.stats} * @return direct access to the back buffer, as an image. * If there is no back buffer, returns null. */ Image getBackBuffer() { if (backBuffers != null) { return backBuffers[backBuffers.length - 1]; } else { return null; } } /** {@collect.stats} * Makes the next available buffer visible. */ public void show() { showSubRegion(insets.left, insets.top, width - insets.right, height - insets.bottom); } /** {@collect.stats} * Package-private method to present a specific rectangular area * of this buffer. This class currently shows only the entire * buffer, by calling showSubRegion() with the full dimensions of * the buffer. Subclasses (e.g., BltSubRegionBufferStrategy * and FlipSubRegionBufferStrategy) may have region-specific show * methods that call this method with actual sub regions of the * buffer. */ void showSubRegion(int x1, int y1, int x2, int y2) { if (backBuffers == null) { return; } // Adjust location to be relative to client area. x1 -= insets.left; x2 -= insets.left; y1 -= insets.top; y2 -= insets.top; Graphics g = getGraphics_NoClientCode(); if (g == null) { // Not showing, bail return; } try { // First image copy is in terms of Frame's coordinates, need // to translate to client area. g.translate(insets.left, insets.top); for (int i = 0; i < backBuffers.length; i++) { g.drawImage(backBuffers[i], x1, y1, x2, y2, x1, y1, x2, y2, null); g.dispose(); g = null; g = backBuffers[i].getGraphics(); } } finally { if (g != null) { g.dispose(); } } } /** {@collect.stats} * Restore the drawing buffer if it has been lost */ protected void revalidate() { revalidate(true); } void revalidate(boolean checkSize) { validatedContents = false; if (backBuffers == null) { return; } if (checkSize) { Insets insets = getInsets_NoClientCode(); if (getWidth() != width || getHeight() != height || !insets.equals(this.insets)) { // component has been resized; recreate the backbuffers createBackBuffers(backBuffers.length); validatedContents = true; } } // now validate the backbuffer GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode(); int returnCode = backBuffers[backBuffers.length - 1].validate(gc); if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) { if (checkSize) { createBackBuffers(backBuffers.length); // backbuffers were recreated, so validate again backBuffers[backBuffers.length - 1].validate(gc); } // else case means we're called from Swing on the toolkit // thread, don't recreate buffers as that'll deadlock // (creating VolatileImages invokes getting GraphicsConfig // which grabs treelock). validatedContents = true; } else if (returnCode == VolatileImage.IMAGE_RESTORED) { validatedContents = true; } } /** {@collect.stats} * @return whether the drawing buffer was lost since the last call to * <code>getDrawGraphics</code> */ public boolean contentsLost() { if (backBuffers == null) { return false; } else { return backBuffers[backBuffers.length - 1].contentsLost(); } } /** {@collect.stats} * @return whether the drawing buffer was recently restored from a lost * state and reinitialized to the default background color (white) */ public boolean contentsRestored() { return validatedContents; } } // Inner class BltBufferStrategy /** {@collect.stats} * Private class to perform sub-region flipping. * REMIND: this subclass currently punts on subregions and * flips the entire buffer. */ private class FlipSubRegionBufferStrategy extends FlipBufferStrategy implements SubRegionShowable { protected FlipSubRegionBufferStrategy(int numBuffers, BufferCapabilities caps) throws AWTException { super(numBuffers, caps); } public void show(int x1, int y1, int x2, int y2) { show(); } // This is invoked by Swing on the toolkit thread. public boolean validateAndShow(int x1, int y1, int x2, int y2) { revalidate(false); if (!contentsRestored() && !contentsLost()) { show(); return !contentsLost(); } return false; } } /** {@collect.stats} * Private class to perform sub-region blitting. Swing will use * this subclass via the SubRegionShowable interface in order to * copy only the area changed during a repaint. * @see javax.swing.BufferStrategyPaintManager */ private class BltSubRegionBufferStrategy extends BltBufferStrategy implements SubRegionShowable { protected BltSubRegionBufferStrategy(int numBuffers, BufferCapabilities caps) { super(numBuffers, caps); } public void show(int x1, int y1, int x2, int y2) { showSubRegion(x1, y1, x2, y2); } // This method is called by Swing on the toolkit thread. public boolean validateAndShow(int x1, int y1, int x2, int y2) { revalidate(false); if (!contentsRestored() && !contentsLost()) { showSubRegion(x1, y1, x2, y2); return !contentsLost(); } return false; } } /** {@collect.stats} * Inner class for flipping buffers on a component. That component must * be a <code>Canvas</code> or <code>Window</code>. * @see Canvas * @see Window * @see java.awt.image.BufferStrategy * @author Michael Martak * @since 1.4 */ private class SingleBufferStrategy extends BufferStrategy { private BufferCapabilities caps; public SingleBufferStrategy(BufferCapabilities caps) { this.caps = caps; } public BufferCapabilities getCapabilities() { return caps; } public Graphics getDrawGraphics() { return getGraphics(); } public boolean contentsLost() { return false; } public boolean contentsRestored() { return false; } public void show() { // Do nothing } } // Inner class SingleBufferStrategy /** {@collect.stats} * Sets whether or not paint messages received from the operating system * should be ignored. This does not affect paint events generated in * software by the AWT, unless they are an immediate response to an * OS-level paint message. * <p> * This is useful, for example, if running under full-screen mode and * better performance is desired, or if page-flipping is used as the * buffer strategy. * * @since 1.4 * @see #getIgnoreRepaint * @see Canvas#createBufferStrategy * @see Window#createBufferStrategy * @see java.awt.image.BufferStrategy * @see GraphicsDevice#setFullScreenWindow */ public void setIgnoreRepaint(boolean ignoreRepaint) { this.ignoreRepaint = ignoreRepaint; } /** {@collect.stats} * @return whether or not paint messages received from the operating system * should be ignored. * * @since 1.4 * @see #setIgnoreRepaint */ public boolean getIgnoreRepaint() { return ignoreRepaint; } /** {@collect.stats} * Checks whether this component "contains" the specified point, * where <code>x</code> and <code>y</code> are defined to be * relative to the coordinate system of this component. * @param x the <i>x</i> coordinate of the point * @param y the <i>y</i> coordinate of the point * @see #getComponentAt(int, int) * @since JDK1.1 */ public boolean contains(int x, int y) { return inside(x, y); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by contains(int, int). */ @Deprecated public boolean inside(int x, int y) { return (x >= 0) && (x < width) && (y >= 0) && (y < height); } /** {@collect.stats} * Checks whether this component "contains" the specified point, * where the point's <i>x</i> and <i>y</i> coordinates are defined * to be relative to the coordinate system of this component. * @param p the point * @see #getComponentAt(Point) * @since JDK1.1 */ public boolean contains(Point p) { return contains(p.x, p.y); } /** {@collect.stats} * Determines if this component or one of its immediate * subcomponents contains the (<i>x</i>,&nbsp;<i>y</i>) location, * and if so, returns the containing component. This method only * looks one level deep. If the point (<i>x</i>,&nbsp;<i>y</i>) is * inside a subcomponent that itself has subcomponents, it does not * go looking down the subcomponent tree. * <p> * The <code>locate</code> method of <code>Component</code> simply * returns the component itself if the (<i>x</i>,&nbsp;<i>y</i>) * coordinate location is inside its bounding box, and <code>null</code> * otherwise. * @param x the <i>x</i> coordinate * @param y the <i>y</i> coordinate * @return the component or subcomponent that contains the * (<i>x</i>,&nbsp;<i>y</i>) location; * <code>null</code> if the location * is outside this component * @see #contains(int, int) * @since JDK1.0 */ public Component getComponentAt(int x, int y) { return locate(x, y); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by getComponentAt(int, int). */ @Deprecated public Component locate(int x, int y) { return contains(x, y) ? this : null; } /** {@collect.stats} * Returns the component or subcomponent that contains the * specified point. * @param p the point * @see java.awt.Component#contains * @since JDK1.1 */ public Component getComponentAt(Point p) { return getComponentAt(p.x, p.y); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by <code>dispatchEvent(AWTEvent e)</code>. */ @Deprecated public void deliverEvent(Event e) { postEvent(e); } /** {@collect.stats} * Dispatches an event to this component or one of its sub components. * Calls <code>processEvent</code> before returning for 1.1-style * events which have been enabled for the <code>Component</code>. * @param e the event */ public final void dispatchEvent(AWTEvent e) { dispatchEventImpl(e); } void dispatchEventImpl(AWTEvent e) { int id = e.getID(); // Check that this component belongs to this app-context AppContext compContext = appContext; if (compContext != null && !compContext.equals(AppContext.getAppContext())) { if (eventLog.isLoggable(Level.FINE)) { eventLog.log(Level.FINE, "Event " + e + " is being dispatched on the wrong AppContext"); } } if (eventLog.isLoggable(Level.FINEST)) { eventLog.log(Level.FINEST, "{0}", String.valueOf(e)); } /* * 0. Set timestamp and modifiers of current event. */ EventQueue.setCurrentEventAndMostRecentTime(e); /* * 1. Pre-dispatchers. Do any necessary retargeting/reordering here * before we notify AWTEventListeners. */ if (e instanceof SunDropTargetEvent) { ((SunDropTargetEvent)e).dispatch(); return; } if (!e.focusManagerIsDispatching) { // Invoke the private focus retargeting method which provides // lightweight Component support if (e.isPosted) { e = KeyboardFocusManager.retargetFocusEvent(e); e.isPosted = true; } // Now, with the event properly targeted to a lightweight // descendant if necessary, invoke the public focus retargeting // and dispatching function if (KeyboardFocusManager.getCurrentKeyboardFocusManager(). dispatchEvent(e)) { return; } } if ((e instanceof FocusEvent) && focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "" + e); } // MouseWheel may need to be retargeted here so that // AWTEventListener sees the event go to the correct // Component. If the MouseWheelEvent needs to go to an ancestor, // the event is dispatched to the ancestor, and dispatching here // stops. if (id == MouseEvent.MOUSE_WHEEL && (!eventTypeEnabled(id)) && (peer != null && !peer.handlesWheelScrolling()) && (dispatchMouseWheelToAncestor((MouseWheelEvent)e))) { return; } /* * 2. Allow the Toolkit to pass this to AWTEventListeners. */ Toolkit toolkit = Toolkit.getDefaultToolkit(); toolkit.notifyAWTEventListeners(e); /* * 3. If no one has consumed a key event, allow the * KeyboardFocusManager to process it. */ if (!e.isConsumed()) { if (e instanceof java.awt.event.KeyEvent) { KeyboardFocusManager.getCurrentKeyboardFocusManager(). processKeyEvent(this, (KeyEvent)e); if (e.isConsumed()) { return; } } } /* * 4. Allow input methods to process the event */ if (areInputMethodsEnabled()) { // We need to pass on InputMethodEvents since some host // input method adapters send them through the Java // event queue instead of directly to the component, // and the input context also handles the Java composition window if(((e instanceof InputMethodEvent) && !(this instanceof CompositionArea)) || // Otherwise, we only pass on input and focus events, because // a) input methods shouldn't know about semantic or component-level events // b) passing on the events takes time // c) isConsumed() is always true for semantic events. (e instanceof InputEvent) || (e instanceof FocusEvent)) { InputContext inputContext = getInputContext(); if (inputContext != null) { inputContext.dispatchEvent(e); if (e.isConsumed()) { if ((e instanceof FocusEvent) && focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "3579: Skipping " + e); } return; } } } } else { // When non-clients get focus, we need to explicitly disable the native // input method. The native input method is actually not disabled when // the active/passive/peered clients loose focus. if (id == FocusEvent.FOCUS_GAINED) { InputContext inputContext = getInputContext(); if (inputContext != null && inputContext instanceof sun.awt.im.InputContext) { ((sun.awt.im.InputContext)inputContext).disableNativeIM(); } } } /* * 5. Pre-process any special events before delivery */ switch(id) { // Handling of the PAINT and UPDATE events is now done in the // peer's handleEvent() method so the background can be cleared // selectively for non-native components on Windows only. // - Fred.Ecks@Eng.sun.com, 5-8-98 case KeyEvent.KEY_PRESSED: case KeyEvent.KEY_RELEASED: Container p = (Container)((this instanceof Container) ? this : parent); if (p != null) { p.preProcessKeyEvent((KeyEvent)e); if (e.isConsumed()) { if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "Pre-process consumed event"); } return; } } break; case WindowEvent.WINDOW_CLOSING: if (toolkit instanceof WindowClosingListener) { windowClosingException = ((WindowClosingListener) toolkit).windowClosingNotify((WindowEvent)e); if (checkWindowClosingException()) { return; } } break; default: break; } /* * 6. Deliver event for normal processing */ if (newEventsOnly) { // Filtering needs to really be moved to happen at a lower // level in order to get maximum performance gain; it is // here temporarily to ensure the API spec is honored. // if (eventEnabled(e)) { processEvent(e); } } else if (id == MouseEvent.MOUSE_WHEEL) { // newEventsOnly will be false for a listenerless ScrollPane, but // MouseWheelEvents still need to be dispatched to it so scrolling // can be done. autoProcessMouseWheel((MouseWheelEvent)e); } else if (!(e instanceof MouseEvent && !postsOldMouseEvents())) { // // backward compatibility // Event olde = e.convertToOld(); if (olde != null) { int key = olde.key; int modifiers = olde.modifiers; postEvent(olde); if (olde.isConsumed()) { e.consume(); } // if target changed key or modifier values, copy them // back to original event // switch(olde.id) { case Event.KEY_PRESS: case Event.KEY_RELEASE: case Event.KEY_ACTION: case Event.KEY_ACTION_RELEASE: if (olde.key != key) { ((KeyEvent)e).setKeyChar(olde.getKeyEventChar()); } if (olde.modifiers != modifiers) { ((KeyEvent)e).setModifiers(olde.modifiers); } break; default: break; } } } /* * 8. Special handling for 4061116 : Hook for browser to close modal * dialogs. */ if (id == WindowEvent.WINDOW_CLOSING && !e.isConsumed()) { if (toolkit instanceof WindowClosingListener) { windowClosingException = ((WindowClosingListener)toolkit). windowClosingDelivered((WindowEvent)e); if (checkWindowClosingException()) { return; } } } /* * 9. Allow the peer to process the event. * Except KeyEvents, they will be processed by peer after * all KeyEventPostProcessors * (see DefaultKeyboardFocusManager.dispatchKeyEvent()) */ if (!(e instanceof KeyEvent)) { ComponentPeer tpeer = peer; if (e instanceof FocusEvent && (tpeer == null || tpeer instanceof LightweightPeer)) { // if focus owner is lightweight then its native container // processes event Component source = (Component)e.getSource(); if (source != null) { Container target = source.getNativeContainer(); if (target != null) { tpeer = target.getPeer(); } } } if (tpeer != null) { tpeer.handleEvent(e); } } } // dispatchEventImpl() /* * If newEventsOnly is false, method is called so that ScrollPane can * override it and handle common-case mouse wheel scrolling. NOP * for Component. */ void autoProcessMouseWheel(MouseWheelEvent e) {} /* * Dispatch given MouseWheelEvent to the first ancestor for which * MouseWheelEvents are enabled. * * Returns whether or not event was dispatched to an ancestor */ boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) { int newX, newY; newX = e.getX() + getX(); // Coordinates take into account at least newY = e.getY() + getY(); // the cursor's position relative to this // Component (e.getX()), and this Component's // position relative to its parent. MouseWheelEvent newMWE; if (eventLog.isLoggable(Level.FINEST)) { eventLog.log(Level.FINEST, "dispatchMouseWheelToAncestor"); eventLog.log(Level.FINEST, "orig event src is of " + e.getSource().getClass()); } /* parent field for Window refers to the owning Window. * MouseWheelEvents should NOT be propagated into owning Windows */ synchronized (getTreeLock()) { Container anc = getParent(); while (anc != null && !anc.eventEnabled(e)) { // fix coordinates to be relative to new event source newX += anc.getX(); newY += anc.getY(); if (!(anc instanceof Window)) { anc = anc.getParent(); } else { break; } } if (eventLog.isLoggable(Level.FINEST)) { eventLog.log(Level.FINEST, "new event src is " + anc.getClass()); } if (anc != null && anc.eventEnabled(e)) { // Change event to be from new source, with new x,y // For now, just create a new event - yucky newMWE = new MouseWheelEvent(anc, // new source e.getID(), e.getWhen(), e.getModifiers(), newX, // x relative to new source newY, // y relative to new source e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e.getWheelRotation()); ((AWTEvent)e).copyPrivateDataInto(newMWE); // When dispatching a wheel event to // ancestor, there is no need trying to find descendant // lightweights to dispatch event to. // If we dispatch the event to toplevel ancestor, // this could encolse the loop: 6480024. anc.dispatchEventToSelf(newMWE); } } return true; } boolean checkWindowClosingException() { if (windowClosingException != null) { if (this instanceof Dialog) { ((Dialog)this).interruptBlocking(); } else { windowClosingException.fillInStackTrace(); windowClosingException.printStackTrace(); windowClosingException = null; } return true; } return false; } boolean areInputMethodsEnabled() { // in 1.2, we assume input method support is required for all // components that handle key events, but components can turn off // input methods by calling enableInputMethods(false). return ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) && ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 || keyListener != null); } // REMIND: remove when filtering is handled at lower level boolean eventEnabled(AWTEvent e) { return eventTypeEnabled(e.id); } boolean eventTypeEnabled(int type) { switch(type) { case ComponentEvent.COMPONENT_MOVED: case ComponentEvent.COMPONENT_RESIZED: case ComponentEvent.COMPONENT_SHOWN: case ComponentEvent.COMPONENT_HIDDEN: if ((eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || componentListener != null) { return true; } break; case FocusEvent.FOCUS_GAINED: case FocusEvent.FOCUS_LOST: if ((eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 || focusListener != null) { return true; } break; case KeyEvent.KEY_PRESSED: case KeyEvent.KEY_RELEASED: case KeyEvent.KEY_TYPED: if ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 || keyListener != null) { return true; } break; case MouseEvent.MOUSE_PRESSED: case MouseEvent.MOUSE_RELEASED: case MouseEvent.MOUSE_ENTERED: case MouseEvent.MOUSE_EXITED: case MouseEvent.MOUSE_CLICKED: if ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 || mouseListener != null) { return true; } break; case MouseEvent.MOUSE_MOVED: case MouseEvent.MOUSE_DRAGGED: if ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 || mouseMotionListener != null) { return true; } break; case MouseEvent.MOUSE_WHEEL: if ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 || mouseWheelListener != null) { return true; } break; case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED: case InputMethodEvent.CARET_POSITION_CHANGED: if ((eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 || inputMethodListener != null) { return true; } break; case HierarchyEvent.HIERARCHY_CHANGED: if ((eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || hierarchyListener != null) { return true; } break; case HierarchyEvent.ANCESTOR_MOVED: case HierarchyEvent.ANCESTOR_RESIZED: if ((eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 || hierarchyBoundsListener != null) { return true; } break; case ActionEvent.ACTION_PERFORMED: if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0) { return true; } break; case TextEvent.TEXT_VALUE_CHANGED: if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0) { return true; } break; case ItemEvent.ITEM_STATE_CHANGED: if ((eventMask & AWTEvent.ITEM_EVENT_MASK) != 0) { return true; } break; case AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED: if ((eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0) { return true; } break; default: break; } // // Always pass on events defined by external programs. // if (type > AWTEvent.RESERVED_ID_MAX) { return true; } return false; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by dispatchEvent(AWTEvent). */ @Deprecated public boolean postEvent(Event e) { ComponentPeer peer = this.peer; if (handleEvent(e)) { e.consume(); return true; } Component parent = this.parent; int eventx = e.x; int eventy = e.y; if (parent != null) { e.translate(x, y); if (parent.postEvent(e)) { e.consume(); return true; } // restore coords e.x = eventx; e.y = eventy; } return false; } // Event source interfaces /** {@collect.stats} * Adds the specified component listener to receive component events from * this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the component listener * @see java.awt.event.ComponentEvent * @see java.awt.event.ComponentListener * @see #removeComponentListener * @see #getComponentListeners * @since JDK1.1 */ public synchronized void addComponentListener(ComponentListener l) { if (l == null) { return; } componentListener = AWTEventMulticaster.add(componentListener, l); newEventsOnly = true; } /** {@collect.stats} * Removes the specified component listener so that it no longer * receives component events from this component. This method performs * no function, nor does it throw an exception, if the listener * specified by the argument was not previously added to this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * @param l the component listener * @see java.awt.event.ComponentEvent * @see java.awt.event.ComponentListener * @see #addComponentListener * @see #getComponentListeners * @since JDK1.1 */ public synchronized void removeComponentListener(ComponentListener l) { if (l == null) { return; } componentListener = AWTEventMulticaster.remove(componentListener, l); } /** {@collect.stats} * Returns an array of all the component listeners * registered on this component. * * @return all of this comonent's <code>ComponentListener</code>s * or an empty array if no component * listeners are currently registered * * @see #addComponentListener * @see #removeComponentListener * @since 1.4 */ public synchronized ComponentListener[] getComponentListeners() { return (ComponentListener[]) (getListeners(ComponentListener.class)); } /** {@collect.stats} * Adds the specified focus listener to receive focus events from * this component when this component gains input focus. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the focus listener * @see java.awt.event.FocusEvent * @see java.awt.event.FocusListener * @see #removeFocusListener * @see #getFocusListeners * @since JDK1.1 */ public synchronized void addFocusListener(FocusListener l) { if (l == null) { return; } focusListener = AWTEventMulticaster.add(focusListener, l); newEventsOnly = true; // if this is a lightweight component, enable focus events // in the native container. if (peer instanceof LightweightPeer) { parent.proxyEnableEvents(AWTEvent.FOCUS_EVENT_MASK); } } /** {@collect.stats} * Removes the specified focus listener so that it no longer * receives focus events from this component. This method performs * no function, nor does it throw an exception, if the listener * specified by the argument was not previously added to this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the focus listener * @see java.awt.event.FocusEvent * @see java.awt.event.FocusListener * @see #addFocusListener * @see #getFocusListeners * @since JDK1.1 */ public synchronized void removeFocusListener(FocusListener l) { if (l == null) { return; } focusListener = AWTEventMulticaster.remove(focusListener, l); } /** {@collect.stats} * Returns an array of all the focus listeners * registered on this component. * * @return all of this component's <code>FocusListener</code>s * or an empty array if no component * listeners are currently registered * * @see #addFocusListener * @see #removeFocusListener * @since 1.4 */ public synchronized FocusListener[] getFocusListeners() { return (FocusListener[]) (getListeners(FocusListener.class)); } /** {@collect.stats} * Adds the specified hierarchy listener to receive hierarchy changed * events from this component when the hierarchy to which this container * belongs changes. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the hierarchy listener * @see java.awt.event.HierarchyEvent * @see java.awt.event.HierarchyListener * @see #removeHierarchyListener * @see #getHierarchyListeners * @since 1.3 */ public void addHierarchyListener(HierarchyListener l) { if (l == null) { return; } boolean notifyAncestors; synchronized (this) { notifyAncestors = (hierarchyListener == null && (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0); hierarchyListener = AWTEventMulticaster.add(hierarchyListener, l); notifyAncestors = (notifyAncestors && hierarchyListener != null); newEventsOnly = true; } if (notifyAncestors) { synchronized (getTreeLock()) { adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK, 1); } } } /** {@collect.stats} * Removes the specified hierarchy listener so that it no longer * receives hierarchy changed events from this component. This method * performs no function, nor does it throw an exception, if the listener * specified by the argument was not previously added to this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the hierarchy listener * @see java.awt.event.HierarchyEvent * @see java.awt.event.HierarchyListener * @see #addHierarchyListener * @see #getHierarchyListeners * @since 1.3 */ public void removeHierarchyListener(HierarchyListener l) { if (l == null) { return; } boolean notifyAncestors; synchronized (this) { notifyAncestors = (hierarchyListener != null && (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0); hierarchyListener = AWTEventMulticaster.remove(hierarchyListener, l); notifyAncestors = (notifyAncestors && hierarchyListener == null); } if (notifyAncestors) { synchronized (getTreeLock()) { adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK, -1); } } } /** {@collect.stats} * Returns an array of all the hierarchy listeners * registered on this component. * * @return all of this component's <code>HierarchyListener</code>s * or an empty array if no hierarchy * listeners are currently registered * * @see #addHierarchyListener * @see #removeHierarchyListener * @since 1.4 */ public synchronized HierarchyListener[] getHierarchyListeners() { return (HierarchyListener[])(getListeners(HierarchyListener.class)); } /** {@collect.stats} * Adds the specified hierarchy bounds listener to receive hierarchy * bounds events from this component when the hierarchy to which this * container belongs changes. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the hierarchy bounds listener * @see java.awt.event.HierarchyEvent * @see java.awt.event.HierarchyBoundsListener * @see #removeHierarchyBoundsListener * @see #getHierarchyBoundsListeners * @since 1.3 */ public void addHierarchyBoundsListener(HierarchyBoundsListener l) { if (l == null) { return; } boolean notifyAncestors; synchronized (this) { notifyAncestors = (hierarchyBoundsListener == null && (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0); hierarchyBoundsListener = AWTEventMulticaster.add(hierarchyBoundsListener, l); notifyAncestors = (notifyAncestors && hierarchyBoundsListener != null); newEventsOnly = true; } if (notifyAncestors) { synchronized (getTreeLock()) { adjustListeningChildrenOnParent( AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, 1); } } } /** {@collect.stats} * Removes the specified hierarchy bounds listener so that it no longer * receives hierarchy bounds events from this component. This method * performs no function, nor does it throw an exception, if the listener * specified by the argument was not previously added to this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the hierarchy bounds listener * @see java.awt.event.HierarchyEvent * @see java.awt.event.HierarchyBoundsListener * @see #addHierarchyBoundsListener * @see #getHierarchyBoundsListeners * @since 1.3 */ public void removeHierarchyBoundsListener(HierarchyBoundsListener l) { if (l == null) { return; } boolean notifyAncestors; synchronized (this) { notifyAncestors = (hierarchyBoundsListener != null && (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0); hierarchyBoundsListener = AWTEventMulticaster.remove(hierarchyBoundsListener, l); notifyAncestors = (notifyAncestors && hierarchyBoundsListener == null); } if (notifyAncestors) { synchronized (getTreeLock()) { adjustListeningChildrenOnParent( AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, -1); } } } // Should only be called while holding the tree lock int numListening(long mask) { // One mask or the other, but not neither or both. if (eventLog.isLoggable(Level.FINE)) { if ((mask != AWTEvent.HIERARCHY_EVENT_MASK) && (mask != AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)) { eventLog.log(Level.FINE, "Assertion failed"); } } if ((mask == AWTEvent.HIERARCHY_EVENT_MASK && (hierarchyListener != null || (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0)) || (mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK && (hierarchyBoundsListener != null || (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0))) { return 1; } else { return 0; } } // Should only be called while holding tree lock int countHierarchyMembers() { return 1; } // Should only be called while holding the tree lock int createHierarchyEvents(int id, Component changed, Container changedParent, long changeFlags, boolean enabledOnToolkit) { switch (id) { case HierarchyEvent.HIERARCHY_CHANGED: if (hierarchyListener != null || (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || enabledOnToolkit) { HierarchyEvent e = new HierarchyEvent(this, id, changed, changedParent, changeFlags); dispatchEvent(e); return 1; } break; case HierarchyEvent.ANCESTOR_MOVED: case HierarchyEvent.ANCESTOR_RESIZED: if (eventLog.isLoggable(Level.FINE)) { if (changeFlags != 0) { eventLog.log(Level.FINE, "Assertion (changeFlags == 0) failed"); } } if (hierarchyBoundsListener != null || (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 || enabledOnToolkit) { HierarchyEvent e = new HierarchyEvent(this, id, changed, changedParent); dispatchEvent(e); return 1; } break; default: // assert false if (eventLog.isLoggable(Level.FINE)) { eventLog.log(Level.FINE, "This code must never be reached"); } break; } return 0; } /** {@collect.stats} * Returns an array of all the hierarchy bounds listeners * registered on this component. * * @return all of this component's <code>HierarchyBoundsListener</code>s * or an empty array if no hierarchy bounds * listeners are currently registered * * @see #addHierarchyBoundsListener * @see #removeHierarchyBoundsListener * @since 1.4 */ public synchronized HierarchyBoundsListener[] getHierarchyBoundsListeners() { return (HierarchyBoundsListener[]) (getListeners(HierarchyBoundsListener.class)); } /* * Should only be called while holding the tree lock. * It's added only for overriding in java.awt.Window * because parent in Window is owner. */ void adjustListeningChildrenOnParent(long mask, int num) { if (parent != null) { parent.adjustListeningChildren(mask, num); } } /** {@collect.stats} * Adds the specified key listener to receive key events from * this component. * If l is null, no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the key listener. * @see java.awt.event.KeyEvent * @see java.awt.event.KeyListener * @see #removeKeyListener * @see #getKeyListeners * @since JDK1.1 */ public synchronized void addKeyListener(KeyListener l) { if (l == null) { return; } keyListener = AWTEventMulticaster.add(keyListener, l); newEventsOnly = true; // if this is a lightweight component, enable key events // in the native container. if (peer instanceof LightweightPeer) { parent.proxyEnableEvents(AWTEvent.KEY_EVENT_MASK); } } /** {@collect.stats} * Removes the specified key listener so that it no longer * receives key events from this component. This method performs * no function, nor does it throw an exception, if the listener * specified by the argument was not previously added to this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the key listener * @see java.awt.event.KeyEvent * @see java.awt.event.KeyListener * @see #addKeyListener * @see #getKeyListeners * @since JDK1.1 */ public synchronized void removeKeyListener(KeyListener l) { if (l == null) { return; } keyListener = AWTEventMulticaster.remove(keyListener, l); } /** {@collect.stats} * Returns an array of all the key listeners * registered on this component. * * @return all of this component's <code>KeyListener</code>s * or an empty array if no key * listeners are currently registered * * @see #addKeyListener * @see #removeKeyListener * @since 1.4 */ public synchronized KeyListener[] getKeyListeners() { return (KeyListener[]) (getListeners(KeyListener.class)); } /** {@collect.stats} * Adds the specified mouse listener to receive mouse events from * this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the mouse listener * @see java.awt.event.MouseEvent * @see java.awt.event.MouseListener * @see #removeMouseListener * @see #getMouseListeners * @since JDK1.1 */ public synchronized void addMouseListener(MouseListener l) { if (l == null) { return; } mouseListener = AWTEventMulticaster.add(mouseListener,l); newEventsOnly = true; // if this is a lightweight component, enable mouse events // in the native container. if (peer instanceof LightweightPeer) { parent.proxyEnableEvents(AWTEvent.MOUSE_EVENT_MASK); } } /** {@collect.stats} * Removes the specified mouse listener so that it no longer * receives mouse events from this component. This method performs * no function, nor does it throw an exception, if the listener * specified by the argument was not previously added to this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the mouse listener * @see java.awt.event.MouseEvent * @see java.awt.event.MouseListener * @see #addMouseListener * @see #getMouseListeners * @since JDK1.1 */ public synchronized void removeMouseListener(MouseListener l) { if (l == null) { return; } mouseListener = AWTEventMulticaster.remove(mouseListener, l); } /** {@collect.stats} * Returns an array of all the mouse listeners * registered on this component. * * @return all of this component's <code>MouseListener</code>s * or an empty array if no mouse * listeners are currently registered * * @see #addMouseListener * @see #removeMouseListener * @since 1.4 */ public synchronized MouseListener[] getMouseListeners() { return (MouseListener[]) (getListeners(MouseListener.class)); } /** {@collect.stats} * Adds the specified mouse motion listener to receive mouse motion * events from this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the mouse motion listener * @see java.awt.event.MouseEvent * @see java.awt.event.MouseMotionListener * @see #removeMouseMotionListener * @see #getMouseMotionListeners * @since JDK1.1 */ public synchronized void addMouseMotionListener(MouseMotionListener l) { if (l == null) { return; } mouseMotionListener = AWTEventMulticaster.add(mouseMotionListener,l); newEventsOnly = true; // if this is a lightweight component, enable mouse events // in the native container. if (peer instanceof LightweightPeer) { parent.proxyEnableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK); } } /** {@collect.stats} * Removes the specified mouse motion listener so that it no longer * receives mouse motion events from this component. This method performs * no function, nor does it throw an exception, if the listener * specified by the argument was not previously added to this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the mouse motion listener * @see java.awt.event.MouseEvent * @see java.awt.event.MouseMotionListener * @see #addMouseMotionListener * @see #getMouseMotionListeners * @since JDK1.1 */ public synchronized void removeMouseMotionListener(MouseMotionListener l) { if (l == null) { return; } mouseMotionListener = AWTEventMulticaster.remove(mouseMotionListener, l); } /** {@collect.stats} * Returns an array of all the mouse motion listeners * registered on this component. * * @return all of this component's <code>MouseMotionListener</code>s * or an empty array if no mouse motion * listeners are currently registered * * @see #addMouseMotionListener * @see #removeMouseMotionListener * @since 1.4 */ public synchronized MouseMotionListener[] getMouseMotionListeners() { return (MouseMotionListener[]) (getListeners(MouseMotionListener.class)); } /** {@collect.stats} * Adds the specified mouse wheel listener to receive mouse wheel events * from this component. Containers also receive mouse wheel events from * sub-components. * <p> * For information on how mouse wheel events are dispatched, see * the class description for {@link MouseWheelEvent}. * <p> * If l is <code>null</code>, no exception is thrown and no * action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the mouse wheel listener * @see java.awt.event.MouseWheelEvent * @see java.awt.event.MouseWheelListener * @see #removeMouseWheelListener * @see #getMouseWheelListeners * @since 1.4 */ public synchronized void addMouseWheelListener(MouseWheelListener l) { if (l == null) { return; } mouseWheelListener = AWTEventMulticaster.add(mouseWheelListener,l); newEventsOnly = true; // if this is a lightweight component, enable mouse events // in the native container. if (peer instanceof LightweightPeer) { parent.proxyEnableEvents(AWTEvent.MOUSE_WHEEL_EVENT_MASK); } } /** {@collect.stats} * Removes the specified mouse wheel listener so that it no longer * receives mouse wheel events from this component. This method performs * no function, nor does it throw an exception, if the listener * specified by the argument was not previously added to this component. * If l is null, no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the mouse wheel listener. * @see java.awt.event.MouseWheelEvent * @see java.awt.event.MouseWheelListener * @see #addMouseWheelListener * @see #getMouseWheelListeners * @since 1.4 */ public synchronized void removeMouseWheelListener(MouseWheelListener l) { if (l == null) { return; } mouseWheelListener = AWTEventMulticaster.remove(mouseWheelListener, l); } /** {@collect.stats} * Returns an array of all the mouse wheel listeners * registered on this component. * * @return all of this component's <code>MouseWheelListener</code>s * or an empty array if no mouse wheel * listeners are currently registered * * @see #addMouseWheelListener * @see #removeMouseWheelListener * @since 1.4 */ public synchronized MouseWheelListener[] getMouseWheelListeners() { return (MouseWheelListener[]) (getListeners(MouseWheelListener.class)); } /** {@collect.stats} * Adds the specified input method listener to receive * input method events from this component. A component will * only receive input method events from input methods * if it also overrides <code>getInputMethodRequests</code> to return an * <code>InputMethodRequests</code> instance. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the input method listener * @see java.awt.event.InputMethodEvent * @see java.awt.event.InputMethodListener * @see #removeInputMethodListener * @see #getInputMethodListeners * @see #getInputMethodRequests * @since 1.2 */ public synchronized void addInputMethodListener(InputMethodListener l) { if (l == null) { return; } inputMethodListener = AWTEventMulticaster.add(inputMethodListener, l); newEventsOnly = true; } /** {@collect.stats} * Removes the specified input method listener so that it no longer * receives input method events from this component. This method performs * no function, nor does it throw an exception, if the listener * specified by the argument was not previously added to this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" * >AWT Threading Issues</a> for details on AWT's threading model. * * @param l the input method listener * @see java.awt.event.InputMethodEvent * @see java.awt.event.InputMethodListener * @see #addInputMethodListener * @see #getInputMethodListeners * @since 1.2 */ public synchronized void removeInputMethodListener(InputMethodListener l) { if (l == null) { return; } inputMethodListener = AWTEventMulticaster.remove(inputMethodListener, l); } /** {@collect.stats} * Returns an array of all the input method listeners * registered on this component. * * @return all of this component's <code>InputMethodListener</code>s * or an empty array if no input method * listeners are currently registered * * @see #addInputMethodListener * @see #removeInputMethodListener * @since 1.4 */ public synchronized InputMethodListener[] getInputMethodListeners() { return (InputMethodListener[]) (getListeners(InputMethodListener.class)); } /** {@collect.stats} * Returns an array of all the objects currently registered * as <code><em>Foo</em>Listener</code>s * upon this <code>Component</code>. * <code><em>Foo</em>Listener</code>s are registered using the * <code>add<em>Foo</em>Listener</code> method. * * <p> * You can specify the <code>listenerType</code> argument * with a class literal, such as * <code><em>Foo</em>Listener.class</code>. * For example, you can query a * <code>Component</code> <code>c</code> * for its mouse listeners with the following code: * * <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre> * * If no such listeners exist, this method returns an empty array. * * @param listenerType the type of listeners requested; this parameter * should specify an interface that descends from * <code>java.util.EventListener</code> * @return an array of all objects registered as * <code><em>Foo</em>Listener</code>s on this component, * or an empty array if no such listeners have been added * @exception ClassCastException if <code>listenerType</code> * doesn't specify a class or interface that implements * <code>java.util.EventListener</code> * * @see #getComponentListeners * @see #getFocusListeners * @see #getHierarchyListeners * @see #getHierarchyBoundsListeners * @see #getKeyListeners * @see #getMouseListeners * @see #getMouseMotionListeners * @see #getMouseWheelListeners * @see #getInputMethodListeners * @see #getPropertyChangeListeners * * @since 1.3 */ public <T extends EventListener> T[] getListeners(Class<T> listenerType) { EventListener l = null; if (listenerType == ComponentListener.class) { l = componentListener; } else if (listenerType == FocusListener.class) { l = focusListener; } else if (listenerType == HierarchyListener.class) { l = hierarchyListener; } else if (listenerType == HierarchyBoundsListener.class) { l = hierarchyBoundsListener; } else if (listenerType == KeyListener.class) { l = keyListener; } else if (listenerType == MouseListener.class) { l = mouseListener; } else if (listenerType == MouseMotionListener.class) { l = mouseMotionListener; } else if (listenerType == MouseWheelListener.class) { l = mouseWheelListener; } else if (listenerType == InputMethodListener.class) { l = inputMethodListener; } else if (listenerType == PropertyChangeListener.class) { return (T[])getPropertyChangeListeners(); } return AWTEventMulticaster.getListeners(l, listenerType); } /** {@collect.stats} * Gets the input method request handler which supports * requests from input methods for this component. A component * that supports on-the-spot text input must override this * method to return an <code>InputMethodRequests</code> instance. * At the same time, it also has to handle input method events. * * @return the input method request handler for this component, * <code>null</code> by default * @see #addInputMethodListener * @since 1.2 */ public InputMethodRequests getInputMethodRequests() { return null; } /** {@collect.stats} * Gets the input context used by this component for handling * the communication with input methods when text is entered * in this component. By default, the input context used for * the parent component is returned. Components may * override this to return a private input context. * * @return the input context used by this component; * <code>null</code> if no context can be determined * @since 1.2 */ public InputContext getInputContext() { Container parent = this.parent; if (parent == null) { return null; } else { return parent.getInputContext(); } } /** {@collect.stats} * Enables the events defined by the specified event mask parameter * to be delivered to this component. * <p> * Event types are automatically enabled when a listener for * that event type is added to the component. * <p> * This method only needs to be invoked by subclasses of * <code>Component</code> which desire to have the specified event * types delivered to <code>processEvent</code> regardless of whether * or not a listener is registered. * @param eventsToEnable the event mask defining the event types * @see #processEvent * @see #disableEvents * @see AWTEvent * @since JDK1.1 */ protected final void enableEvents(long eventsToEnable) { long notifyAncestors = 0; synchronized (this) { if ((eventsToEnable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 && hierarchyListener == null && (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0) { notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK; } if ((eventsToEnable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 && hierarchyBoundsListener == null && (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0) { notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK; } eventMask |= eventsToEnable; newEventsOnly = true; } // if this is a lightweight component, enable mouse events // in the native container. if (peer instanceof LightweightPeer) { parent.proxyEnableEvents(eventMask); } if (notifyAncestors != 0) { synchronized (getTreeLock()) { adjustListeningChildrenOnParent(notifyAncestors, 1); } } } /** {@collect.stats} * Disables the events defined by the specified event mask parameter * from being delivered to this component. * @param eventsToDisable the event mask defining the event types * @see #enableEvents * @since JDK1.1 */ protected final void disableEvents(long eventsToDisable) { long notifyAncestors = 0; synchronized (this) { if ((eventsToDisable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 && hierarchyListener == null && (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0) { notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK; } if ((eventsToDisable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)!=0 && hierarchyBoundsListener == null && (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0) { notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK; } eventMask &= ~eventsToDisable; } if (notifyAncestors != 0) { synchronized (getTreeLock()) { adjustListeningChildrenOnParent(notifyAncestors, -1); } } } transient EventQueueItem[] eventCache; /** {@collect.stats} * @see #isCoalescingEnabled * @see #checkCoalescing */ transient private boolean coalescingEnabled = checkCoalescing(); /** {@collect.stats} * Weak map of known coalesceEvent overriders. * Value indicates whether overriden. * Bootstrap classes are not included. */ private static final Map<Class<?>, Boolean> coalesceMap = new java.util.WeakHashMap<Class<?>, Boolean>(); /** {@collect.stats} * Indicates whether this class overrides coalesceEvents. * It is assumed that all classes that are loaded from the bootstrap * do not. * The boostrap class loader is assumed to be represented by null. * We do not check that the method really overrides * (it might be static, private or package private). */ private boolean checkCoalescing() { if (getClass().getClassLoader()==null) { return false; } final Class<? extends Component> clazz = getClass(); synchronized (coalesceMap) { // Check cache. Boolean value = coalesceMap.get(clazz); if (value != null) { return value; } // Need to check non-bootstraps. Boolean enabled = java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Boolean>() { public Boolean run() { return isCoalesceEventsOverriden(clazz); } } ); coalesceMap.put(clazz, enabled); return enabled; } } /** {@collect.stats} * Parameter types of coalesceEvents(AWTEvent,AWTEVent). */ private static final Class[] coalesceEventsParams = { AWTEvent.class, AWTEvent.class }; /** {@collect.stats} * Indicates whether a class or its superclasses override coalesceEvents. * Must be called with lock on coalesceMap and privileged. * @see checkCoalsecing */ private static boolean isCoalesceEventsOverriden(Class<?> clazz) { assert Thread.holdsLock(coalesceMap); // First check superclass - we may not need to bother ourselves. Class<?> superclass = clazz.getSuperclass(); if (superclass == null) { // Only occurs on implementations that // do not use null to represent the bootsrap class loader. return false; } if (superclass.getClassLoader() != null) { Boolean value = coalesceMap.get(superclass); if (value == null) { // Not done already - recurse. if (isCoalesceEventsOverriden(superclass)) { coalesceMap.put(superclass, true); return true; } } else if (value) { return true; } } try { // Throws if not overriden. clazz.getDeclaredMethod( "coalesceEvents", coalesceEventsParams ); return true; } catch (NoSuchMethodException e) { // Not present in this class. return false; } } /** {@collect.stats} * Indicates whether coalesceEvents may do something. */ final boolean isCoalescingEnabled() { return coalescingEnabled; } /** {@collect.stats} * Potentially coalesce an event being posted with an existing * event. This method is called by <code>EventQueue.postEvent</code> * if an event with the same ID as the event to be posted is found in * the queue (both events must have this component as their source). * This method either returns a coalesced event which replaces * the existing event (and the new event is then discarded), or * <code>null</code> to indicate that no combining should be done * (add the second event to the end of the queue). Either event * parameter may be modified and returned, as the other one is discarded * unless <code>null</code> is returned. * <p> * This implementation of <code>coalesceEvents</code> coalesces * two event types: mouse move (and drag) events, * and paint (and update) events. * For mouse move events the last event is always returned, causing * intermediate moves to be discarded. For paint events, the new * event is coalesced into a complex <code>RepaintArea</code> in the peer. * The new <code>AWTEvent</code> is always returned. * * @param existingEvent the event already on the <code>EventQueue</code> * @param newEvent the event being posted to the * <code>EventQueue</code> * @return a coalesced event, or <code>null</code> indicating that no * coalescing was done */ protected AWTEvent coalesceEvents(AWTEvent existingEvent, AWTEvent newEvent) { return null; } /** {@collect.stats} * Processes events occurring on this component. By default this * method calls the appropriate * <code>process&lt;event&nbsp;type&gt;Event</code> * method for the given class of event. * <p>Note that if the event parameter is <code>null</code> * the behavior is unspecified and may result in an * exception. * * @param e the event * @see #processComponentEvent * @see #processFocusEvent * @see #processKeyEvent * @see #processMouseEvent * @see #processMouseMotionEvent * @see #processInputMethodEvent * @see #processHierarchyEvent * @see #processMouseWheelEvent * @since JDK1.1 */ protected void processEvent(AWTEvent e) { if (e instanceof FocusEvent) { processFocusEvent((FocusEvent)e); } else if (e instanceof MouseEvent) { switch(e.getID()) { case MouseEvent.MOUSE_PRESSED: case MouseEvent.MOUSE_RELEASED: case MouseEvent.MOUSE_CLICKED: case MouseEvent.MOUSE_ENTERED: case MouseEvent.MOUSE_EXITED: processMouseEvent((MouseEvent)e); break; case MouseEvent.MOUSE_MOVED: case MouseEvent.MOUSE_DRAGGED: processMouseMotionEvent((MouseEvent)e); break; case MouseEvent.MOUSE_WHEEL: processMouseWheelEvent((MouseWheelEvent)e); break; } } else if (e instanceof KeyEvent) { processKeyEvent((KeyEvent)e); } else if (e instanceof ComponentEvent) { processComponentEvent((ComponentEvent)e); } else if (e instanceof InputMethodEvent) { processInputMethodEvent((InputMethodEvent)e); } else if (e instanceof HierarchyEvent) { switch (e.getID()) { case HierarchyEvent.HIERARCHY_CHANGED: processHierarchyEvent((HierarchyEvent)e); break; case HierarchyEvent.ANCESTOR_MOVED: case HierarchyEvent.ANCESTOR_RESIZED: processHierarchyBoundsEvent((HierarchyEvent)e); break; } } } /** {@collect.stats} * Processes component events occurring on this component by * dispatching them to any registered * <code>ComponentListener</code> objects. * <p> * This method is not called unless component events are * enabled for this component. Component events are enabled * when one of the following occurs: * <p><ul> * <li>A <code>ComponentListener</code> object is registered * via <code>addComponentListener</code>. * <li>Component events are enabled via <code>enableEvents</code>. * </ul> * <p>Note that if the event parameter is <code>null</code> * the behavior is unspecified and may result in an * exception. * * @param e the component event * @see java.awt.event.ComponentEvent * @see java.awt.event.ComponentListener * @see #addComponentListener * @see #enableEvents * @since JDK1.1 */ protected void processComponentEvent(ComponentEvent e) { ComponentListener listener = componentListener; if (listener != null) { int id = e.getID(); switch(id) { case ComponentEvent.COMPONENT_RESIZED: listener.componentResized(e); break; case ComponentEvent.COMPONENT_MOVED: listener.componentMoved(e); break; case ComponentEvent.COMPONENT_SHOWN: listener.componentShown(e); break; case ComponentEvent.COMPONENT_HIDDEN: listener.componentHidden(e); break; } } } /** {@collect.stats} * Processes focus events occurring on this component by * dispatching them to any registered * <code>FocusListener</code> objects. * <p> * This method is not called unless focus events are * enabled for this component. Focus events are enabled * when one of the following occurs: * <p><ul> * <li>A <code>FocusListener</code> object is registered * via <code>addFocusListener</code>. * <li>Focus events are enabled via <code>enableEvents</code>. * </ul> * <p> * If focus events are enabled for a <code>Component</code>, * the current <code>KeyboardFocusManager</code> determines * whether or not a focus event should be dispatched to * registered <code>FocusListener</code> objects. If the * events are to be dispatched, the <code>KeyboardFocusManager</code> * calls the <code>Component</code>'s <code>dispatchEvent</code> * method, which results in a call to the <code>Component</code>'s * <code>processFocusEvent</code> method. * <p> * If focus events are enabled for a <code>Component</code>, calling * the <code>Component</code>'s <code>dispatchEvent</code> method * with a <code>FocusEvent</code> as the argument will result in a * call to the <code>Component</code>'s <code>processFocusEvent</code> * method regardless of the current <code>KeyboardFocusManager</code>. * <p> * <p>Note that if the event parameter is <code>null</code> * the behavior is unspecified and may result in an * exception. * * @param e the focus event * @see java.awt.event.FocusEvent * @see java.awt.event.FocusListener * @see java.awt.KeyboardFocusManager * @see #addFocusListener * @see #enableEvents * @see #dispatchEvent * @since JDK1.1 */ protected void processFocusEvent(FocusEvent e) { FocusListener listener = focusListener; if (listener != null) { int id = e.getID(); switch(id) { case FocusEvent.FOCUS_GAINED: listener.focusGained(e); break; case FocusEvent.FOCUS_LOST: listener.focusLost(e); break; } } } /** {@collect.stats} * Processes key events occurring on this component by * dispatching them to any registered * <code>KeyListener</code> objects. * <p> * This method is not called unless key events are * enabled for this component. Key events are enabled * when one of the following occurs: * <p><ul> * <li>A <code>KeyListener</code> object is registered * via <code>addKeyListener</code>. * <li>Key events are enabled via <code>enableEvents</code>. * </ul> * * <p> * If key events are enabled for a <code>Component</code>, * the current <code>KeyboardFocusManager</code> determines * whether or not a key event should be dispatched to * registered <code>KeyListener</code> objects. The * <code>DefaultKeyboardFocusManager</code> will not dispatch * key events to a <code>Component</code> that is not the focus * owner or is not showing. * <p> * As of J2SE 1.4, <code>KeyEvent</code>s are redirected to * the focus owner. Please see the * <a href="doc-files/FocusSpec.html">Focus Specification</a> * for further information. * <p> * Calling a <code>Component</code>'s <code>dispatchEvent</code> * method with a <code>KeyEvent</code> as the argument will * result in a call to the <code>Component</code>'s * <code>processKeyEvent</code> method regardless of the * current <code>KeyboardFocusManager</code> as long as the * component is showing, focused, and enabled, and key events * are enabled on it. * <p>If the event parameter is <code>null</code> * the behavior is unspecified and may result in an * exception. * * @param e the key event * @see java.awt.event.KeyEvent * @see java.awt.event.KeyListener * @see java.awt.KeyboardFocusManager * @see java.awt.DefaultKeyboardFocusManager * @see #processEvent * @see #dispatchEvent * @see #addKeyListener * @see #enableEvents * @see #isShowing * @since JDK1.1 */ protected void processKeyEvent(KeyEvent e) { KeyListener listener = keyListener; if (listener != null) { int id = e.getID(); switch(id) { case KeyEvent.KEY_TYPED: listener.keyTyped(e); break; case KeyEvent.KEY_PRESSED: listener.keyPressed(e); break; case KeyEvent.KEY_RELEASED: listener.keyReleased(e); break; } } } /** {@collect.stats} * Processes mouse events occurring on this component by * dispatching them to any registered * <code>MouseListener</code> objects. * <p> * This method is not called unless mouse events are * enabled for this component. Mouse events are enabled * when one of the following occurs: * <p><ul> * <li>A <code>MouseListener</code> object is registered * via <code>addMouseListener</code>. * <li>Mouse events are enabled via <code>enableEvents</code>. * </ul> * <p>Note that if the event parameter is <code>null</code> * the behavior is unspecified and may result in an * exception. * * @param e the mouse event * @see java.awt.event.MouseEvent * @see java.awt.event.MouseListener * @see #addMouseListener * @see #enableEvents * @since JDK1.1 */ protected void processMouseEvent(MouseEvent e) { MouseListener listener = mouseListener; if (listener != null) { int id = e.getID(); switch(id) { case MouseEvent.MOUSE_PRESSED: listener.mousePressed(e); break; case MouseEvent.MOUSE_RELEASED: listener.mouseReleased(e); break; case MouseEvent.MOUSE_CLICKED: listener.mouseClicked(e); break; case MouseEvent.MOUSE_EXITED: listener.mouseExited(e); break; case MouseEvent.MOUSE_ENTERED: listener.mouseEntered(e); break; } } } /** {@collect.stats} * Processes mouse motion events occurring on this component by * dispatching them to any registered * <code>MouseMotionListener</code> objects. * <p> * This method is not called unless mouse motion events are * enabled for this component. Mouse motion events are enabled * when one of the following occurs: * <p><ul> * <li>A <code>MouseMotionListener</code> object is registered * via <code>addMouseMotionListener</code>. * <li>Mouse motion events are enabled via <code>enableEvents</code>. * </ul> * <p>Note that if the event parameter is <code>null</code> * the behavior is unspecified and may result in an * exception. * * @param e the mouse motion event * @see java.awt.event.MouseEvent * @see java.awt.event.MouseMotionListener * @see #addMouseMotionListener * @see #enableEvents * @since JDK1.1 */ protected void processMouseMotionEvent(MouseEvent e) { MouseMotionListener listener = mouseMotionListener; if (listener != null) { int id = e.getID(); switch(id) { case MouseEvent.MOUSE_MOVED: listener.mouseMoved(e); break; case MouseEvent.MOUSE_DRAGGED: listener.mouseDragged(e); break; } } } /** {@collect.stats} * Processes mouse wheel events occurring on this component by * dispatching them to any registered * <code>MouseWheelListener</code> objects. * <p> * This method is not called unless mouse wheel events are * enabled for this component. Mouse wheel events are enabled * when one of the following occurs: * <p><ul> * <li>A <code>MouseWheelListener</code> object is registered * via <code>addMouseWheelListener</code>. * <li>Mouse wheel events are enabled via <code>enableEvents</code>. * </ul> * <p> * For information on how mouse wheel events are dispatched, see * the class description for {@link MouseWheelEvent}. * <p> * Note that if the event parameter is <code>null</code> * the behavior is unspecified and may result in an * exception. * * @param e the mouse wheel event * @see java.awt.event.MouseWheelEvent * @see java.awt.event.MouseWheelListener * @see #addMouseWheelListener * @see #enableEvents * @since 1.4 */ protected void processMouseWheelEvent(MouseWheelEvent e) { MouseWheelListener listener = mouseWheelListener; if (listener != null) { int id = e.getID(); switch(id) { case MouseEvent.MOUSE_WHEEL: listener.mouseWheelMoved(e); break; } } } boolean postsOldMouseEvents() { return false; } /** {@collect.stats} * Processes input method events occurring on this component by * dispatching them to any registered * <code>InputMethodListener</code> objects. * <p> * This method is not called unless input method events * are enabled for this component. Input method events are enabled * when one of the following occurs: * <p><ul> * <li>An <code>InputMethodListener</code> object is registered * via <code>addInputMethodListener</code>. * <li>Input method events are enabled via <code>enableEvents</code>. * </ul> * <p>Note that if the event parameter is <code>null</code> * the behavior is unspecified and may result in an * exception. * * @param e the input method event * @see java.awt.event.InputMethodEvent * @see java.awt.event.InputMethodListener * @see #addInputMethodListener * @see #enableEvents * @since 1.2 */ protected void processInputMethodEvent(InputMethodEvent e) { InputMethodListener listener = inputMethodListener; if (listener != null) { int id = e.getID(); switch (id) { case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED: listener.inputMethodTextChanged(e); break; case InputMethodEvent.CARET_POSITION_CHANGED: listener.caretPositionChanged(e); break; } } } /** {@collect.stats} * Processes hierarchy events occurring on this component by * dispatching them to any registered * <code>HierarchyListener</code> objects. * <p> * This method is not called unless hierarchy events * are enabled for this component. Hierarchy events are enabled * when one of the following occurs: * <p><ul> * <li>An <code>HierarchyListener</code> object is registered * via <code>addHierarchyListener</code>. * <li>Hierarchy events are enabled via <code>enableEvents</code>. * </ul> * <p>Note that if the event parameter is <code>null</code> * the behavior is unspecified and may result in an * exception. * * @param e the hierarchy event * @see java.awt.event.HierarchyEvent * @see java.awt.event.HierarchyListener * @see #addHierarchyListener * @see #enableEvents * @since 1.3 */ protected void processHierarchyEvent(HierarchyEvent e) { HierarchyListener listener = hierarchyListener; if (listener != null) { int id = e.getID(); switch (id) { case HierarchyEvent.HIERARCHY_CHANGED: listener.hierarchyChanged(e); break; } } } /** {@collect.stats} * Processes hierarchy bounds events occurring on this component by * dispatching them to any registered * <code>HierarchyBoundsListener</code> objects. * <p> * This method is not called unless hierarchy bounds events * are enabled for this component. Hierarchy bounds events are enabled * when one of the following occurs: * <p><ul> * <li>An <code>HierarchyBoundsListener</code> object is registered * via <code>addHierarchyBoundsListener</code>. * <li>Hierarchy bounds events are enabled via <code>enableEvents</code>. * </ul> * <p>Note that if the event parameter is <code>null</code> * the behavior is unspecified and may result in an * exception. * * @param e the hierarchy event * @see java.awt.event.HierarchyEvent * @see java.awt.event.HierarchyBoundsListener * @see #addHierarchyBoundsListener * @see #enableEvents * @since 1.3 */ protected void processHierarchyBoundsEvent(HierarchyEvent e) { HierarchyBoundsListener listener = hierarchyBoundsListener; if (listener != null) { int id = e.getID(); switch (id) { case HierarchyEvent.ANCESTOR_MOVED: listener.ancestorMoved(e); break; case HierarchyEvent.ANCESTOR_RESIZED: listener.ancestorResized(e); break; } } } /** {@collect.stats} * @deprecated As of JDK version 1.1 * replaced by processEvent(AWTEvent). */ @Deprecated public boolean handleEvent(Event evt) { switch (evt.id) { case Event.MOUSE_ENTER: return mouseEnter(evt, evt.x, evt.y); case Event.MOUSE_EXIT: return mouseExit(evt, evt.x, evt.y); case Event.MOUSE_MOVE: return mouseMove(evt, evt.x, evt.y); case Event.MOUSE_DOWN: return mouseDown(evt, evt.x, evt.y); case Event.MOUSE_DRAG: return mouseDrag(evt, evt.x, evt.y); case Event.MOUSE_UP: return mouseUp(evt, evt.x, evt.y); case Event.KEY_PRESS: case Event.KEY_ACTION: return keyDown(evt, evt.key); case Event.KEY_RELEASE: case Event.KEY_ACTION_RELEASE: return keyUp(evt, evt.key); case Event.ACTION_EVENT: return action(evt, evt.arg); case Event.GOT_FOCUS: return gotFocus(evt, evt.arg); case Event.LOST_FOCUS: return lostFocus(evt, evt.arg); } return false; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by processMouseEvent(MouseEvent). */ @Deprecated public boolean mouseDown(Event evt, int x, int y) { return false; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by processMouseMotionEvent(MouseEvent). */ @Deprecated public boolean mouseDrag(Event evt, int x, int y) { return false; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by processMouseEvent(MouseEvent). */ @Deprecated public boolean mouseUp(Event evt, int x, int y) { return false; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by processMouseMotionEvent(MouseEvent). */ @Deprecated public boolean mouseMove(Event evt, int x, int y) { return false; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by processMouseEvent(MouseEvent). */ @Deprecated public boolean mouseEnter(Event evt, int x, int y) { return false; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by processMouseEvent(MouseEvent). */ @Deprecated public boolean mouseExit(Event evt, int x, int y) { return false; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by processKeyEvent(KeyEvent). */ @Deprecated public boolean keyDown(Event evt, int key) { return false; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by processKeyEvent(KeyEvent). */ @Deprecated public boolean keyUp(Event evt, int key) { return false; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * should register this component as ActionListener on component * which fires action events. */ @Deprecated public boolean action(Event evt, Object what) { return false; } /** {@collect.stats} * Makes this <code>Component</code> displayable by connecting it to a * native screen resource. * This method is called internally by the toolkit and should * not be called directly by programs. * @see #isDisplayable * @see #removeNotify * @since JDK1.0 */ public void addNotify() { synchronized (getTreeLock()) { ComponentPeer peer = this.peer; if (peer == null || peer instanceof LightweightPeer){ if (peer == null) { // Update both the Component's peer variable and the local // variable we use for thread safety. this.peer = peer = getToolkit().createComponent(this); } // This is a lightweight component which means it won't be // able to get window-related events by itself. If any // have been enabled, then the nearest native container must // be enabled. if (parent != null) { long mask = 0; if ((mouseListener != null) || ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0)) { mask |= AWTEvent.MOUSE_EVENT_MASK; } if ((mouseMotionListener != null) || ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0)) { mask |= AWTEvent.MOUSE_MOTION_EVENT_MASK; } if ((mouseWheelListener != null ) || ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0)) { mask |= AWTEvent.MOUSE_WHEEL_EVENT_MASK; } if (focusListener != null || (eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0) { mask |= AWTEvent.FOCUS_EVENT_MASK; } if (keyListener != null || (eventMask & AWTEvent.KEY_EVENT_MASK) != 0) { mask |= AWTEvent.KEY_EVENT_MASK; } if (mask != 0) { parent.proxyEnableEvents(mask); } } } else { // It's native. If the parent is lightweight it // will need some help. Container parent = this.parent; if (parent != null && parent.peer instanceof LightweightPeer) { nativeInLightFixer = new NativeInLightFixer(); } } invalidate(); int npopups = (popups != null? popups.size() : 0); for (int i = 0 ; i < npopups ; i++) { PopupMenu popup = (PopupMenu)popups.elementAt(i); popup.addNotify(); } if (dropTarget != null) dropTarget.addNotify(peer); peerFont = getFont(); if (getContainer() != null && !isAddNotifyComplete) { getContainer().increaseComponentCount(this); } // Update stacking order if (parent != null && parent.peer != null) { ContainerPeer parentContPeer = (ContainerPeer) parent.peer; // if our parent is lightweight and we are not // we should call restack on nearest heavyweight // container. if (parentContPeer instanceof LightweightPeer && ! (peer instanceof LightweightPeer)) { Container hwParent = getNativeContainer(); if (hwParent != null && hwParent.peer != null) { parentContPeer = (ContainerPeer) hwParent.peer; } } if (parentContPeer.isRestackSupported()) { parentContPeer.restack(); } } if (!isAddNotifyComplete) { addPropertyChangeListener("opaque", opaquePropertyChangeListener); mixOnShowing(); } isAddNotifyComplete = true; if (hierarchyListener != null || (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) { HierarchyEvent e = new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED, this, parent, HierarchyEvent.DISPLAYABILITY_CHANGED | ((isRecursivelyVisible()) ? HierarchyEvent.SHOWING_CHANGED : 0)); dispatchEvent(e); } } } /** {@collect.stats} * Makes this <code>Component</code> undisplayable by destroying it native * screen resource. * <p> * This method is called by the toolkit internally and should * not be called directly by programs. Code overriding * this method should call <code>super.removeNotify</code> as * the first line of the overriding method. * * @see #isDisplayable * @see #addNotify * @since JDK1.0 */ public void removeNotify() { KeyboardFocusManager.clearMostRecentFocusOwner(this); if (KeyboardFocusManager.getCurrentKeyboardFocusManager(). getPermanentFocusOwner() == this) { KeyboardFocusManager.getCurrentKeyboardFocusManager(). setGlobalPermanentFocusOwner(null); } synchronized (getTreeLock()) { if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabled() && !nextFocusHelper()) { KeyboardFocusManager.getCurrentKeyboardFocusManager(). clearGlobalFocusOwner(); } if (getContainer() != null && isAddNotifyComplete) { getContainer().decreaseComponentCount(this); } int npopups = (popups != null? popups.size() : 0); for (int i = 0 ; i < npopups ; i++) { PopupMenu popup = (PopupMenu)popups.elementAt(i); popup.removeNotify(); } // If there is any input context for this component, notify // that this component is being removed. (This has to be done // before hiding peer.) if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) { InputContext inputContext = getInputContext(); if (inputContext != null) { inputContext.removeNotify(this); } } if (nativeInLightFixer != null) { nativeInLightFixer.uninstall(); } ComponentPeer p = peer; if (p != null) { boolean isLightweight = isLightweight(); if (bufferStrategy instanceof FlipBufferStrategy) { ((FlipBufferStrategy)bufferStrategy).destroyBuffers(); } if (dropTarget != null) dropTarget.removeNotify(peer); // Hide peer first to stop system events such as cursor moves. if (visible) { p.hide(); } peer = null; // Stop peer updates. peerFont = null; Toolkit.getEventQueue().removeSourceEvents(this, false); KeyboardFocusManager.getCurrentKeyboardFocusManager(). discardKeyEvents(this); p.dispose(); mixOnHiding(isLightweight); removePropertyChangeListener("opaque", opaquePropertyChangeListener); isAddNotifyComplete = false; } if (hierarchyListener != null || (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) { HierarchyEvent e = new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED, this, parent, HierarchyEvent.DISPLAYABILITY_CHANGED | ((isRecursivelyVisible()) ? HierarchyEvent.SHOWING_CHANGED : 0)); dispatchEvent(e); } } } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by processFocusEvent(FocusEvent). */ @Deprecated public boolean gotFocus(Event evt, Object what) { return false; } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by processFocusEvent(FocusEvent). */ @Deprecated public boolean lostFocus(Event evt, Object what) { return false; } /** {@collect.stats} * Returns whether this <code>Component</code> can become the focus * owner. * * @return <code>true</code> if this <code>Component</code> is * focusable; <code>false</code> otherwise * @see #setFocusable * @since JDK1.1 * @deprecated As of 1.4, replaced by <code>isFocusable()</code>. */ @Deprecated public boolean isFocusTraversable() { if (isFocusTraversableOverridden == FOCUS_TRAVERSABLE_UNKNOWN) { isFocusTraversableOverridden = FOCUS_TRAVERSABLE_DEFAULT; } return focusable; } /** {@collect.stats} * Returns whether this Component can be focused. * * @return <code>true</code> if this Component is focusable; * <code>false</code> otherwise. * @see #setFocusable * @since 1.4 */ public boolean isFocusable() { return isFocusTraversable(); } /** {@collect.stats} * Sets the focusable state of this Component to the specified value. This * value overrides the Component's default focusability. * * @param focusable indicates whether this Component is focusable * @see #isFocusable * @since 1.4 * @beaninfo * bound: true */ public void setFocusable(boolean focusable) { boolean oldFocusable; synchronized (this) { oldFocusable = this.focusable; this.focusable = focusable; } isFocusTraversableOverridden = FOCUS_TRAVERSABLE_SET; firePropertyChange("focusable", oldFocusable, focusable); if (oldFocusable && !focusable) { if (isFocusOwner()) { autoTransferFocus(true); } KeyboardFocusManager.clearMostRecentFocusOwner(this); } } final boolean isFocusTraversableOverridden() { return (isFocusTraversableOverridden != FOCUS_TRAVERSABLE_DEFAULT); } /** {@collect.stats} * Sets the focus traversal keys for a given traversal operation for this * Component. * <p> * The default values for a Component's focus traversal keys are * implementation-dependent. Sun recommends that all implementations for a * particular native platform use the same default values. The * recommendations for Windows and Unix are listed below. These * recommendations are used in the Sun AWT implementations. * * <table border=1 summary="Recommended default values for a Component's focus traversal keys"> * <tr> * <th>Identifier</th> * <th>Meaning</th> * <th>Default</th> * </tr> * <tr> * <td>KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS</td> * <td>Normal forward keyboard traversal</td> * <td>TAB on KEY_PRESSED, CTRL-TAB on KEY_PRESSED</td> * </tr> * <tr> * <td>KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS</td> * <td>Normal reverse keyboard traversal</td> * <td>SHIFT-TAB on KEY_PRESSED, CTRL-SHIFT-TAB on KEY_PRESSED</td> * </tr> * <tr> * <td>KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS</td> * <td>Go up one focus traversal cycle</td> * <td>none</td> * </tr> * </table> * * To disable a traversal key, use an empty Set; Collections.EMPTY_SET is * recommended. * <p> * Using the AWTKeyStroke API, client code can specify on which of two * specific KeyEvents, KEY_PRESSED or KEY_RELEASED, the focus traversal * operation will occur. Regardless of which KeyEvent is specified, * however, all KeyEvents related to the focus traversal key, including the * associated KEY_TYPED event, will be consumed, and will not be dispatched * to any Component. It is a runtime error to specify a KEY_TYPED event as * mapping to a focus traversal operation, or to map the same event to * multiple default focus traversal operations. * <p> * If a value of null is specified for the Set, this Component inherits the * Set from its parent. If all ancestors of this Component have null * specified for the Set, then the current KeyboardFocusManager's default * Set is used. * * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS * @param keystrokes the Set of AWTKeyStroke for the specified operation * @see #getFocusTraversalKeys * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS * @throws IllegalArgumentException if id is not one of * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes * contains null, or if any Object in keystrokes is not an * AWTKeyStroke, or if any keystroke represents a KEY_TYPED event, * or if any keystroke already maps to another focus traversal * operation for this Component * @since 1.4 * @beaninfo * bound: true */ public void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes) { if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { throw new IllegalArgumentException("invalid focus traversal key identifier"); } setFocusTraversalKeys_NoIDCheck(id, keystrokes); } /** {@collect.stats} * Returns the Set of focus traversal keys for a given traversal operation * for this Component. (See * <code>setFocusTraversalKeys</code> for a full description of each key.) * <p> * If a Set of traversal keys has not been explicitly defined for this * Component, then this Component's parent's Set is returned. If no Set * has been explicitly defined for any of this Component's ancestors, then * the current KeyboardFocusManager's default Set is returned. * * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS * @return the Set of AWTKeyStrokes for the specified operation. The Set * will be unmodifiable, and may be empty. null will never be * returned. * @see #setFocusTraversalKeys * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS * @throws IllegalArgumentException if id is not one of * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS * @since 1.4 */ public Set<AWTKeyStroke> getFocusTraversalKeys(int id) { if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { throw new IllegalArgumentException("invalid focus traversal key identifier"); } return getFocusTraversalKeys_NoIDCheck(id); } // We define these methods so that Container does not need to repeat this // code. Container cannot call super.<method> because Container allows // DOWN_CYCLE_TRAVERSAL_KEY while Component does not. The Component method // would erroneously generate an IllegalArgumentException for // DOWN_CYCLE_TRAVERSAL_KEY. final void setFocusTraversalKeys_NoIDCheck(int id, Set<? extends AWTKeyStroke> keystrokes) { Set oldKeys; synchronized (this) { if (focusTraversalKeys == null) { initializeFocusTraversalKeys(); } if (keystrokes != null) { for (Iterator iter = keystrokes.iterator(); iter.hasNext(); ) { Object obj = iter.next(); if (obj == null) { throw new IllegalArgumentException("cannot set null focus traversal key"); } // Fix for 6195828: //According to javadoc this method should throw IAE instead of ClassCastException if (!(obj instanceof AWTKeyStroke)) { throw new IllegalArgumentException("object is expected to be AWTKeyStroke"); } AWTKeyStroke keystroke = (AWTKeyStroke)obj; if (keystroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED) { throw new IllegalArgumentException("focus traversal keys cannot map to KEY_TYPED events"); } for (int i = 0; i < focusTraversalKeys.length; i++) { if (i == id) { continue; } if (getFocusTraversalKeys_NoIDCheck(i).contains(keystroke)) { throw new IllegalArgumentException("focus traversal keys must be unique for a Component"); } } } } oldKeys = focusTraversalKeys[id]; focusTraversalKeys[id] = (keystrokes != null) ? Collections.unmodifiableSet(new HashSet(keystrokes)) : null; } firePropertyChange(focusTraversalKeyPropertyNames[id], oldKeys, keystrokes); } final Set getFocusTraversalKeys_NoIDCheck(int id) { // Okay to return Set directly because it is an unmodifiable view Set keystrokes = (focusTraversalKeys != null) ? focusTraversalKeys[id] : null; if (keystrokes != null) { return keystrokes; } else { Container parent = this.parent; if (parent != null) { return parent.getFocusTraversalKeys(id); } else { return KeyboardFocusManager.getCurrentKeyboardFocusManager(). getDefaultFocusTraversalKeys(id); } } } /** {@collect.stats} * Returns whether the Set of focus traversal keys for the given focus * traversal operation has been explicitly defined for this Component. If * this method returns <code>false</code>, this Component is inheriting the * Set from an ancestor, or from the current KeyboardFocusManager. * * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS * @return <code>true</code> if the the Set of focus traversal keys for the * given focus traversal operation has been explicitly defined for * this Component; <code>false</code> otherwise. * @throws IllegalArgumentException if id is not one of * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS * @since 1.4 */ public boolean areFocusTraversalKeysSet(int id) { if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { throw new IllegalArgumentException("invalid focus traversal key identifier"); } return (focusTraversalKeys != null && focusTraversalKeys[id] != null); } /** {@collect.stats} * Sets whether focus traversal keys are enabled for this Component. * Components for which focus traversal keys are disabled receive key * events for focus traversal keys. Components for which focus traversal * keys are enabled do not see these events; instead, the events are * automatically converted to traversal operations. * * @param focusTraversalKeysEnabled whether focus traversal keys are * enabled for this Component * @see #getFocusTraversalKeysEnabled * @see #setFocusTraversalKeys * @see #getFocusTraversalKeys * @since 1.4 * @beaninfo * bound: true */ public void setFocusTraversalKeysEnabled(boolean focusTraversalKeysEnabled) { boolean oldFocusTraversalKeysEnabled; synchronized (this) { oldFocusTraversalKeysEnabled = this.focusTraversalKeysEnabled; this.focusTraversalKeysEnabled = focusTraversalKeysEnabled; } firePropertyChange("focusTraversalKeysEnabled", oldFocusTraversalKeysEnabled, focusTraversalKeysEnabled); } /** {@collect.stats} * Returns whether focus traversal keys are enabled for this Component. * Components for which focus traversal keys are disabled receive key * events for focus traversal keys. Components for which focus traversal * keys are enabled do not see these events; instead, the events are * automatically converted to traversal operations. * * @return whether focus traversal keys are enabled for this Component * @see #setFocusTraversalKeysEnabled * @see #setFocusTraversalKeys * @see #getFocusTraversalKeys * @since 1.4 */ public boolean getFocusTraversalKeysEnabled() { return focusTraversalKeysEnabled; } /** {@collect.stats} * Requests that this Component get the input focus, and that this * Component's top-level ancestor become the focused Window. This * component must be displayable, focusable, visible and all of * its ancestors (with the exception of the top-level Window) must * be visible for the request to be granted. Every effort will be * made to honor the request; however, in some cases it may be * impossible to do so. Developers must never assume that this * Component is the focus owner until this Component receives a * FOCUS_GAINED event. If this request is denied because this * Component's top-level Window cannot become the focused Window, * the request will be remembered and will be granted when the * Window is later focused by the user. * <p> * This method cannot be used to set the focus owner to no Component at * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code> * instead. * <p> * Because the focus behavior of this method is platform-dependent, * developers are strongly encouraged to use * <code>requestFocusInWindow</code> when possible. * * <p>Note: Not all focus transfers result from invoking this method. As * such, a component may receive focus without this or any of the other * {@code requestFocus} methods of {@code Component} being invoked. * * @see #requestFocusInWindow * @see java.awt.event.FocusEvent * @see #addFocusListener * @see #isFocusable * @see #isDisplayable * @see KeyboardFocusManager#clearGlobalFocusOwner * @since JDK1.0 */ public void requestFocus() { requestFocusHelper(false, true); } void requestFocus(CausedFocusEvent.Cause cause) { requestFocusHelper(false, true, cause); } /** {@collect.stats} * Requests that this <code>Component</code> get the input focus, * and that this <code>Component</code>'s top-level ancestor * become the focused <code>Window</code>. This component must be * displayable, focusable, visible and all of its ancestors (with * the exception of the top-level Window) must be visible for the * request to be granted. Every effort will be made to honor the * request; however, in some cases it may be impossible to do * so. Developers must never assume that this component is the * focus owner until this component receives a FOCUS_GAINED * event. If this request is denied because this component's * top-level window cannot become the focused window, the request * will be remembered and will be granted when the window is later * focused by the user. * <p> * This method returns a boolean value. If <code>false</code> is returned, * the request is <b>guaranteed to fail</b>. If <code>true</code> is * returned, the request will succeed <b>unless</b> it is vetoed, or an * extraordinary event, such as disposal of the component's peer, occurs * before the request can be granted by the native windowing system. Again, * while a return value of <code>true</code> indicates that the request is * likely to succeed, developers must never assume that this component is * the focus owner until this component receives a FOCUS_GAINED event. * <p> * This method cannot be used to set the focus owner to no component at * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code> * instead. * <p> * Because the focus behavior of this method is platform-dependent, * developers are strongly encouraged to use * <code>requestFocusInWindow</code> when possible. * <p> * Every effort will be made to ensure that <code>FocusEvent</code>s * generated as a * result of this request will have the specified temporary value. However, * because specifying an arbitrary temporary state may not be implementable * on all native windowing systems, correct behavior for this method can be * guaranteed only for lightweight <code>Component</code>s. * This method is not intended * for general use, but exists instead as a hook for lightweight component * libraries, such as Swing. * * <p>Note: Not all focus transfers result from invoking this method. As * such, a component may receive focus without this or any of the other * {@code requestFocus} methods of {@code Component} being invoked. * * @param temporary true if the focus change is temporary, * such as when the window loses the focus; for * more information on temporary focus changes see the *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> * @return <code>false</code> if the focus change request is guaranteed to * fail; <code>true</code> if it is likely to succeed * @see java.awt.event.FocusEvent * @see #addFocusListener * @see #isFocusable * @see #isDisplayable * @see KeyboardFocusManager#clearGlobalFocusOwner * @since 1.4 */ protected boolean requestFocus(boolean temporary) { return requestFocusHelper(temporary, true); } boolean requestFocus(boolean temporary, CausedFocusEvent.Cause cause) { return requestFocusHelper(temporary, true, cause); } /** {@collect.stats} * Requests that this Component get the input focus, if this * Component's top-level ancestor is already the focused * Window. This component must be displayable, focusable, visible * and all of its ancestors (with the exception of the top-level * Window) must be visible for the request to be granted. Every * effort will be made to honor the request; however, in some * cases it may be impossible to do so. Developers must never * assume that this Component is the focus owner until this * Component receives a FOCUS_GAINED event. * <p> * This method returns a boolean value. If <code>false</code> is returned, * the request is <b>guaranteed to fail</b>. If <code>true</code> is * returned, the request will succeed <b>unless</b> it is vetoed, or an * extraordinary event, such as disposal of the Component's peer, occurs * before the request can be granted by the native windowing system. Again, * while a return value of <code>true</code> indicates that the request is * likely to succeed, developers must never assume that this Component is * the focus owner until this Component receives a FOCUS_GAINED event. * <p> * This method cannot be used to set the focus owner to no Component at * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code> * instead. * <p> * The focus behavior of this method can be implemented uniformly across * platforms, and thus developers are strongly encouraged to use this * method over <code>requestFocus</code> when possible. Code which relies * on <code>requestFocus</code> may exhibit different focus behavior on * different platforms. * * <p>Note: Not all focus transfers result from invoking this method. As * such, a component may receive focus without this or any of the other * {@code requestFocus} methods of {@code Component} being invoked. * * @return <code>false</code> if the focus change request is guaranteed to * fail; <code>true</code> if it is likely to succeed * @see #requestFocus * @see java.awt.event.FocusEvent * @see #addFocusListener * @see #isFocusable * @see #isDisplayable * @see KeyboardFocusManager#clearGlobalFocusOwner * @since 1.4 */ public boolean requestFocusInWindow() { return requestFocusHelper(false, false); } boolean requestFocusInWindow(CausedFocusEvent.Cause cause) { return requestFocusHelper(false, false, cause); } /** {@collect.stats} * Requests that this <code>Component</code> get the input focus, * if this <code>Component</code>'s top-level ancestor is already * the focused <code>Window</code>. This component must be * displayable, focusable, visible and all of its ancestors (with * the exception of the top-level Window) must be visible for the * request to be granted. Every effort will be made to honor the * request; however, in some cases it may be impossible to do * so. Developers must never assume that this component is the * focus owner until this component receives a FOCUS_GAINED event. * <p> * This method returns a boolean value. If <code>false</code> is returned, * the request is <b>guaranteed to fail</b>. If <code>true</code> is * returned, the request will succeed <b>unless</b> it is vetoed, or an * extraordinary event, such as disposal of the component's peer, occurs * before the request can be granted by the native windowing system. Again, * while a return value of <code>true</code> indicates that the request is * likely to succeed, developers must never assume that this component is * the focus owner until this component receives a FOCUS_GAINED event. * <p> * This method cannot be used to set the focus owner to no component at * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code> * instead. * <p> * The focus behavior of this method can be implemented uniformly across * platforms, and thus developers are strongly encouraged to use this * method over <code>requestFocus</code> when possible. Code which relies * on <code>requestFocus</code> may exhibit different focus behavior on * different platforms. * <p> * Every effort will be made to ensure that <code>FocusEvent</code>s * generated as a * result of this request will have the specified temporary value. However, * because specifying an arbitrary temporary state may not be implementable * on all native windowing systems, correct behavior for this method can be * guaranteed only for lightweight components. This method is not intended * for general use, but exists instead as a hook for lightweight component * libraries, such as Swing. * * <p>Note: Not all focus transfers result from invoking this method. As * such, a component may receive focus without this or any of the other * {@code requestFocus} methods of {@code Component} being invoked. * * @param temporary true if the focus change is temporary, * such as when the window loses the focus; for * more information on temporary focus changes see the *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> * @return <code>false</code> if the focus change request is guaranteed to * fail; <code>true</code> if it is likely to succeed * @see #requestFocus * @see java.awt.event.FocusEvent * @see #addFocusListener * @see #isFocusable * @see #isDisplayable * @see KeyboardFocusManager#clearGlobalFocusOwner * @since 1.4 */ protected boolean requestFocusInWindow(boolean temporary) { return requestFocusHelper(temporary, false); } boolean requestFocusInWindow(boolean temporary, CausedFocusEvent.Cause cause) { return requestFocusHelper(temporary, false, cause); } final boolean requestFocusHelper(boolean temporary, boolean focusedWindowChangeAllowed) { return requestFocusHelper(temporary, focusedWindowChangeAllowed, CausedFocusEvent.Cause.UNKNOWN); } final boolean requestFocusHelper(boolean temporary, boolean focusedWindowChangeAllowed, CausedFocusEvent.Cause cause) { if (!isRequestFocusAccepted(temporary, focusedWindowChangeAllowed, cause)) { if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "requestFocus is not accepted"); } return false; } // Update most-recent map KeyboardFocusManager.setMostRecentFocusOwner(this); Component window = this; while ( (window != null) && !(window instanceof Window)) { if (!window.isVisible()) { if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "component is recurively invisible"); } return false; } window = window.parent; } ComponentPeer peer = this.peer; Component heavyweight = (peer instanceof LightweightPeer) ? getNativeContainer() : this; if (heavyweight == null || !heavyweight.isVisible()) { if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "Component is not a part of visible hierarchy"); } return false; } peer = heavyweight.peer; if (peer == null) { if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "Peer is null"); } return false; } // Focus this Component long time = EventQueue.getMostRecentEventTime(); boolean success = peer.requestFocus (this, temporary, focusedWindowChangeAllowed, time, cause); if (!success) { KeyboardFocusManager.getCurrentKeyboardFocusManager (appContext).dequeueKeyEvents(time, this); if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "Peer request failed"); } } else { if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "Pass for " + this); } } return success; } private boolean isRequestFocusAccepted(boolean temporary, boolean focusedWindowChangeAllowed, CausedFocusEvent.Cause cause) { if (!isFocusable() || !isVisible()) { if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "Not focusable or not visible"); } return false; } ComponentPeer peer = this.peer; if (peer == null) { if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "peer is null"); } return false; } Window window = getContainingWindow(); if (window == null || !((Window)window).isFocusableWindow()) { if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "Component doesn't have toplevel"); } return false; } // We have passed all regular checks for focus request, // now let's call RequestFocusController and see what it says. Component focusOwner = KeyboardFocusManager.getMostRecentFocusOwner(window); if (focusOwner == null) { // sometimes most recent focus owner may be null, but focus owner is not // e.g. we reset most recent focus owner if user removes focus owner focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (focusOwner != null && getContainingWindow(focusOwner) != window) { focusOwner = null; } } if (focusOwner == this || focusOwner == null) { // Controller is supposed to verify focus transfers and for this it // should know both from and to components. And it shouldn't verify // transfers from when these components are equal. if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "focus owner is null or this"); } return true; } if (CausedFocusEvent.Cause.ACTIVATION == cause) { // we shouldn't call RequestFocusController in case we are // in activation. We do request focus on component which // has got temporary focus lost and then on component which is // most recent focus owner. But most recent focus owner can be // changed by requestFocsuXXX() call only, so this transfer has // been already approved. if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "cause is activation"); } return true; } boolean ret = Component.requestFocusController.acceptRequestFocus(focusOwner, this, temporary, focusedWindowChangeAllowed, cause); if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "RequestFocusController returns {0}", ret); } return ret; } private static RequestFocusController requestFocusController = new DummyRequestFocusController(); // Swing access this method through reflection to implement InputVerifier's functionality. // Perhaps, we should make this method public (later ;) private static class DummyRequestFocusController implements RequestFocusController { public boolean acceptRequestFocus(Component from, Component to, boolean temporary, boolean focusedWindowChangeAllowed, CausedFocusEvent.Cause cause) { return true; } }; synchronized static void setRequestFocusController(RequestFocusController requestController) { if (requestController == null) { requestFocusController = new DummyRequestFocusController(); } else { requestFocusController = requestController; } } private void autoTransferFocus(boolean clearOnFailure) { Component toTest = KeyboardFocusManager. getCurrentKeyboardFocusManager().getFocusOwner(); if (toTest != this) { if (toTest != null) { toTest.autoTransferFocus(clearOnFailure); } return; } // Check if there are pending focus requests. We shouldn't do // auto-transfer if user has already took care of this // component becoming ineligible to hold focus. if (!KeyboardFocusManager.isAutoFocusTransferEnabled()) { return; } // the following code will execute only if this Component is the focus // owner if (!(isDisplayable() && isVisible() && isEnabled() && isFocusable())) { doAutoTransfer(clearOnFailure); return; } toTest = getParent(); while (toTest != null && !(toTest instanceof Window)) { if (!(toTest.isDisplayable() && toTest.isVisible() && (toTest.isEnabled() || toTest.isLightweight()))) { doAutoTransfer(clearOnFailure); return; } toTest = toTest.getParent(); } } private void doAutoTransfer(boolean clearOnFailure) { if (focusLog.isLoggable(Level.FINER)) { focusLog.log(Level.FINER, "this = " + this + ", clearOnFailure = " + clearOnFailure); } if (clearOnFailure) { if (!nextFocusHelper()) { if (focusLog.isLoggable(Level.FINER)) { focusLog.log(Level.FINER, "clear global focus owner"); } KeyboardFocusManager.getCurrentKeyboardFocusManager(). clearGlobalFocusOwner(); } } else { transferFocus(); } } /** {@collect.stats} * Transfers the focus to the next component, as though this Component were * the focus owner. * @see #requestFocus() * @since JDK1.1 */ public void transferFocus() { nextFocus(); } /** {@collect.stats} * Returns the Container which is the focus cycle root of this Component's * focus traversal cycle. Each focus traversal cycle has only a single * focus cycle root and each Component which is not a Container belongs to * only a single focus traversal cycle. Containers which are focus cycle * roots belong to two cycles: one rooted at the Container itself, and one * rooted at the Container's nearest focus-cycle-root ancestor. For such * Containers, this method will return the Container's nearest focus-cycle- * root ancestor. * * @return this Component's nearest focus-cycle-root ancestor * @see Container#isFocusCycleRoot() * @since 1.4 */ public Container getFocusCycleRootAncestor() { Container rootAncestor = this.parent; while (rootAncestor != null && !rootAncestor.isFocusCycleRoot()) { rootAncestor = rootAncestor.parent; } return rootAncestor; } /** {@collect.stats} * Returns whether the specified Container is the focus cycle root of this * Component's focus traversal cycle. Each focus traversal cycle has only * a single focus cycle root and each Component which is not a Container * belongs to only a single focus traversal cycle. * * @param container the Container to be tested * @return <code>true</code> if the specified Container is a focus-cycle- * root of this Component; <code>false</code> otherwise * @see Container#isFocusCycleRoot() * @since 1.4 */ public boolean isFocusCycleRoot(Container container) { Container rootAncestor = getFocusCycleRootAncestor(); return (rootAncestor == container); } /** {@collect.stats} * @deprecated As of JDK version 1.1, * replaced by transferFocus(). */ @Deprecated public void nextFocus() { nextFocusHelper(); } private boolean nextFocusHelper() { Component toFocus = preNextFocusHelper(); if (focusLog.isLoggable(Level.FINER)) { focusLog.log(Level.FINER, "toFocus = " + toFocus); } if (isFocusOwner() && toFocus == this) { return false; } return postNextFocusHelper(toFocus, CausedFocusEvent.Cause.TRAVERSAL_FORWARD); } Container getTraversalRoot() { return getFocusCycleRootAncestor(); } final Component preNextFocusHelper() { Container rootAncestor = getTraversalRoot(); Component comp = this; while (rootAncestor != null && !(rootAncestor.isShowing() && rootAncestor.isFocusable() && rootAncestor.isEnabled())) { comp = rootAncestor; rootAncestor = comp.getFocusCycleRootAncestor(); } if (focusLog.isLoggable(Level.FINER)) { focusLog.log(Level.FINER, "comp = " + comp + ", root = " + rootAncestor); } if (rootAncestor != null) { FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy(); Component toFocus = policy.getComponentAfter(rootAncestor, comp); if (focusLog.isLoggable(Level.FINER)) { focusLog.log(Level.FINER, "component after is " + toFocus); } if (toFocus == null) { toFocus = policy.getDefaultComponent(rootAncestor); if (focusLog.isLoggable(Level.FINER)) { focusLog.log(Level.FINER, "default component is " + toFocus); } } if (toFocus == null) { Applet applet = EmbeddedFrame.getAppletIfAncestorOf(this); if (applet != null) { toFocus = applet; } } return toFocus; } return null; } static boolean postNextFocusHelper(Component toFocus, CausedFocusEvent.Cause cause) { if (toFocus != null) { if (focusLog.isLoggable(Level.FINER)) { focusLog.log(Level.FINER, "Next component " + toFocus); } boolean res = toFocus.requestFocusInWindow(cause); if (focusLog.isLoggable(Level.FINER)) { focusLog.log(Level.FINER, "Request focus returned " + res); } return res; } return false; } /** {@collect.stats} * Transfers the focus to the previous component, as though this Component * were the focus owner. * @see #requestFocus() * @since 1.4 */ public void transferFocusBackward() { Container rootAncestor = getTraversalRoot(); Component comp = this; while (rootAncestor != null && !(rootAncestor.isShowing() && rootAncestor.isFocusable() && rootAncestor.isEnabled())) { comp = rootAncestor; rootAncestor = comp.getFocusCycleRootAncestor(); } if (rootAncestor != null) { FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy(); Component toFocus = policy.getComponentBefore(rootAncestor, comp); if (toFocus == null) { toFocus = policy.getDefaultComponent(rootAncestor); } if (toFocus != null) { toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_BACKWARD); } } } /** {@collect.stats} * Transfers the focus up one focus traversal cycle. Typically, the focus * owner is set to this Component's focus cycle root, and the current focus * cycle root is set to the new focus owner's focus cycle root. If, * however, this Component's focus cycle root is a Window, then the focus * owner is set to the focus cycle root's default Component to focus, and * the current focus cycle root is unchanged. * * @see #requestFocus() * @see Container#isFocusCycleRoot() * @see Container#setFocusCycleRoot(boolean) * @since 1.4 */ public void transferFocusUpCycle() { Container rootAncestor; for (rootAncestor = getFocusCycleRootAncestor(); rootAncestor != null && !(rootAncestor.isShowing() && rootAncestor.isFocusable() && rootAncestor.isEnabled()); rootAncestor = rootAncestor.getFocusCycleRootAncestor()) { } if (rootAncestor != null) { Container rootAncestorRootAncestor = rootAncestor.getFocusCycleRootAncestor(); KeyboardFocusManager.getCurrentKeyboardFocusManager(). setGlobalCurrentFocusCycleRoot( (rootAncestorRootAncestor != null) ? rootAncestorRootAncestor : rootAncestor); rootAncestor.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP); } else { Window window = getContainingWindow(); if (window != null) { Component toFocus = window.getFocusTraversalPolicy(). getDefaultComponent(window); if (toFocus != null) { KeyboardFocusManager.getCurrentKeyboardFocusManager(). setGlobalCurrentFocusCycleRoot(window); toFocus.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP); } } } } /** {@collect.stats} * Returns <code>true</code> if this <code>Component</code> is the * focus owner. This method is obsolete, and has been replaced by * <code>isFocusOwner()</code>. * * @return <code>true</code> if this <code>Component</code> is the * focus owner; <code>false</code> otherwise * @since 1.2 */ public boolean hasFocus() { return (KeyboardFocusManager.getCurrentKeyboardFocusManager(). getFocusOwner() == this); } /** {@collect.stats} * Returns <code>true</code> if this <code>Component</code> is the * focus owner. * * @return <code>true</code> if this <code>Component</code> is the * focus owner; <code>false</code> otherwise * @since 1.4 */ public boolean isFocusOwner() { return hasFocus(); } /** {@collect.stats} * Adds the specified popup menu to the component. * @param popup the popup menu to be added to the component. * @see #remove(MenuComponent) * @exception NullPointerException if {@code popup} is {@code null} * @since JDK1.1 */ public void add(PopupMenu popup) { synchronized (getTreeLock()) { if (popup.parent != null) { popup.parent.remove(popup); } if (popups == null) { popups = new Vector(); } popups.addElement(popup); popup.parent = this; if (peer != null) { if (popup.peer == null) { popup.addNotify(); } } } } /** {@collect.stats} * Removes the specified popup menu from the component. * @param popup the popup menu to be removed * @see #add(PopupMenu) * @since JDK1.1 */ public void remove(MenuComponent popup) { synchronized (getTreeLock()) { if (popups == null) { return; } int index = popups.indexOf(popup); if (index >= 0) { PopupMenu pmenu = (PopupMenu)popup; if (pmenu.peer != null) { pmenu.removeNotify(); } pmenu.parent = null; popups.removeElementAt(index); if (popups.size() == 0) { popups = null; } } } } /** {@collect.stats} * Returns a string representing the state of this component. This * method is intended to be used only for debugging purposes, and the * content and format of the returned string may vary between * implementations. The returned string may be empty but may not be * <code>null</code>. * * @return a string representation of this component's state * @since JDK1.0 */ protected String paramString() { String thisName = getName(); String str = (thisName != null? thisName : "") + "," + x + "," + y + "," + width + "x" + height; if (!valid) { str += ",invalid"; } if (!visible) { str += ",hidden"; } if (!enabled) { str += ",disabled"; } return str; } /** {@collect.stats} * Returns a string representation of this component and its values. * @return a string representation of this component * @since JDK1.0 */ public String toString() { return getClass().getName() + "[" + paramString() + "]"; } /** {@collect.stats} * Prints a listing of this component to the standard system output * stream <code>System.out</code>. * @see java.lang.System#out * @since JDK1.0 */ public void list() { list(System.out, 0); } /** {@collect.stats} * Prints a listing of this component to the specified output * stream. * @param out a print stream * @since JDK1.0 */ public void list(PrintStream out) { list(out, 0); } /** {@collect.stats} * Prints out a list, starting at the specified indentation, to the * specified print stream. * @param out a print stream * @param indent number of spaces to indent * @see java.io.PrintStream#println(java.lang.Object) * @since JDK1.0 */ public void list(PrintStream out, int indent) { for (int i = 0 ; i < indent ; i++) { out.print(" "); } out.println(this); } /** {@collect.stats} * Prints a listing to the specified print writer. * @param out the print writer to print to * @since JDK1.1 */ public void list(PrintWriter out) { list(out, 0); } /** {@collect.stats} * Prints out a list, starting at the specified indentation, to * the specified print writer. * @param out the print writer to print to * @param indent the number of spaces to indent * @see java.io.PrintStream#println(java.lang.Object) * @since JDK1.1 */ public void list(PrintWriter out, int indent) { for (int i = 0 ; i < indent ; i++) { out.print(" "); } out.println(this); } /* * Fetches the native container somewhere higher up in the component * tree that contains this component. */ Container getNativeContainer() { Container p = parent; while (p != null && p.peer instanceof LightweightPeer) { p = p.getParent(); } return p; } /** {@collect.stats} * Adds a PropertyChangeListener to the listener list. The listener is * registered for all bound properties of this class, including the * following: * <ul> * <li>this Component's font ("font")</li> * <li>this Component's background color ("background")</li> * <li>this Component's foreground color ("foreground")</li> * <li>this Component's focusability ("focusable")</li> * <li>this Component's focus traversal keys enabled state * ("focusTraversalKeysEnabled")</li> * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS * ("forwardFocusTraversalKeys")</li> * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS * ("backwardFocusTraversalKeys")</li> * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS * ("upCycleFocusTraversalKeys")</li> * <li>this Component's preferred size ("preferredSize")</li> * <li>this Component's minimum size ("minimumSize")</li> * <li>this Component's maximum size ("maximumSize")</li> * <li>this Component's name ("name")</li> * </ul> * Note that if this <code>Component</code> is inheriting a bound property, then no * event will be fired in response to a change in the inherited property. * <p> * If <code>listener</code> is <code>null</code>, * no exception is thrown and no action is performed. * * @param listener the property change listener to be added * * @see #removePropertyChangeListener * @see #getPropertyChangeListeners * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) */ public void addPropertyChangeListener( PropertyChangeListener listener) { synchronized (getChangeSupportLock()) { if (listener == null) { return; } if (changeSupport == null) { changeSupport = new PropertyChangeSupport(this); } changeSupport.addPropertyChangeListener(listener); } } /** {@collect.stats} * Removes a PropertyChangeListener from the listener list. This method * should be used to remove PropertyChangeListeners that were registered * for all bound properties of this class. * <p> * If listener is null, no exception is thrown and no action is performed. * * @param listener the PropertyChangeListener to be removed * * @see #addPropertyChangeListener * @see #getPropertyChangeListeners * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener) */ public void removePropertyChangeListener( PropertyChangeListener listener) { synchronized (getChangeSupportLock()) { if (listener == null || changeSupport == null) { return; } changeSupport.removePropertyChangeListener(listener); } } /** {@collect.stats} * Returns an array of all the property change listeners * registered on this component. * * @return all of this component's <code>PropertyChangeListener</code>s * or an empty array if no property change * listeners are currently registered * * @see #addPropertyChangeListener * @see #removePropertyChangeListener * @see #getPropertyChangeListeners(java.lang.String) * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners * @since 1.4 */ public PropertyChangeListener[] getPropertyChangeListeners() { synchronized (getChangeSupportLock()) { if (changeSupport == null) { return new PropertyChangeListener[0]; } return changeSupport.getPropertyChangeListeners(); } } /** {@collect.stats} * Adds a PropertyChangeListener to the listener list for a specific * property. The specified property may be user-defined, or one of the * following: * <ul> * <li>this Component's font ("font")</li> * <li>this Component's background color ("background")</li> * <li>this Component's foreground color ("foreground")</li> * <li>this Component's focusability ("focusable")</li> * <li>this Component's focus traversal keys enabled state * ("focusTraversalKeysEnabled")</li> * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS * ("forwardFocusTraversalKeys")</li> * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS * ("backwardFocusTraversalKeys")</li> * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS * ("upCycleFocusTraversalKeys")</li> * </ul> * Note that if this <code>Component</code> is inheriting a bound property, then no * event will be fired in response to a change in the inherited property. * <p> * If <code>propertyName</code> or <code>listener</code> is <code>null</code>, * no exception is thrown and no action is taken. * * @param propertyName one of the property names listed above * @param listener the property change listener to be added * * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) * @see #getPropertyChangeListeners(java.lang.String) * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) */ public void addPropertyChangeListener( String propertyName, PropertyChangeListener listener) { synchronized (getChangeSupportLock()) { if (listener == null) { return; } if (changeSupport == null) { changeSupport = new PropertyChangeSupport(this); } changeSupport.addPropertyChangeListener(propertyName, listener); } } /** {@collect.stats} * Removes a <code>PropertyChangeListener</code> from the listener * list for a specific property. This method should be used to remove * <code>PropertyChangeListener</code>s * that were registered for a specific bound property. * <p> * If <code>propertyName</code> or <code>listener</code> is <code>null</code>, * no exception is thrown and no action is taken. * * @param propertyName a valid property name * @param listener the PropertyChangeListener to be removed * * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) * @see #getPropertyChangeListeners(java.lang.String) * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) */ public void removePropertyChangeListener( String propertyName, PropertyChangeListener listener) { synchronized (getChangeSupportLock()) { if (listener == null || changeSupport == null) { return; } changeSupport.removePropertyChangeListener(propertyName, listener); } } /** {@collect.stats} * Returns an array of all the listeners which have been associated * with the named property. * * @return all of the <code>PropertyChangeListener</code>s associated with * the named property; if no such listeners have been added or * if <code>propertyName</code> is <code>null</code>, an empty * array is returned * * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) * @see #getPropertyChangeListeners * @since 1.4 */ public PropertyChangeListener[] getPropertyChangeListeners( String propertyName) { synchronized (getChangeSupportLock()) { if (changeSupport == null) { return new PropertyChangeListener[0]; } return changeSupport.getPropertyChangeListeners(propertyName); } } /** {@collect.stats} * Support for reporting bound property changes for Object properties. * This method can be called when a bound property has changed and it will * send the appropriate PropertyChangeEvent to any registered * PropertyChangeListeners. * * @param propertyName the property whose value has changed * @param oldValue the property's previous value * @param newValue the property's new value */ protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { PropertyChangeSupport changeSupport; synchronized (getChangeSupportLock()) { changeSupport = this.changeSupport; } if (changeSupport == null || (oldValue != null && newValue != null && oldValue.equals(newValue))) { return; } changeSupport.firePropertyChange(propertyName, oldValue, newValue); } /** {@collect.stats} * Support for reporting bound property changes for boolean properties. * This method can be called when a bound property has changed and it will * send the appropriate PropertyChangeEvent to any registered * PropertyChangeListeners. * * @param propertyName the property whose value has changed * @param oldValue the property's previous value * @param newValue the property's new value * @since 1.4 */ protected void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { PropertyChangeSupport changeSupport = this.changeSupport; if (changeSupport == null || oldValue == newValue) { return; } changeSupport.firePropertyChange(propertyName, oldValue, newValue); } /** {@collect.stats} * Support for reporting bound property changes for integer properties. * This method can be called when a bound property has changed and it will * send the appropriate PropertyChangeEvent to any registered * PropertyChangeListeners. * * @param propertyName the property whose value has changed * @param oldValue the property's previous value * @param newValue the property's new value * @since 1.4 */ protected void firePropertyChange(String propertyName, int oldValue, int newValue) { PropertyChangeSupport changeSupport = this.changeSupport; if (changeSupport == null || oldValue == newValue) { return; } changeSupport.firePropertyChange(propertyName, oldValue, newValue); } /** {@collect.stats} * Reports a bound property change. * * @param propertyName the programmatic name of the property * that was changed * @param oldValue the old value of the property (as a byte) * @param newValue the new value of the property (as a byte) * @see #firePropertyChange(java.lang.String, java.lang.Object, * java.lang.Object) * @since 1.5 */ public void firePropertyChange(String propertyName, byte oldValue, byte newValue) { if (changeSupport == null || oldValue == newValue) { return; } firePropertyChange(propertyName, Byte.valueOf(oldValue), Byte.valueOf(newValue)); } /** {@collect.stats} * Reports a bound property change. * * @param propertyName the programmatic name of the property * that was changed * @param oldValue the old value of the property (as a char) * @param newValue the new value of the property (as a char) * @see #firePropertyChange(java.lang.String, java.lang.Object, * java.lang.Object) * @since 1.5 */ public void firePropertyChange(String propertyName, char oldValue, char newValue) { if (changeSupport == null || oldValue == newValue) { return; } firePropertyChange(propertyName, new Character(oldValue), new Character(newValue)); } /** {@collect.stats} * Reports a bound property change. * * @param propertyName the programmatic name of the property * that was changed * @param oldValue the old value of the property (as a short) * @param newValue the old value of the property (as a short) * @see #firePropertyChange(java.lang.String, java.lang.Object, * java.lang.Object) * @since 1.5 */ public void firePropertyChange(String propertyName, short oldValue, short newValue) { if (changeSupport == null || oldValue == newValue) { return; } firePropertyChange(propertyName, Short.valueOf(oldValue), Short.valueOf(newValue)); } /** {@collect.stats} * Reports a bound property change. * * @param propertyName the programmatic name of the property * that was changed * @param oldValue the old value of the property (as a long) * @param newValue the new value of the property (as a long) * @see #firePropertyChange(java.lang.String, java.lang.Object, * java.lang.Object) * @since 1.5 */ public void firePropertyChange(String propertyName, long oldValue, long newValue) { if (changeSupport == null || oldValue == newValue) { return; } firePropertyChange(propertyName, Long.valueOf(oldValue), Long.valueOf(newValue)); } /** {@collect.stats} * Reports a bound property change. * * @param propertyName the programmatic name of the property * that was changed * @param oldValue the old value of the property (as a float) * @param newValue the new value of the property (as a float) * @see #firePropertyChange(java.lang.String, java.lang.Object, * java.lang.Object) * @since 1.5 */ public void firePropertyChange(String propertyName, float oldValue, float newValue) { if (changeSupport == null || oldValue == newValue) { return; } firePropertyChange(propertyName, Float.valueOf(oldValue), Float.valueOf(newValue)); } /** {@collect.stats} * Reports a bound property change. * * @param propertyName the programmatic name of the property * that was changed * @param oldValue the old value of the property (as a double) * @param newValue the new value of the property (as a double) * @see #firePropertyChange(java.lang.String, java.lang.Object, * java.lang.Object) * @since 1.5 */ public void firePropertyChange(String propertyName, double oldValue, double newValue) { if (changeSupport == null || oldValue == newValue) { return; } firePropertyChange(propertyName, Double.valueOf(oldValue), Double.valueOf(newValue)); } // Serialization support. /** {@collect.stats} * Component Serialized Data Version. * * @serial */ private int componentSerializedDataVersion = 4; /** {@collect.stats} * This hack is for Swing serialization. It will invoke * the Swing package private method <code>compWriteObjectNotify</code>. */ private void doSwingSerialization() { Package swingPackage = Package.getPackage("javax.swing"); // For Swing serialization to correctly work Swing needs to // be notified before Component does it's serialization. This // hack accomodates this. // // Swing classes MUST be loaded by the bootstrap class loader, // otherwise we don't consider them. for (Class klass = Component.this.getClass(); klass != null; klass = klass.getSuperclass()) { if (klass.getPackage() == swingPackage && klass.getClassLoader() == null) { final Class swingClass = klass; // Find the first override of the compWriteObjectNotify method Method[] methods = (Method[])AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return swingClass.getDeclaredMethods(); } }); for (int counter = methods.length - 1; counter >= 0; counter--) { final Method method = methods[counter]; if (method.getName().equals("compWriteObjectNotify")){ // We found it, use doPrivileged to make it accessible // to use. AccessController.doPrivileged(new PrivilegedAction() { public Object run() { method.setAccessible(true); return null; } }); // Invoke the method try { method.invoke(this, (Object[]) null); } catch (IllegalAccessException iae) { } catch (InvocationTargetException ite) { } // We're done, bail. return; } } } } } /** {@collect.stats} * Writes default serializable fields to stream. Writes * a variety of serializable listeners as optional data. * The non-serializable listeners are detected and * no attempt is made to serialize them. * * @param s the <code>ObjectOutputStream</code> to write * @serialData <code>null</code> terminated sequence of * 0 or more pairs; the pair consists of a <code>String</code> * and an <code>Object</code>; the <code>String</code> indicates * the type of object and is one of the following (as of 1.4): * <code>componentListenerK</code> indicating an * <code>ComponentListener</code> object; * <code>focusListenerK</code> indicating an * <code>FocusListener</code> object; * <code>keyListenerK</code> indicating an * <code>KeyListener</code> object; * <code>mouseListenerK</code> indicating an * <code>MouseListener</code> object; * <code>mouseMotionListenerK</code> indicating an * <code>MouseMotionListener</code> object; * <code>inputMethodListenerK</code> indicating an * <code>InputMethodListener</code> object; * <code>hierarchyListenerK</code> indicating an * <code>HierarchyListener</code> object; * <code>hierarchyBoundsListenerK</code> indicating an * <code>HierarchyBoundsListener</code> object; * <code>mouseWheelListenerK</code> indicating an * <code>MouseWheelListener</code> object * @serialData an optional <code>ComponentOrientation</code> * (after <code>inputMethodListener</code>, as of 1.2) * * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener) * @see #componentListenerK * @see #focusListenerK * @see #keyListenerK * @see #mouseListenerK * @see #mouseMotionListenerK * @see #inputMethodListenerK * @see #hierarchyListenerK * @see #hierarchyBoundsListenerK * @see #mouseWheelListenerK * @see #readObject(ObjectInputStream) */ private void writeObject(ObjectOutputStream s) throws IOException { doSwingSerialization(); s.defaultWriteObject(); AWTEventMulticaster.save(s, componentListenerK, componentListener); AWTEventMulticaster.save(s, focusListenerK, focusListener); AWTEventMulticaster.save(s, keyListenerK, keyListener); AWTEventMulticaster.save(s, mouseListenerK, mouseListener); AWTEventMulticaster.save(s, mouseMotionListenerK, mouseMotionListener); AWTEventMulticaster.save(s, inputMethodListenerK, inputMethodListener); s.writeObject(null); s.writeObject(componentOrientation); AWTEventMulticaster.save(s, hierarchyListenerK, hierarchyListener); AWTEventMulticaster.save(s, hierarchyBoundsListenerK, hierarchyBoundsListener); s.writeObject(null); AWTEventMulticaster.save(s, mouseWheelListenerK, mouseWheelListener); s.writeObject(null); } /** {@collect.stats} * Reads the <code>ObjectInputStream</code> and if it isn't * <code>null</code> adds a listener to receive a variety * of events fired by the component. * Unrecognized keys or values will be ignored. * * @param s the <code>ObjectInputStream</code> to read * @see #writeObject(ObjectOutputStream) */ private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { changeSupportLock = new Object(); acc = AccessController.getContext(); s.defaultReadObject(); appContext = AppContext.getAppContext(); coalescingEnabled = checkCoalescing(); if (componentSerializedDataVersion < 4) { // These fields are non-transient and rely on default // serialization. However, the default values are insufficient, // so we need to set them explicitly for object data streams prior // to 1.4. focusable = true; isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN; initializeFocusTraversalKeys(); focusTraversalKeysEnabled = true; } Object keyOrNull; while(null != (keyOrNull = s.readObject())) { String key = ((String)keyOrNull).intern(); if (componentListenerK == key) addComponentListener((ComponentListener)(s.readObject())); else if (focusListenerK == key) addFocusListener((FocusListener)(s.readObject())); else if (keyListenerK == key) addKeyListener((KeyListener)(s.readObject())); else if (mouseListenerK == key) addMouseListener((MouseListener)(s.readObject())); else if (mouseMotionListenerK == key) addMouseMotionListener((MouseMotionListener)(s.readObject())); else if (inputMethodListenerK == key) addInputMethodListener((InputMethodListener)(s.readObject())); else // skip value for unrecognized key s.readObject(); } // Read the component's orientation if it's present Object orient = null; try { orient = s.readObject(); } catch (java.io.OptionalDataException e) { // JDK 1.1 instances will not have this optional data. // e.eof will be true to indicate that there is no more // data available for this object. // If e.eof is not true, throw the exception as it // might have been caused by reasons unrelated to // componentOrientation. if (!e.eof) { throw (e); } } if (orient != null) { componentOrientation = (ComponentOrientation)orient; } else { componentOrientation = ComponentOrientation.UNKNOWN; } try { while(null != (keyOrNull = s.readObject())) { String key = ((String)keyOrNull).intern(); if (hierarchyListenerK == key) { addHierarchyListener((HierarchyListener)(s.readObject())); } else if (hierarchyBoundsListenerK == key) { addHierarchyBoundsListener((HierarchyBoundsListener) (s.readObject())); } else { // skip value for unrecognized key s.readObject(); } } } catch (java.io.OptionalDataException e) { // JDK 1.1/1.2 instances will not have this optional data. // e.eof will be true to indicate that there is no more // data available for this object. // If e.eof is not true, throw the exception as it // might have been caused by reasons unrelated to // hierarchy and hierarchyBounds listeners. if (!e.eof) { throw (e); } } try { while (null != (keyOrNull = s.readObject())) { String key = ((String)keyOrNull).intern(); if (mouseWheelListenerK == key) { addMouseWheelListener((MouseWheelListener)(s.readObject())); } else { // skip value for unrecognized key s.readObject(); } } } catch (java.io.OptionalDataException e) { // pre-1.3 instances will not have this optional data. // e.eof will be true to indicate that there is no more // data available for this object. // If e.eof is not true, throw the exception as it // might have been caused by reasons unrelated to // mouse wheel listeners if (!e.eof) { throw (e); } } if (popups != null) { int npopups = popups.size(); for (int i = 0 ; i < npopups ; i++) { PopupMenu popup = (PopupMenu)popups.elementAt(i); popup.parent = this; } } } /** {@collect.stats} * Sets the language-sensitive orientation that is to be used to order * the elements or text within this component. Language-sensitive * <code>LayoutManager</code> and <code>Component</code> * subclasses will use this property to * determine how to lay out and draw components. * <p> * At construction time, a component's orientation is set to * <code>ComponentOrientation.UNKNOWN</code>, * indicating that it has not been specified * explicitly. The UNKNOWN orientation behaves the same as * <code>ComponentOrientation.LEFT_TO_RIGHT</code>. * <p> * To set the orientation of a single component, use this method. * To set the orientation of an entire component * hierarchy, use * {@link #applyComponentOrientation applyComponentOrientation}. * * @see ComponentOrientation * * @author Laura Werner, IBM * @beaninfo * bound: true */ public void setComponentOrientation(ComponentOrientation o) { ComponentOrientation oldValue = componentOrientation; componentOrientation = o; // This is a bound property, so report the change to // any registered listeners. (Cheap if there are none.) firePropertyChange("componentOrientation", oldValue, o); // This could change the preferred size of the Component. if (valid) { invalidate(); } } /** {@collect.stats} * Retrieves the language-sensitive orientation that is to be used to order * the elements or text within this component. <code>LayoutManager</code> * and <code>Component</code> * subclasses that wish to respect orientation should call this method to * get the component's orientation before performing layout or drawing. * * @see ComponentOrientation * * @author Laura Werner, IBM */ public ComponentOrientation getComponentOrientation() { return componentOrientation; } /** {@collect.stats} * Sets the <code>ComponentOrientation</code> property of this component * and all components contained within it. * * @param orientation the new component orientation of this component and * the components contained within it. * @exception NullPointerException if <code>orientation</code> is null. * @see #setComponentOrientation * @see #getComponentOrientation * @since 1.4 */ public void applyComponentOrientation(ComponentOrientation orientation) { if (orientation == null) { throw new NullPointerException(); } setComponentOrientation(orientation); } transient NativeInLightFixer nativeInLightFixer; /** {@collect.stats} * Checks that this component meets the prerequesites to be focus owner: * - it is enabled, visible, focusable * - it's parents are all enabled and showing * - top-level window is focusable * - if focus cycle root has DefaultFocusTraversalPolicy then it also checks that this policy accepts * this component as focus owner * @since 1.5 */ final boolean canBeFocusOwner() { // - it is enabled, visible, focusable if (!(isEnabled() && isDisplayable() && isVisible() && isFocusable())) { return false; } // - it's parents are all enabled and showing synchronized(getTreeLock()) { if (parent != null) { return parent.canContainFocusOwner(this); } } return true; } /** {@collect.stats} * This odd class is to help out a native component that has been * embedded in a lightweight component. Moving lightweight * components around and changing their visibility is not seen * by the native window system. This is a feature for lightweights, * but a problem for native components that depend upon the * lightweights. An instance of this class listens to the lightweight * parents of an associated native component (the outer class). * * @author Timothy Prinzing */ final class NativeInLightFixer implements ComponentListener, ContainerListener { NativeInLightFixer() { lightParents = new Vector(); install(parent); } void install(Container parent) { lightParents.clear(); Container p = parent; boolean isLwParentsVisible = true; // stash a reference to the components that are being observed so that // we can reliably remove ourself as a listener later. for (; p.peer instanceof LightweightPeer; p = p.parent) { // register listeners and stash a reference p.addComponentListener(this); p.addContainerListener(this); lightParents.addElement(p); isLwParentsVisible &= p.isVisible(); } // register with the native host (native parent of associated native) // to get notified if the top-level lightweight is removed. nativeHost = p; p.addContainerListener(this); // kick start the fixup. Since the event isn't looked at // we can simulate movement notification. componentMoved(null); if (!isLwParentsVisible) { synchronized (getTreeLock()) { if (peer != null) { peer.hide(); } } } } void uninstall() { if (nativeHost != null) { removeReferences(); } } // --- ComponentListener ------------------------------------------- /** {@collect.stats} * Invoked when one of the lightweight parents has been resized. * This doesn't change the position of the native child so it * is ignored. */ public void componentResized(ComponentEvent e) { } /** {@collect.stats} * Invoked when one of the lightweight parents has been moved. * The native peer must be told of the new position which is * relative to the native container that is hosting the * lightweight components. */ public void componentMoved(ComponentEvent e) { synchronized (getTreeLock()) { int nativeX = x; int nativeY = y; for(Component c = parent; (c != null) && (c.peer instanceof LightweightPeer); c = c.parent) { nativeX += c.x; nativeY += c.y; } if (peer != null) { peer.setBounds(nativeX, nativeY, width, height, ComponentPeer.SET_LOCATION); } } } /** {@collect.stats} * Invoked when a lightweight parent component has been * shown. The associated native component must also be * shown if it hasn't had an overriding hide done on it. */ public void componentShown(ComponentEvent e) { if (shouldShow()) { synchronized (getTreeLock()) { if (peer != null) { peer.show(); } } } } /** {@collect.stats} * Invoked when one of the lightweight parents become visible. * Returns true if component and all its lightweight * parents are visible. */ private boolean shouldShow() { boolean isLwParentsVisible = visible; for (int i = lightParents.size() - 1; i >= 0 && isLwParentsVisible; i--) { isLwParentsVisible &= ((Container) lightParents.elementAt(i)).isVisible(); } return isLwParentsVisible; } /** {@collect.stats} * Invoked when component has been hidden. */ public void componentHidden(ComponentEvent e) { if (visible) { synchronized (getTreeLock()) { if (peer != null) { peer.hide(); } } } } // --- ContainerListener ------------------------------------ /** {@collect.stats} * Invoked when a component has been added to a lightweight * parent. This doesn't effect the native component. */ public void componentAdded(ContainerEvent e) { } /** {@collect.stats} * Invoked when a lightweight parent has been removed. * This means the services of this listener are no longer * required and it should remove all references (ie * registered listeners). */ public void componentRemoved(ContainerEvent e) { Component c = e.getChild(); if (c == Component.this) { removeReferences(); } else { int n = lightParents.size(); for (int i = 0; i < n; i++) { Container p = (Container) lightParents.elementAt(i); if (p == c) { removeReferences(); break; } } } } /** {@collect.stats} * Removes references to this object so it can be * garbage collected. */ void removeReferences() { int n = lightParents.size(); for (int i = 0; i < n; i++) { Container c = (Container) lightParents.elementAt(i); c.removeComponentListener(this); c.removeContainerListener(this); } nativeHost.removeContainerListener(this); lightParents.clear(); nativeHost = null; } Vector lightParents; Container nativeHost; } /** {@collect.stats} * Returns the <code>Window</code> ancestor of the component. * @return Window ancestor of the component or component by itself if it is Window; * null, if component is not a part of window hierarchy */ Window getContainingWindow() { return getContainingWindow(this); } /** {@collect.stats} * Returns the <code>Window</code> ancestor of the component <code>comp</code>. * @return Window ancestor of the component or component by itself if it is Window; * null, if component is not a part of window hierarchy */ static Window getContainingWindow(Component comp) { while (comp != null && !(comp instanceof Window)) { comp = comp.getParent(); } return (Window)comp; } /** {@collect.stats} * Initialize JNI field and method IDs */ private static native void initIDs(); /* * --- Accessibility Support --- * * Component will contain all of the methods in interface Accessible, * though it won't actually implement the interface - that will be up * to the individual objects which extend Component. */ AccessibleContext accessibleContext = null; /** {@collect.stats} * Gets the <code>AccessibleContext</code> associated * with this <code>Component</code>. * The method implemented by this base * class returns null. Classes that extend <code>Component</code> * should implement this method to return the * <code>AccessibleContext</code> associated with the subclass. * * * @return the <code>AccessibleContext</code> of this * <code>Component</code> * @since 1.3 */ public AccessibleContext getAccessibleContext() { return accessibleContext; } /** {@collect.stats} * Inner class of Component used to provide default support for * accessibility. This class is not meant to be used directly by * application developers, but is instead meant only to be * subclassed by component developers. * <p> * The class used to obtain the accessible role for this object. * @since 1.3 */ protected abstract class AccessibleAWTComponent extends AccessibleContext implements Serializable, AccessibleComponent { private static final long serialVersionUID = 642321655757800191L; /** {@collect.stats} * Though the class is abstract, this should be called by * all sub-classes. */ protected AccessibleAWTComponent() { } protected ComponentListener accessibleAWTComponentHandler = null; protected FocusListener accessibleAWTFocusHandler = null; /** {@collect.stats} * Fire PropertyChange listener, if one is registered, * when shown/hidden.. * @since 1.3 */ protected class AccessibleAWTComponentHandler implements ComponentListener { public void componentHidden(ComponentEvent e) { if (accessibleContext != null) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_STATE_PROPERTY, AccessibleState.VISIBLE, null); } } public void componentShown(ComponentEvent e) { if (accessibleContext != null) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_STATE_PROPERTY, null, AccessibleState.VISIBLE); } } public void componentMoved(ComponentEvent e) { } public void componentResized(ComponentEvent e) { } } // inner class AccessibleAWTComponentHandler /** {@collect.stats} * Fire PropertyChange listener, if one is registered, * when focus events happen * @since 1.3 */ protected class AccessibleAWTFocusHandler implements FocusListener { public void focusGained(FocusEvent event) { if (accessibleContext != null) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_STATE_PROPERTY, null, AccessibleState.FOCUSED); } } public void focusLost(FocusEvent event) { if (accessibleContext != null) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_STATE_PROPERTY, AccessibleState.FOCUSED, null); } } } // inner class AccessibleAWTFocusHandler /** {@collect.stats} * Adds a <code>PropertyChangeListener</code> to the listener list. * * @param listener the property change listener to be added */ public void addPropertyChangeListener(PropertyChangeListener listener) { if (accessibleAWTComponentHandler == null) { accessibleAWTComponentHandler = new AccessibleAWTComponentHandler(); Component.this.addComponentListener(accessibleAWTComponentHandler); } if (accessibleAWTFocusHandler == null) { accessibleAWTFocusHandler = new AccessibleAWTFocusHandler(); Component.this.addFocusListener(accessibleAWTFocusHandler); } super.addPropertyChangeListener(listener); } /** {@collect.stats} * Remove a PropertyChangeListener from the listener list. * This removes a PropertyChangeListener that was registered * for all properties. * * @param listener The PropertyChangeListener to be removed */ public void removePropertyChangeListener(PropertyChangeListener listener) { if (accessibleAWTComponentHandler != null) { Component.this.removeComponentListener(accessibleAWTComponentHandler); accessibleAWTComponentHandler = null; } if (accessibleAWTFocusHandler != null) { Component.this.removeFocusListener(accessibleAWTFocusHandler); accessibleAWTFocusHandler = null; } super.removePropertyChangeListener(listener); } // AccessibleContext methods // /** {@collect.stats} * Gets the accessible name of this object. This should almost never * return <code>java.awt.Component.getName()</code>, * as that generally isn't a localized name, * and doesn't have meaning for the user. If the * object is fundamentally a text object (e.g. a menu item), the * accessible name should be the text of the object (e.g. "save"). * If the object has a tooltip, the tooltip text may also be an * appropriate String to return. * * @return the localized name of the object -- can be * <code>null</code> if this * object does not have a name * @see javax.accessibility.AccessibleContext#setAccessibleName */ public String getAccessibleName() { return accessibleName; } /** {@collect.stats} * Gets the accessible description of this object. This should be * a concise, localized description of what this object is - what * is its meaning to the user. If the object has a tooltip, the * tooltip text may be an appropriate string to return, assuming * it contains a concise description of the object (instead of just * the name of the object - e.g. a "Save" icon on a toolbar that * had "save" as the tooltip text shouldn't return the tooltip * text as the description, but something like "Saves the current * text document" instead). * * @return the localized description of the object -- can be * <code>null</code> if this object does not have a description * @see javax.accessibility.AccessibleContext#setAccessibleDescription */ public String getAccessibleDescription() { return accessibleDescription; } /** {@collect.stats} * Gets the role of this object. * * @return an instance of <code>AccessibleRole</code> * describing the role of the object * @see javax.accessibility.AccessibleRole */ public AccessibleRole getAccessibleRole() { return AccessibleRole.AWT_COMPONENT; } /** {@collect.stats} * Gets the state of this object. * * @return an instance of <code>AccessibleStateSet</code> * containing the current state set of the object * @see javax.accessibility.AccessibleState */ public AccessibleStateSet getAccessibleStateSet() { return Component.this.getAccessibleStateSet(); } /** {@collect.stats} * Gets the <code>Accessible</code> parent of this object. * If the parent of this object implements <code>Accessible</code>, * this method should simply return <code>getParent</code>. * * @return the <code>Accessible</code> parent of this * object -- can be <code>null</code> if this * object does not have an <code>Accessible</code> parent */ public Accessible getAccessibleParent() { if (accessibleParent != null) { return accessibleParent; } else { Container parent = getParent(); if (parent instanceof Accessible) { return (Accessible) parent; } } return null; } /** {@collect.stats} * Gets the index of this object in its accessible parent. * * @return the index of this object in its parent; or -1 if this * object does not have an accessible parent * @see #getAccessibleParent */ public int getAccessibleIndexInParent() { return Component.this.getAccessibleIndexInParent(); } /** {@collect.stats} * Returns the number of accessible children in the object. If all * of the children of this object implement <code>Accessible</code>, * then this method should return the number of children of this object. * * @return the number of accessible children in the object */ public int getAccessibleChildrenCount() { return 0; // Components don't have children } /** {@collect.stats} * Returns the nth <code>Accessible</code> child of the object. * * @param i zero-based index of child * @return the nth <code>Accessible</code> child of the object */ public Accessible getAccessibleChild(int i) { return null; // Components don't have children } /** {@collect.stats} * Returns the locale of this object. * * @return the locale of this object */ public Locale getLocale() { return Component.this.getLocale(); } /** {@collect.stats} * Gets the <code>AccessibleComponent</code> associated * with this object if one exists. * Otherwise return <code>null</code>. * * @return the component */ public AccessibleComponent getAccessibleComponent() { return this; } // AccessibleComponent methods // /** {@collect.stats} * Gets the background color of this object. * * @return the background color, if supported, of the object; * otherwise, <code>null</code> */ public Color getBackground() { return Component.this.getBackground(); } /** {@collect.stats} * Sets the background color of this object. * (For transparency, see <code>isOpaque</code>.) * * @param c the new <code>Color</code> for the background * @see Component#isOpaque */ public void setBackground(Color c) { Component.this.setBackground(c); } /** {@collect.stats} * Gets the foreground color of this object. * * @return the foreground color, if supported, of the object; * otherwise, <code>null</code> */ public Color getForeground() { return Component.this.getForeground(); } /** {@collect.stats} * Sets the foreground color of this object. * * @param c the new <code>Color</code> for the foreground */ public void setForeground(Color c) { Component.this.setForeground(c); } /** {@collect.stats} * Gets the <code>Cursor</code> of this object. * * @return the <code>Cursor</code>, if supported, * of the object; otherwise, <code>null</code> */ public Cursor getCursor() { return Component.this.getCursor(); } /** {@collect.stats} * Sets the <code>Cursor</code> of this object. * <p> * The method may have no visual effect if the Java platform * implementation and/or the native system do not support * changing the mouse cursor shape. * @param cursor the new <code>Cursor</code> for the object */ public void setCursor(Cursor cursor) { Component.this.setCursor(cursor); } /** {@collect.stats} * Gets the <code>Font</code> of this object. * * @return the <code>Font</code>, if supported, * for the object; otherwise, <code>null</code> */ public Font getFont() { return Component.this.getFont(); } /** {@collect.stats} * Sets the <code>Font</code> of this object. * * @param f the new <code>Font</code> for the object */ public void setFont(Font f) { Component.this.setFont(f); } /** {@collect.stats} * Gets the <code>FontMetrics</code> of this object. * * @param f the <code>Font</code> * @return the <code>FontMetrics</code>, if supported, * the object; otherwise, <code>null</code> * @see #getFont */ public FontMetrics getFontMetrics(Font f) { if (f == null) { return null; } else { return Component.this.getFontMetrics(f); } } /** {@collect.stats} * Determines if the object is enabled. * * @return true if object is enabled; otherwise, false */ public boolean isEnabled() { return Component.this.isEnabled(); } /** {@collect.stats} * Sets the enabled state of the object. * * @param b if true, enables this object; otherwise, disables it */ public void setEnabled(boolean b) { boolean old = Component.this.isEnabled(); Component.this.setEnabled(b); if (b != old) { if (accessibleContext != null) { if (b) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_STATE_PROPERTY, null, AccessibleState.ENABLED); } else { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_STATE_PROPERTY, AccessibleState.ENABLED, null); } } } } /** {@collect.stats} * Determines if the object is visible. Note: this means that the * object intends to be visible; however, it may not in fact be * showing on the screen because one of the objects that this object * is contained by is not visible. To determine if an object is * showing on the screen, use <code>isShowing</code>. * * @return true if object is visible; otherwise, false */ public boolean isVisible() { return Component.this.isVisible(); } /** {@collect.stats} * Sets the visible state of the object. * * @param b if true, shows this object; otherwise, hides it */ public void setVisible(boolean b) { boolean old = Component.this.isVisible(); Component.this.setVisible(b); if (b != old) { if (accessibleContext != null) { if (b) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_STATE_PROPERTY, null, AccessibleState.VISIBLE); } else { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_STATE_PROPERTY, AccessibleState.VISIBLE, null); } } } } /** {@collect.stats} * Determines if the object is showing. This is determined by checking * the visibility of the object and ancestors of the object. Note: * this will return true even if the object is obscured by another * (for example, it happens to be underneath a menu that was pulled * down). * * @return true if object is showing; otherwise, false */ public boolean isShowing() { return Component.this.isShowing(); } /** {@collect.stats} * Checks whether the specified point is within this object's bounds, * where the point's x and y coordinates are defined to be relative to * the coordinate system of the object. * * @param p the <code>Point</code> relative to the * coordinate system of the object * @return true if object contains <code>Point</code>; otherwise false */ public boolean contains(Point p) { return Component.this.contains(p); } /** {@collect.stats} * Returns the location of the object on the screen. * * @return location of object on screen -- can be * <code>null</code> if this object is not on the screen */ public Point getLocationOnScreen() { synchronized (Component.this.getTreeLock()) { if (Component.this.isShowing()) { return Component.this.getLocationOnScreen(); } else { return null; } } } /** {@collect.stats} * Gets the location of the object relative to the parent in the form * of a point specifying the object's top-left corner in the screen's * coordinate space. * * @return an instance of Point representing the top-left corner of * the object's bounds in the coordinate space of the screen; * <code>null</code> if this object or its parent are not on the screen */ public Point getLocation() { return Component.this.getLocation(); } /** {@collect.stats} * Sets the location of the object relative to the parent. * @param p the coordinates of the object */ public void setLocation(Point p) { Component.this.setLocation(p); } /** {@collect.stats} * Gets the bounds of this object in the form of a Rectangle object. * The bounds specify this object's width, height, and location * relative to its parent. * * @return a rectangle indicating this component's bounds; * <code>null</code> if this object is not on the screen */ public Rectangle getBounds() { return Component.this.getBounds(); } /** {@collect.stats} * Sets the bounds of this object in the form of a * <code>Rectangle</code> object. * The bounds specify this object's width, height, and location * relative to its parent. * * @param r a rectangle indicating this component's bounds */ public void setBounds(Rectangle r) { Component.this.setBounds(r); } /** {@collect.stats} * Returns the size of this object in the form of a * <code>Dimension</code> object. The height field of the * <code>Dimension</code> object contains this objects's * height, and the width field of the <code>Dimension</code> * object contains this object's width. * * @return a <code>Dimension</code> object that indicates * the size of this component; <code>null</code> if * this object is not on the screen */ public Dimension getSize() { return Component.this.getSize(); } /** {@collect.stats} * Resizes this object so that it has width and height. * * @param d - the dimension specifying the new size of the object */ public void setSize(Dimension d) { Component.this.setSize(d); } /** {@collect.stats} * Returns the <code>Accessible</code> child, * if one exists, contained at the local * coordinate <code>Point</code>. Otherwise returns * <code>null</code>. * * @param p the point defining the top-left corner of * the <code>Accessible</code>, given in the * coordinate space of the object's parent * @return the <code>Accessible</code>, if it exists, * at the specified location; else <code>null</code> */ public Accessible getAccessibleAt(Point p) { return null; // Components don't have children } /** {@collect.stats} * Returns whether this object can accept focus or not. * * @return true if object can accept focus; otherwise false */ public boolean isFocusTraversable() { return Component.this.isFocusTraversable(); } /** {@collect.stats} * Requests focus for this object. */ public void requestFocus() { Component.this.requestFocus(); } /** {@collect.stats} * Adds the specified focus listener to receive focus events from this * component. * * @param l the focus listener */ public void addFocusListener(FocusListener l) { Component.this.addFocusListener(l); } /** {@collect.stats} * Removes the specified focus listener so it no longer receives focus * events from this component. * * @param l the focus listener */ public void removeFocusListener(FocusListener l) { Component.this.removeFocusListener(l); } } // inner class AccessibleAWTComponent /** {@collect.stats} * Gets the index of this object in its accessible parent. * If this object does not have an accessible parent, returns * -1. * * @return the index of this object in its accessible parent */ int getAccessibleIndexInParent() { synchronized (getTreeLock()) { int index = -1; Container parent = this.getParent(); if (parent != null && parent instanceof Accessible) { Component ca[] = parent.getComponents(); for (int i = 0; i < ca.length; i++) { if (ca[i] instanceof Accessible) { index++; } if (this.equals(ca[i])) { return index; } } } return -1; } } /** {@collect.stats} * Gets the current state set of this object. * * @return an instance of <code>AccessibleStateSet</code> * containing the current state set of the object * @see AccessibleState */ AccessibleStateSet getAccessibleStateSet() { synchronized (getTreeLock()) { AccessibleStateSet states = new AccessibleStateSet(); if (this.isEnabled()) { states.add(AccessibleState.ENABLED); } if (this.isFocusTraversable()) { states.add(AccessibleState.FOCUSABLE); } if (this.isVisible()) { states.add(AccessibleState.VISIBLE); } if (this.isShowing()) { states.add(AccessibleState.SHOWING); } if (this.isFocusOwner()) { states.add(AccessibleState.FOCUSED); } if (this instanceof Accessible) { AccessibleContext ac = ((Accessible) this).getAccessibleContext(); if (ac != null) { Accessible ap = ac.getAccessibleParent(); if (ap != null) { AccessibleContext pac = ap.getAccessibleContext(); if (pac != null) { AccessibleSelection as = pac.getAccessibleSelection(); if (as != null) { states.add(AccessibleState.SELECTABLE); int i = ac.getAccessibleIndexInParent(); if (i >= 0) { if (as.isAccessibleChildSelected(i)) { states.add(AccessibleState.SELECTED); } } } } } } } if (Component.isInstanceOf(this, "javax.swing.JComponent")) { if (((javax.swing.JComponent) this).isOpaque()) { states.add(AccessibleState.OPAQUE); } } return states; } } /** {@collect.stats} * Checks that the given object is instance of the given class. * @param obj Object to be checked * @param className The name of the class. Must be fully-qualified class name. * @return true, if this object is instanceof given class, * false, otherwise, or if obj or className is null */ static boolean isInstanceOf(Object obj, String className) { if (obj == null) return false; if (className == null) return false; Class cls = obj.getClass(); while (cls != null) { if (cls.getName().equals(className)) { return true; } cls = cls.getSuperclass(); } return false; } // ************************** MIXING CODE ******************************* /** {@collect.stats} * Applies the shape to the component * @param shape Shape to be applied to the component */ void applyCompoundShape(Region shape) { checkTreeLock(); if (!isLightweight()) { ComponentPeer peer = getPeer(); if (peer != null) { // The Region class has some optimizations. That's why // we should manually check whether it's empty and // substitute the object ourselves. Otherwise we end up // with some incorrect Region object with loX being // greater than the hiX for instance. if (shape.isEmpty()) { shape = Region.getInstanceXYWH(0, 0, 0, 0); } // Note: the shape is not really copied/cloned. We create // the Region object ourselves, so there's no any possibility // to modify the object outside of the mixing code. this.compoundShape = shape; if (isValid()) { Point compAbsolute = getLocationOnWindow(); if (mixingLog.isLoggable(Level.FINER)) { mixingLog.fine("this = " + this + "; compAbsolute=" + compAbsolute + "; shape=" + shape); } peer.applyShape(shape.getTranslatedRegion(-compAbsolute.x, -compAbsolute.y)); } } } } /** {@collect.stats} * Returns the shape previously set with applyCompoundShape(). * If the component is LW or no shape was applied yet, * the method returns the normal shape. */ private Region getAppliedShape() { checkTreeLock(); //XXX: if we allow LW components to have a shape, this must be changed return (this.compoundShape == null || isLightweight()) ? getNormalShape() : this.compoundShape; } Point getLocationOnWindow() { checkTreeLock(); Point curLocation = getLocation(); for (Container parent = getContainer(); parent != null; parent = parent.getContainer()) { curLocation.x += parent.getX(); curLocation.y += parent.getY(); } return curLocation; } /** {@collect.stats} * Returns the full shape of the component located in window coordinates */ final Region getNormalShape() { checkTreeLock(); //XXX: we may take into account a user-specified shape for this component Point compAbsolute = getLocationOnWindow(); return Region.getInstanceXYWH( compAbsolute.x, compAbsolute.y, getWidth(), getHeight() ); } private int getSiblingIndexAbove() { checkTreeLock(); Container parent = getContainer(); if (parent == null) { return -1; } int nextAbove = parent.getComponentZOrder(this) - 1; return nextAbove < 0 ? -1 : nextAbove; } private int getSiblingIndexBelow() { checkTreeLock(); Container parent = getContainer(); if (parent == null) { return -1; } int nextBelow = parent.getComponentZOrder(this) + 1; return nextBelow >= parent.getComponentCount() ? -1 : nextBelow; } private Region calculateCurrentShape() { checkTreeLock(); Region s = getNormalShape(); if (mixingLog.isLoggable(Level.FINE)) { mixingLog.fine("this = " + this + "; normalShape=" + s); } if (getContainer() != null) { Component comp = this; Container cont = comp.getContainer(); while (cont != null) { for (int index = comp.getSiblingIndexAbove(); index != -1; --index) { /* It is assumed that: * * getComponent(getContainer().getComponentZOrder(comp)) == comp * * The assumption has been made according to the current * implementation of the Container class. */ Component c = cont.getComponent(index); if (c.isLightweight() && c.isShowing() && c.isOpaque()) { s = s.getDifference(c.getNormalShape()); } } if (cont.isLightweight()) { s = s.getIntersection(cont.getNormalShape()); } else { break; } comp = cont; cont = cont.getContainer(); } } if (mixingLog.isLoggable(Level.FINE)) { mixingLog.fine("currentShape=" + s); } return s; } void applyCurrentShape() { checkTreeLock(); if (!isValid()) { return; // Because applyCompoundShape() ignores such components anyway } if (mixingLog.isLoggable(Level.FINE)) { mixingLog.fine("this = " + this); } applyCompoundShape(calculateCurrentShape()); } final void subtractAndApplyShape(Region s) { checkTreeLock(); if (mixingLog.isLoggable(Level.FINE)) { mixingLog.fine("this = " + this + "; s=" + s); } applyCompoundShape(getAppliedShape().getDifference(s)); } void mixOnShowing() { synchronized (getTreeLock()) { if (mixingLog.isLoggable(Level.FINE)) { mixingLog.fine("this = " + this); } if (isLightweight()) { Container parent = getContainer(); if (parent != null && isShowing() && isOpaque()) { parent.recursiveSubtractAndApplyShape(getNormalShape(), getSiblingIndexBelow()); } } else { applyCurrentShape(); } } } void mixOnHiding(boolean isLightweight) { // We cannot be sure that the peer exists at this point, so we need the argument // to find out whether the hiding component is (well, actually was) a LW or a HW. synchronized (getTreeLock()) { if (mixingLog.isLoggable(Level.FINE)) { mixingLog.fine("this = " + this + "; isLightweight = " + isLightweight); } if (isLightweight) { Container parent = getContainer(); if (parent != null) { parent.recursiveApplyCurrentShape(getSiblingIndexBelow()); } } //XXX: else applyNormalShape() ??? } } void mixOnReshaping() { synchronized (getTreeLock()) { if (mixingLog.isLoggable(Level.FINE)) { mixingLog.fine("this = " + this); } if (isLightweight()) { Container parent = getContainer(); if (parent != null) { parent.recursiveApplyCurrentShape(parent.getComponentZOrder(this)); } } else { applyCurrentShape(); } } } void mixOnZOrderChanging(int oldZorder, int newZorder) { synchronized (getTreeLock()) { boolean becameHigher = newZorder < oldZorder; Container parent = getContainer(); if (mixingLog.isLoggable(Level.FINE)) { mixingLog.fine("this = " + this + "; oldZorder=" + oldZorder + "; newZorder=" + newZorder + "; parent=" + parent); } if (isLightweight()) { if (becameHigher) { if (parent != null && isShowing() && isOpaque()) { parent.recursiveSubtractAndApplyShape(getNormalShape(), getSiblingIndexBelow(), oldZorder); } } else { if (parent != null) { parent.recursiveApplyCurrentShape(oldZorder, newZorder); } } } else { if (becameHigher) { applyCurrentShape(); } else { if (parent != null) { Region shape = getAppliedShape(); for (int index = oldZorder; index < newZorder; index++) { Component c = parent.getComponent(index); if (c.isLightweight() && c.isShowing() && c.isOpaque()) { shape = shape.getDifference(c.getNormalShape()); } } applyCompoundShape(shape); } } } } } void mixOnOpaqueChanging() { if (mixingLog.isLoggable(Level.FINE)) { mixingLog.fine("this = " + this); } if (isOpaque()) { mixOnShowing(); } else { mixOnHiding(isLightweight()); } } // ****************** END OF MIXING CODE ******************************** }
Java
/* * Copyright (c) 1996, 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.event.*; /** {@collect.stats} * The interface for objects which contain a set of items for * which zero or more can be selected. * * @author Amy Fowler */ public interface ItemSelectable { /** {@collect.stats} * Returns the selected items or <code>null</code> if no * items are selected. */ public Object[] getSelectedObjects(); /** {@collect.stats} * Adds a listener to receive item events when the state of an item is * changed by the user. Item events are not sent when an item's * state is set programmatically. If <code>l</code> is * <code>null</code>, no exception is thrown and no action is performed. * * @param l the listener to receive events * @see ItemEvent */ public void addItemListener(ItemListener l); /** {@collect.stats} * Removes an item listener. * If <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * * @param l the listener being removed * @see ItemEvent */ public void removeItemListener(ItemListener l); }
Java
/* * Copyright (c) 1997, 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.geom.AffineTransform; import java.awt.image.ColorModel; /** {@collect.stats} * The <code>GradientPaint</code> class provides a way to fill * a {@link Shape} with a linear color gradient pattern. * If {@link Point} P1 with {@link Color} C1 and <code>Point</code> P2 with * <code>Color</code> C2 are specified in user space, the * <code>Color</code> on the P1, P2 connecting line is proportionally * changed from C1 to C2. Any point P not on the extended P1, P2 * connecting line has the color of the point P' that is the perpendicular * projection of P on the extended P1, P2 connecting line. * Points on the extended line outside of the P1, P2 segment can be colored * in one of two ways. * <ul> * <li> * If the gradient is cyclic then the points on the extended P1, P2 * connecting line cycle back and forth between the colors C1 and C2. * <li> * If the gradient is acyclic then points on the P1 side of the segment * have the constant <code>Color</code> C1 while points on the P2 side * have the constant <code>Color</code> C2. * </ul> * * @see Paint * @see Graphics2D#setPaint */ public class GradientPaint implements Paint { Point2D.Float p1; Point2D.Float p2; Color color1; Color color2; boolean cyclic; /** {@collect.stats} * Constructs a simple acyclic <code>GradientPaint</code> object. * @param x1 x coordinate of the first specified * <code>Point</code> in user space * @param y1 y coordinate of the first specified * <code>Point</code> in user space * @param color1 <code>Color</code> at the first specified * <code>Point</code> * @param x2 x coordinate of the second specified * <code>Point</code> in user space * @param y2 y coordinate of the second specified * <code>Point</code> in user space * @param color2 <code>Color</code> at the second specified * <code>Point</code> * @throws NullPointerException if either one of colors is null */ public GradientPaint(float x1, float y1, Color color1, float x2, float y2, Color color2) { if ((color1 == null) || (color2 == null)) { throw new NullPointerException("Colors cannot be null"); } p1 = new Point2D.Float(x1, y1); p2 = new Point2D.Float(x2, y2); this.color1 = color1; this.color2 = color2; } /** {@collect.stats} * Constructs a simple acyclic <code>GradientPaint</code> object. * @param pt1 the first specified <code>Point</code> in user space * @param color1 <code>Color</code> at the first specified * <code>Point</code> * @param pt2 the second specified <code>Point</code> in user space * @param color2 <code>Color</code> at the second specified * <code>Point</code> * @throws NullPointerException if either one of colors or points * is null */ public GradientPaint(Point2D pt1, Color color1, Point2D pt2, Color color2) { if ((color1 == null) || (color2 == null) || (pt1 == null) || (pt2 == null)) { throw new NullPointerException("Colors and points should be non-null"); } p1 = new Point2D.Float((float)pt1.getX(), (float)pt1.getY()); p2 = new Point2D.Float((float)pt2.getX(), (float)pt2.getY()); this.color1 = color1; this.color2 = color2; } /** {@collect.stats} * Constructs either a cyclic or acyclic <code>GradientPaint</code> * object depending on the <code>boolean</code> parameter. * @param x1 x coordinate of the first specified * <code>Point</code> in user space * @param y1 y coordinate of the first specified * <code>Point</code> in user space * @param color1 <code>Color</code> at the first specified * <code>Point</code> * @param x2 x coordinate of the second specified * <code>Point</code> in user space * @param y2 y coordinate of the second specified * <code>Point</code> in user space * @param color2 <code>Color</code> at the second specified * <code>Point</code> * @param cyclic <code>true</code> if the gradient pattern should cycle * repeatedly between the two colors; <code>false</code> otherwise */ public GradientPaint(float x1, float y1, Color color1, float x2, float y2, Color color2, boolean cyclic) { this (x1, y1, color1, x2, y2, color2); this.cyclic = cyclic; } /** {@collect.stats} * Constructs either a cyclic or acyclic <code>GradientPaint</code> * object depending on the <code>boolean</code> parameter. * @param pt1 the first specified <code>Point</code> * in user space * @param color1 <code>Color</code> at the first specified * <code>Point</code> * @param pt2 the second specified <code>Point</code> * in user space * @param color2 <code>Color</code> at the second specified * <code>Point</code> * @param cyclic <code>true</code> if the gradient pattern should cycle * repeatedly between the two colors; <code>false</code> otherwise * @throws NullPointerException if either one of colors or points * is null */ public GradientPaint(Point2D pt1, Color color1, Point2D pt2, Color color2, boolean cyclic) { this (pt1, color1, pt2, color2); this.cyclic = cyclic; } /** {@collect.stats} * Returns a copy of the point P1 that anchors the first color. * @return a {@link Point2D} object that is a copy of the point * that anchors the first color of this * <code>GradientPaint</code>. */ public Point2D getPoint1() { return new Point2D.Float(p1.x, p1.y); } /** {@collect.stats} * Returns the color C1 anchored by the point P1. * @return a <code>Color</code> object that is the color * anchored by P1. */ public Color getColor1() { return color1; } /** {@collect.stats} * Returns a copy of the point P2 which anchors the second color. * @return a {@link Point2D} object that is a copy of the point * that anchors the second color of this * <code>GradientPaint</code>. */ public Point2D getPoint2() { return new Point2D.Float(p2.x, p2.y); } /** {@collect.stats} * Returns the color C2 anchored by the point P2. * @return a <code>Color</code> object that is the color * anchored by P2. */ public Color getColor2() { return color2; } /** {@collect.stats} * Returns <code>true</code> if the gradient cycles repeatedly * between the two colors C1 and C2. * @return <code>true</code> if the gradient cycles repeatedly * between the two colors; <code>false</code> otherwise. */ public boolean isCyclic() { return cyclic; } /** {@collect.stats} * Creates and returns a {@link PaintContext} used to * generate a linear color gradient pattern. * See the {@link Paint#createContext specification} of the * method in the {@link Paint} interface for information * on null parameter handling. * * @param cm the preferred {@link ColorModel} which represents the most convenient * format for the caller to receive the pixel data, or {@code null} * if there is no preference. * @param deviceBounds the device space bounding box * of the graphics primitive being rendered. * @param userBounds the user space bounding box * of the graphics primitive being rendered. * @param xform the {@link AffineTransform} from user * space into device space. * @param hints the set of hints that the context object can use to * choose between rendering alternatives. * @return the {@code PaintContext} for * generating color patterns. * @see Paint * @see PaintContext * @see ColorModel * @see Rectangle * @see Rectangle2D * @see AffineTransform * @see RenderingHints */ public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) { return new GradientPaintContext(cm, p1, p2, xform, color1, color2, cyclic); } /** {@collect.stats} * Returns the transparency mode for this <code>GradientPaint</code>. * @return an integer value representing this <code>GradientPaint</code> * object's transparency mode. * @see Transparency */ public int getTransparency() { int a1 = color1.getAlpha(); int a2 = color2.getAlpha(); return (((a1 & a2) == 0xff) ? OPAQUE : TRANSLUCENT); } }
Java
/* * Copyright (c) 2006, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.MultipleGradientPaint.CycleMethod; import java.awt.MultipleGradientPaint.ColorSpaceType; import java.awt.color.ColorSpace; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Rectangle2D; import java.awt.image.ColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferInt; import java.awt.image.DirectColorModel; import java.awt.image.Raster; import java.awt.image.SinglePixelPackedSampleModel; import java.awt.image.WritableRaster; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.Arrays; /** {@collect.stats} * This is the superclass for all PaintContexts which use a multiple color * gradient to fill in their raster. It provides the actual color * interpolation functionality. Subclasses only have to deal with using * the gradient to fill pixels in a raster. * * @author Nicholas Talian, Vincent Hardy, Jim Graham, Jerry Evans */ abstract class MultipleGradientPaintContext implements PaintContext { /** {@collect.stats} * The PaintContext's ColorModel. This is ARGB if colors are not all * opaque, otherwise it is RGB. */ protected ColorModel model; /** {@collect.stats} Color model used if gradient colors are all opaque. */ private static ColorModel xrgbmodel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff); /** {@collect.stats} The cached ColorModel. */ protected static ColorModel cachedModel; /** {@collect.stats} The cached raster, which is reusable among instances. */ protected static WeakReference<Raster> cached; /** {@collect.stats} Raster is reused whenever possible. */ protected Raster saved; /** {@collect.stats} The method to use when painting out of the gradient bounds. */ protected CycleMethod cycleMethod; /** {@collect.stats} The ColorSpace in which to perform the interpolation */ protected ColorSpaceType colorSpace; /** {@collect.stats} Elements of the inverse transform matrix. */ protected float a00, a01, a10, a11, a02, a12; /** {@collect.stats} * This boolean specifies wether we are in simple lookup mode, where an * input value between 0 and 1 may be used to directly index into a single * array of gradient colors. If this boolean value is false, then we have * to use a 2-step process where we have to determine which gradient array * we fall into, then determine the index into that array. */ protected boolean isSimpleLookup; /** {@collect.stats} * Size of gradients array for scaling the 0-1 index when looking up * colors the fast way. */ protected int fastGradientArraySize; /** {@collect.stats} * Array which contains the interpolated color values for each interval, * used by calculateSingleArrayGradient(). It is protected for possible * direct access by subclasses. */ protected int[] gradient; /** {@collect.stats} * Array of gradient arrays, one array for each interval. Used by * calculateMultipleArrayGradient(). */ private int[][] gradients; /** {@collect.stats} Normalized intervals array. */ private float[] normalizedIntervals; /** {@collect.stats} Fractions array. */ private float[] fractions; /** {@collect.stats} Used to determine if gradient colors are all opaque. */ private int transparencyTest; /** {@collect.stats} Color space conversion lookup tables. */ private static final int SRGBtoLinearRGB[] = new int[256]; private static final int LinearRGBtoSRGB[] = new int[256]; static { // build the tables for (int k = 0; k < 256; k++) { SRGBtoLinearRGB[k] = convertSRGBtoLinearRGB(k); LinearRGBtoSRGB[k] = convertLinearRGBtoSRGB(k); } } /** {@collect.stats} * Constant number of max colors between any 2 arbitrary colors. * Used for creating and indexing gradients arrays. */ protected static final int GRADIENT_SIZE = 256; protected static final int GRADIENT_SIZE_INDEX = GRADIENT_SIZE -1; /** {@collect.stats} * Maximum length of the fast single-array. If the estimated array size * is greater than this, switch over to the slow lookup method. * No particular reason for choosing this number, but it seems to provide * satisfactory performance for the common case (fast lookup). */ private static final int MAX_GRADIENT_ARRAY_SIZE = 5000; /** {@collect.stats} * Constructor for MultipleGradientPaintContext superclass. */ protected MultipleGradientPaintContext(MultipleGradientPaint mgp, ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform t, RenderingHints hints, float[] fractions, Color[] colors, CycleMethod cycleMethod, ColorSpaceType colorSpace) { if (deviceBounds == null) { throw new NullPointerException("Device bounds cannot be null"); } if (userBounds == null) { throw new NullPointerException("User bounds cannot be null"); } if (t == null) { throw new NullPointerException("Transform cannot be null"); } if (hints == null) { throw new NullPointerException("RenderingHints cannot be null"); } // The inverse transform is needed to go from device to user space. // Get all the components of the inverse transform matrix. AffineTransform tInv; try { // the following assumes that the caller has copied the incoming // transform and is not concerned about it being modified t.invert(); tInv = t; } catch (NoninvertibleTransformException e) { // just use identity transform in this case; better to show // (incorrect) results than to throw an exception and/or no-op tInv = new AffineTransform(); } double m[] = new double[6]; tInv.getMatrix(m); a00 = (float)m[0]; a10 = (float)m[1]; a01 = (float)m[2]; a11 = (float)m[3]; a02 = (float)m[4]; a12 = (float)m[5]; // copy some flags this.cycleMethod = cycleMethod; this.colorSpace = colorSpace; // we can avoid copying this array since we do not modify its values this.fractions = fractions; // note that only one of these values can ever be non-null (we either // store the fast gradient array or the slow one, but never both // at the same time) int[] gradient = (mgp.gradient != null) ? mgp.gradient.get() : null; int[][] gradients = (mgp.gradients != null) ? mgp.gradients.get() : null; if (gradient == null && gradients == null) { // we need to (re)create the appropriate values calculateLookupData(colors); // now cache the calculated values in the // MultipleGradientPaint instance for future use mgp.model = this.model; mgp.normalizedIntervals = this.normalizedIntervals; mgp.isSimpleLookup = this.isSimpleLookup; if (isSimpleLookup) { // only cache the fast array mgp.fastGradientArraySize = this.fastGradientArraySize; mgp.gradient = new SoftReference<int[]>(this.gradient); } else { // only cache the slow array mgp.gradients = new SoftReference<int[][]>(this.gradients); } } else { // use the values cached in the MultipleGradientPaint instance this.model = mgp.model; this.normalizedIntervals = mgp.normalizedIntervals; this.isSimpleLookup = mgp.isSimpleLookup; this.gradient = gradient; this.fastGradientArraySize = mgp.fastGradientArraySize; this.gradients = gradients; } } /** {@collect.stats} * This function is the meat of this class. It calculates an array of * gradient colors based on an array of fractions and color values at * those fractions. */ private void calculateLookupData(Color[] colors) { Color[] normalizedColors; if (colorSpace == ColorSpaceType.LINEAR_RGB) { // create a new colors array normalizedColors = new Color[colors.length]; // convert the colors using the lookup table for (int i = 0; i < colors.length; i++) { int argb = colors[i].getRGB(); int a = argb >>> 24; int r = SRGBtoLinearRGB[(argb >> 16) & 0xff]; int g = SRGBtoLinearRGB[(argb >> 8) & 0xff]; int b = SRGBtoLinearRGB[(argb ) & 0xff]; normalizedColors[i] = new Color(r, g, b, a); } } else { // we can just use this array by reference since we do not // modify its values in the case of SRGB normalizedColors = colors; } // this will store the intervals (distances) between gradient stops normalizedIntervals = new float[fractions.length-1]; // convert from fractions into intervals for (int i = 0; i < normalizedIntervals.length; i++) { // interval distance is equal to the difference in positions normalizedIntervals[i] = this.fractions[i+1] - this.fractions[i]; } // initialize to be fully opaque for ANDing with colors transparencyTest = 0xff000000; // array of interpolation arrays gradients = new int[normalizedIntervals.length][]; // find smallest interval float Imin = 1; for (int i = 0; i < normalizedIntervals.length; i++) { Imin = (Imin > normalizedIntervals[i]) ? normalizedIntervals[i] : Imin; } // Estimate the size of the entire gradients array. // This is to prevent a tiny interval from causing the size of array // to explode. If the estimated size is too large, break to using // separate arrays for each interval, and using an indexing scheme at // look-up time. int estimatedSize = 0; for (int i = 0; i < normalizedIntervals.length; i++) { estimatedSize += (normalizedIntervals[i]/Imin) * GRADIENT_SIZE; } if (estimatedSize > MAX_GRADIENT_ARRAY_SIZE) { // slow method calculateMultipleArrayGradient(normalizedColors); } else { // fast method calculateSingleArrayGradient(normalizedColors, Imin); } // use the most "economical" model if ((transparencyTest >>> 24) == 0xff) { model = xrgbmodel; } else { model = ColorModel.getRGBdefault(); } } /** {@collect.stats} * FAST LOOKUP METHOD * * This method calculates the gradient color values and places them in a * single int array, gradient[]. It does this by allocating space for * each interval based on its size relative to the smallest interval in * the array. The smallest interval is allocated 255 interpolated values * (the maximum number of unique in-between colors in a 24 bit color * system), and all other intervals are allocated * size = (255 * the ratio of their size to the smallest interval). * * This scheme expedites a speedy retrieval because the colors are * distributed along the array according to their user-specified * distribution. All that is needed is a relative index from 0 to 1. * * The only problem with this method is that the possibility exists for * the array size to balloon in the case where there is a * disproportionately small gradient interval. In this case the other * intervals will be allocated huge space, but much of that data is * redundant. We thus need to use the space conserving scheme below. * * @param Imin the size of the smallest interval */ private void calculateSingleArrayGradient(Color[] colors, float Imin) { // set the flag so we know later it is a simple (fast) lookup isSimpleLookup = true; // 2 colors to interpolate int rgb1, rgb2; //the eventual size of the single array int gradientsTot = 1; // for every interval (transition between 2 colors) for (int i = 0; i < gradients.length; i++) { // create an array whose size is based on the ratio to the // smallest interval int nGradients = (int)((normalizedIntervals[i]/Imin)*255f); gradientsTot += nGradients; gradients[i] = new int[nGradients]; // the 2 colors (keyframes) to interpolate between rgb1 = colors[i].getRGB(); rgb2 = colors[i+1].getRGB(); // fill this array with the colors in between rgb1 and rgb2 interpolate(rgb1, rgb2, gradients[i]); // if the colors are opaque, transparency should still // be 0xff000000 transparencyTest &= rgb1; transparencyTest &= rgb2; } // put all gradients in a single array gradient = new int[gradientsTot]; int curOffset = 0; for (int i = 0; i < gradients.length; i++){ System.arraycopy(gradients[i], 0, gradient, curOffset, gradients[i].length); curOffset += gradients[i].length; } gradient[gradient.length-1] = colors[colors.length-1].getRGB(); // if interpolation occurred in Linear RGB space, convert the // gradients back to sRGB using the lookup table if (colorSpace == ColorSpaceType.LINEAR_RGB) { for (int i = 0; i < gradient.length; i++) { gradient[i] = convertEntireColorLinearRGBtoSRGB(gradient[i]); } } fastGradientArraySize = gradient.length - 1; } /** {@collect.stats} * SLOW LOOKUP METHOD * * This method calculates the gradient color values for each interval and * places each into its own 255 size array. The arrays are stored in * gradients[][]. (255 is used because this is the maximum number of * unique colors between 2 arbitrary colors in a 24 bit color system.) * * This method uses the minimum amount of space (only 255 * number of * intervals), but it aggravates the lookup procedure, because now we * have to find out which interval to select, then calculate the index * within that interval. This causes a significant performance hit, * because it requires this calculation be done for every point in * the rendering loop. * * For those of you who are interested, this is a classic example of the * time-space tradeoff. */ private void calculateMultipleArrayGradient(Color[] colors) { // set the flag so we know later it is a non-simple lookup isSimpleLookup = false; // 2 colors to interpolate int rgb1, rgb2; // for every interval (transition between 2 colors) for (int i = 0; i < gradients.length; i++){ // create an array of the maximum theoretical size for // each interval gradients[i] = new int[GRADIENT_SIZE]; // get the the 2 colors rgb1 = colors[i].getRGB(); rgb2 = colors[i+1].getRGB(); // fill this array with the colors in between rgb1 and rgb2 interpolate(rgb1, rgb2, gradients[i]); // if the colors are opaque, transparency should still // be 0xff000000 transparencyTest &= rgb1; transparencyTest &= rgb2; } // if interpolation occurred in Linear RGB space, convert the // gradients back to SRGB using the lookup table if (colorSpace == ColorSpaceType.LINEAR_RGB) { for (int j = 0; j < gradients.length; j++) { for (int i = 0; i < gradients[j].length; i++) { gradients[j][i] = convertEntireColorLinearRGBtoSRGB(gradients[j][i]); } } } } /** {@collect.stats} * Yet another helper function. This one linearly interpolates between * 2 colors, filling up the output array. * * @param rgb1 the start color * @param rgb2 the end color * @param output the output array of colors; must not be null */ private void interpolate(int rgb1, int rgb2, int[] output) { // color components int a1, r1, g1, b1, da, dr, dg, db; // step between interpolated values float stepSize = 1.0f / output.length; // extract color components from packed integer a1 = (rgb1 >> 24) & 0xff; r1 = (rgb1 >> 16) & 0xff; g1 = (rgb1 >> 8) & 0xff; b1 = (rgb1 ) & 0xff; // calculate the total change in alpha, red, green, blue da = ((rgb2 >> 24) & 0xff) - a1; dr = ((rgb2 >> 16) & 0xff) - r1; dg = ((rgb2 >> 8) & 0xff) - g1; db = ((rgb2 ) & 0xff) - b1; // for each step in the interval calculate the in-between color by // multiplying the normalized current position by the total color // change (0.5 is added to prevent truncation round-off error) for (int i = 0; i < output.length; i++) { output[i] = (((int) ((a1 + i * da * stepSize) + 0.5) << 24)) | (((int) ((r1 + i * dr * stepSize) + 0.5) << 16)) | (((int) ((g1 + i * dg * stepSize) + 0.5) << 8)) | (((int) ((b1 + i * db * stepSize) + 0.5) )); } } /** {@collect.stats} * Yet another helper function. This one extracts the color components * of an integer RGB triple, converts them from LinearRGB to SRGB, then * recompacts them into an int. */ private int convertEntireColorLinearRGBtoSRGB(int rgb) { // color components int a1, r1, g1, b1; // extract red, green, blue components a1 = (rgb >> 24) & 0xff; r1 = (rgb >> 16) & 0xff; g1 = (rgb >> 8) & 0xff; b1 = (rgb ) & 0xff; // use the lookup table r1 = LinearRGBtoSRGB[r1]; g1 = LinearRGBtoSRGB[g1]; b1 = LinearRGBtoSRGB[b1]; // re-compact the components return ((a1 << 24) | (r1 << 16) | (g1 << 8) | (b1 )); } /** {@collect.stats} * Helper function to index into the gradients array. This is necessary * because each interval has an array of colors with uniform size 255. * However, the color intervals are not necessarily of uniform length, so * a conversion is required. * * @param position the unmanipulated position, which will be mapped * into the range 0 to 1 * @returns integer color to display */ protected final int indexIntoGradientsArrays(float position) { // first, manipulate position value depending on the cycle method if (cycleMethod == CycleMethod.NO_CYCLE) { if (position > 1) { // upper bound is 1 position = 1; } else if (position < 0) { // lower bound is 0 position = 0; } } else if (cycleMethod == CycleMethod.REPEAT) { // get the fractional part // (modulo behavior discards integer component) position = position - (int)position; //position should now be between -1 and 1 if (position < 0) { // force it to be in the range 0-1 position = position + 1; } } else { // cycleMethod == CycleMethod.REFLECT if (position < 0) { // take absolute value position = -position; } // get the integer part int part = (int)position; // get the fractional part position = position - part; if ((part & 1) == 1) { // integer part is odd, get reflected color instead position = 1 - position; } } // now, get the color based on this 0-1 position... if (isSimpleLookup) { // easy to compute: just scale index by array size return gradient[(int)(position * fastGradientArraySize)]; } else { // more complicated computation, to save space // for all the gradient interval arrays for (int i = 0; i < gradients.length; i++) { if (position < fractions[i+1]) { // this is the array we want float delta = position - fractions[i]; // this is the interval we want int index = (int)((delta / normalizedIntervals[i]) * (GRADIENT_SIZE_INDEX)); return gradients[i][index]; } } } return gradients[gradients.length - 1][GRADIENT_SIZE_INDEX]; } /** {@collect.stats} * Helper function to convert a color component in sRGB space to linear * RGB space. Used to build a static lookup table. */ private static int convertSRGBtoLinearRGB(int color) { float input, output; input = color / 255.0f; if (input <= 0.04045f) { output = input / 12.92f; } else { output = (float)Math.pow((input + 0.055) / 1.055, 2.4); } return Math.round(output * 255.0f); } /** {@collect.stats} * Helper function to convert a color component in linear RGB space to * SRGB space. Used to build a static lookup table. */ private static int convertLinearRGBtoSRGB(int color) { float input, output; input = color/255.0f; if (input <= 0.0031308) { output = input * 12.92f; } else { output = (1.055f * ((float) Math.pow(input, (1.0 / 2.4)))) - 0.055f; } return Math.round(output * 255.0f); } /** {@collect.stats} * {@inheritDoc} */ public final Raster getRaster(int x, int y, int w, int h) { // If working raster is big enough, reuse it. Otherwise, // build a large enough new one. Raster raster = saved; if (raster == null || raster.getWidth() < w || raster.getHeight() < h) { raster = getCachedRaster(model, w, h); saved = raster; } // Access raster internal int array. Because we use a DirectColorModel, // we know the DataBuffer is of type DataBufferInt and the SampleModel // is SinglePixelPackedSampleModel. // Adjust for initial offset in DataBuffer and also for the scanline // stride. // These calls make the DataBuffer non-acceleratable, but the // Raster is never Stable long enough to accelerate anyway... DataBufferInt rasterDB = (DataBufferInt)raster.getDataBuffer(); int[] pixels = rasterDB.getData(0); int off = rasterDB.getOffset(); int scanlineStride = ((SinglePixelPackedSampleModel) raster.getSampleModel()).getScanlineStride(); int adjust = scanlineStride - w; fillRaster(pixels, off, adjust, x, y, w, h); // delegate to subclass return raster; } protected abstract void fillRaster(int pixels[], int off, int adjust, int x, int y, int w, int h); /** {@collect.stats} * Took this cacheRaster code from GradientPaint. It appears to recycle * rasters for use by any other instance, as long as they are sufficiently * large. */ private static synchronized Raster getCachedRaster(ColorModel cm, int w, int h) { if (cm == cachedModel) { if (cached != null) { Raster ras = (Raster) cached.get(); if (ras != null && ras.getWidth() >= w && ras.getHeight() >= h) { cached = null; return ras; } } } return cm.createCompatibleWritableRaster(w, h); } /** {@collect.stats} * Took this cacheRaster code from GradientPaint. It appears to recycle * rasters for use by any other instance, as long as they are sufficiently * large. */ private static synchronized void putCachedRaster(ColorModel cm, Raster ras) { if (cached != null) { Raster cras = (Raster) cached.get(); if (cras != null) { int cw = cras.getWidth(); int ch = cras.getHeight(); int iw = ras.getWidth(); int ih = ras.getHeight(); if (cw >= iw && ch >= ih) { return; } if (cw * ch >= iw * ih) { return; } } } cachedModel = cm; cached = new WeakReference<Raster>(ras); } /** {@collect.stats} * {@inheritDoc} */ public final void dispose() { if (saved != null) { putCachedRaster(model, saved); saved = null; } } /** {@collect.stats} * {@inheritDoc} */ public final ColorModel getColorModel() { return model; } }
Java
/* * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; /** {@collect.stats} * The <code>GridBagConstraints</code> class specifies constraints * for components that are laid out using the * <code>GridBagLayout</code> class. * * @author Doug Stein * @author Bill Spitzak (orignial NeWS & OLIT implementation) * @see java.awt.GridBagLayout * @since JDK1.0 */ public class GridBagConstraints implements Cloneable, java.io.Serializable { /** {@collect.stats} * Specifies that this component is the next-to-last component in its * column or row (<code>gridwidth</code>, <code>gridheight</code>), * or that this component be placed next to the previously added * component (<code>gridx</code>, <code>gridy</code>). * @see java.awt.GridBagConstraints#gridwidth * @see java.awt.GridBagConstraints#gridheight * @see java.awt.GridBagConstraints#gridx * @see java.awt.GridBagConstraints#gridy */ public static final int RELATIVE = -1; /** {@collect.stats} * Specifies that this component is the * last component in its column or row. */ public static final int REMAINDER = 0; /** {@collect.stats} * Do not resize the component. */ public static final int NONE = 0; /** {@collect.stats} * Resize the component both horizontally and vertically. */ public static final int BOTH = 1; /** {@collect.stats} * Resize the component horizontally but not vertically. */ public static final int HORIZONTAL = 2; /** {@collect.stats} * Resize the component vertically but not horizontally. */ public static final int VERTICAL = 3; /** {@collect.stats} * Put the component in the center of its display area. */ public static final int CENTER = 10; /** {@collect.stats} * Put the component at the top of its display area, * centered horizontally. */ public static final int NORTH = 11; /** {@collect.stats} * Put the component at the top-right corner of its display area. */ public static final int NORTHEAST = 12; /** {@collect.stats} * Put the component on the right side of its display area, * centered vertically. */ public static final int EAST = 13; /** {@collect.stats} * Put the component at the bottom-right corner of its display area. */ public static final int SOUTHEAST = 14; /** {@collect.stats} * Put the component at the bottom of its display area, centered * horizontally. */ public static final int SOUTH = 15; /** {@collect.stats} * Put the component at the bottom-left corner of its display area. */ public static final int SOUTHWEST = 16; /** {@collect.stats} * Put the component on the left side of its display area, * centered vertically. */ public static final int WEST = 17; /** {@collect.stats} * Put the component at the top-left corner of its display area. */ public static final int NORTHWEST = 18; /** {@collect.stats} * Place the component centered along the edge of its display area * associated with the start of a page for the current * <code>ComponentOrienation</code>. Equal to NORTH for horizontal * orientations. */ public static final int PAGE_START = 19; /** {@collect.stats} * Place the component centered along the edge of its display area * associated with the end of a page for the current * <code>ComponentOrienation</code>. Equal to SOUTH for horizontal * orientations. */ public static final int PAGE_END = 20; /** {@collect.stats} * Place the component centered along the edge of its display area where * lines of text would normally begin for the current * <code>ComponentOrienation</code>. Equal to WEST for horizontal, * left-to-right orientations and EAST for horizontal, right-to-left * orientations. */ public static final int LINE_START = 21; /** {@collect.stats} * Place the component centered along the edge of its display area where * lines of text would normally end for the current * <code>ComponentOrienation</code>. Equal to EAST for horizontal, * left-to-right orientations and WEST for horizontal, right-to-left * orientations. */ public static final int LINE_END = 22; /** {@collect.stats} * Place the component in the corner of its display area where * the first line of text on a page would normally begin for the current * <code>ComponentOrienation</code>. Equal to NORTHWEST for horizontal, * left-to-right orientations and NORTHEAST for horizontal, right-to-left * orientations. */ public static final int FIRST_LINE_START = 23; /** {@collect.stats} * Place the component in the corner of its display area where * the first line of text on a page would normally end for the current * <code>ComponentOrienation</code>. Equal to NORTHEAST for horizontal, * left-to-right orientations and NORTHWEST for horizontal, right-to-left * orientations. */ public static final int FIRST_LINE_END = 24; /** {@collect.stats} * Place the component in the corner of its display area where * the last line of text on a page would normally start for the current * <code>ComponentOrienation</code>. Equal to SOUTHWEST for horizontal, * left-to-right orientations and SOUTHEAST for horizontal, right-to-left * orientations. */ public static final int LAST_LINE_START = 25; /** {@collect.stats} * Place the component in the corner of its display area where * the last line of text on a page would normally end for the current * <code>ComponentOrienation</code>. Equal to SOUTHEAST for horizontal, * left-to-right orientations and SOUTHWEST for horizontal, right-to-left * orientations. */ public static final int LAST_LINE_END = 26; /** {@collect.stats} * Possible value for the <code>anchor</code> field. Specifies * that the component should be horizontally centered and * vertically aligned along the baseline of the prevailing row. * If the component does not have a baseline it will be vertically * centered. * * @since 1.6 */ public static final int BASELINE = 0x100; /** {@collect.stats} * Possible value for the <code>anchor</code> field. Specifies * that the component should be horizontally placed along the * leading edge. For components with a left-to-right orientation, * the leading edge is the left edge. Vertically the component is * aligned along the baseline of the prevailing row. If the * component does not have a baseline it will be vertically * centered. * * @since 1.6 */ public static final int BASELINE_LEADING = 0x200; /** {@collect.stats} * Possible value for the <code>anchor</code> field. Specifies * that the component should be horizontally placed along the * trailing edge. For components with a left-to-right * orientation, the trailing edge is the right edge. Vertically * the component is aligned along the baseline of the prevailing * row. If the component does not have a baseline it will be * vertically centered. * * @since 1.6 */ public static final int BASELINE_TRAILING = 0x300; /** {@collect.stats} * Possible value for the <code>anchor</code> field. Specifies * that the component should be horizontally centered. Vertically * the component is positioned so that its bottom edge touches * the baseline of the starting row. If the starting row does not * have a baseline it will be vertically centered. * * @since 1.6 */ public static final int ABOVE_BASELINE = 0x400; /** {@collect.stats} * Possible value for the <code>anchor</code> field. Specifies * that the component should be horizontally placed along the * leading edge. For components with a left-to-right orientation, * the leading edge is the left edge. Vertically the component is * positioned so that its bottom edge touches the baseline of the * starting row. If the starting row does not have a baseline it * will be vertically centered. * * @since 1.6 */ public static final int ABOVE_BASELINE_LEADING = 0x500; /** {@collect.stats} * Possible value for the <code>anchor</code> field. Specifies * that the component should be horizontally placed along the * trailing edge. For components with a left-to-right * orientation, the trailing edge is the right edge. Vertically * the component is positioned so that its bottom edge touches * the baseline of the starting row. If the starting row does not * have a baseline it will be vertically centered. * * @since 1.6 */ public static final int ABOVE_BASELINE_TRAILING = 0x600; /** {@collect.stats} * Possible value for the <code>anchor</code> field. Specifies * that the component should be horizontally centered. Vertically * the component is positioned so that its top edge touches the * baseline of the starting row. If the starting row does not * have a baseline it will be vertically centered. * * @since 1.6 */ public static final int BELOW_BASELINE = 0x700; /** {@collect.stats} * Possible value for the <code>anchor</code> field. Specifies * that the component should be horizontally placed along the * leading edge. For components with a left-to-right orientation, * the leading edge is the left edge. Vertically the component is * positioned so that its top edge touches the baseline of the * starting row. If the starting row does not have a baseline it * will be vertically centered. * * @since 1.6 */ public static final int BELOW_BASELINE_LEADING = 0x800; /** {@collect.stats} * Possible value for the <code>anchor</code> field. Specifies * that the component should be horizontally placed along the * trailing edge. For components with a left-to-right * orientation, the trailing edge is the right edge. Vertically * the component is positioned so that its top edge touches the * baseline of the starting row. If the starting row does not * have a baseline it will be vertically centered. * * @since 1.6 */ public static final int BELOW_BASELINE_TRAILING = 0x900; /** {@collect.stats} * Specifies the cell containing the leading edge of the component's * display area, where the first cell in a row has <code>gridx=0</code>. * The leading edge of a component's display area is its left edge for * a horizontal, left-to-right container and its right edge for a * horizontal, right-to-left container. * The value * <code>RELATIVE</code> specifies that the component be placed * immediately following the component that was added to the container * just before this component was added. * <p> * The default value is <code>RELATIVE</code>. * <code>gridx</code> should be a non-negative value. * @serial * @see #clone() * @see java.awt.GridBagConstraints#gridy * @see java.awt.ComponentOrientation */ public int gridx; /** {@collect.stats} * Specifies the cell at the top of the component's display area, * where the topmost cell has <code>gridy=0</code>. The value * <code>RELATIVE</code> specifies that the component be placed just * below the component that was added to the container just before * this component was added. * <p> * The default value is <code>RELATIVE</code>. * <code>gridy</code> should be a non-negative value. * @serial * @see #clone() * @see java.awt.GridBagConstraints#gridx */ public int gridy; /** {@collect.stats} * Specifies the number of cells in a row for the component's * display area. * <p> * Use <code>REMAINDER</code> to specify that the component's * display area will be from <code>gridx</code> to the last * cell in the row. * Use <code>RELATIVE</code> to specify that the component's * display area will be from <code>gridx</code> to the next * to the last one in its row. * <p> * <code>gridwidth</code> should be non-negative and the default * value is 1. * @serial * @see #clone() * @see java.awt.GridBagConstraints#gridheight */ public int gridwidth; /** {@collect.stats} * Specifies the number of cells in a column for the component's * display area. * <p> * Use <code>REMAINDER</code> to specify that the component's * display area will be from <code>gridy</code> to the last * cell in the column. * Use <code>RELATIVE</code> to specify that the component's * display area will be from <code>gridy</code> to the next * to the last one in its column. * <p> * <code>gridheight</code> should be a non-negative value and the * default value is 1. * @serial * @see #clone() * @see java.awt.GridBagConstraints#gridwidth */ public int gridheight; /** {@collect.stats} * Specifies how to distribute extra horizontal space. * <p> * The grid bag layout manager calculates the weight of a column to * be the maximum <code>weightx</code> of all the components in a * column. If the resulting layout is smaller horizontally than the area * it needs to fill, the extra space is distributed to each column in * proportion to its weight. A column that has a weight of zero receives * no extra space. * <p> * If all the weights are zero, all the extra space appears between * the grids of the cell and the left and right edges. * <p> * The default value of this field is <code>0</code>. * <code>weightx</code> should be a non-negative value. * @serial * @see #clone() * @see java.awt.GridBagConstraints#weighty */ public double weightx; /** {@collect.stats} * Specifies how to distribute extra vertical space. * <p> * The grid bag layout manager calculates the weight of a row to be * the maximum <code>weighty</code> of all the components in a row. * If the resulting layout is smaller vertically than the area it * needs to fill, the extra space is distributed to each row in * proportion to its weight. A row that has a weight of zero receives no * extra space. * <p> * If all the weights are zero, all the extra space appears between * the grids of the cell and the top and bottom edges. * <p> * The default value of this field is <code>0</code>. * <code>weighty</code> should be a non-negative value. * @serial * @see #clone() * @see java.awt.GridBagConstraints#weightx */ public double weighty; /** {@collect.stats} * This field is used when the component is smaller than its * display area. It determines where, within the display area, to * place the component. * <p> There are three kinds of possible values: orientation * relative, baseline relative and absolute. Orientation relative * values are interpreted relative to the container's component * orientation property, baseline relative values are interpreted * relative to the baseline and absolute values are not. The * absolute values are: * <code>CENTER</code>, <code>NORTH</code>, <code>NORTHEAST</code>, * <code>EAST</code>, <code>SOUTHEAST</code>, <code>SOUTH</code>, * <code>SOUTHWEST</code>, <code>WEST</code>, and <code>NORTHWEST</code>. * The orientation relative values are: <code>PAGE_START</code>, * <code>PAGE_END</code>, * <code>LINE_START</code>, <code>LINE_END</code>, * <code>FIRST_LINE_START</code>, <code>FIRST_LINE_END</code>, * <code>LAST_LINE_START</code> and <code>LAST_LINE_END</code>. The * baseline relvative values are: * <code>BASELINE</code>, <code>BASELINE_LEADING</code>, * <code>BASELINE_TRAILING</code>, * <code>ABOVE_BASELINE</code>, <code>ABOVE_BASELINE_LEADING</code>, * <code>ABOVE_BASELINE_TRAILING</code>, * <code>BELOW_BASELINE</code>, <code>BELOW_BASELINE_LEADING</code>, * and <code>BELOW_BASELINE_TRAILING</code>. * The default value is <code>CENTER</code>. * @serial * @see #clone() * @see java.awt.ComponentOrientation */ public int anchor; /** {@collect.stats} * This field is used when the component's display area is larger * than the component's requested size. It determines whether to * resize the component, and if so, how. * <p> * The following values are valid for <code>fill</code>: * <p> * <ul> * <li> * <code>NONE</code>: Do not resize the component. * <li> * <code>HORIZONTAL</code>: Make the component wide enough to fill * its display area horizontally, but do not change its height. * <li> * <code>VERTICAL</code>: Make the component tall enough to fill its * display area vertically, but do not change its width. * <li> * <code>BOTH</code>: Make the component fill its display area * entirely. * </ul> * <p> * The default value is <code>NONE</code>. * @serial * @see #clone() */ public int fill; /** {@collect.stats} * This field specifies the external padding of the component, the * minimum amount of space between the component and the edges of its * display area. * <p> * The default value is <code>new Insets(0, 0, 0, 0)</code>. * @serial * @see #clone() */ public Insets insets; /** {@collect.stats} * This field specifies the internal padding of the component, how much * space to add to the minimum width of the component. The width of * the component is at least its minimum width plus * <code>ipadx</code> pixels. * <p> * The default value is <code>0</code>. * @serial * @see #clone() * @see java.awt.GridBagConstraints#ipady */ public int ipadx; /** {@collect.stats} * This field specifies the internal padding, that is, how much * space to add to the minimum height of the component. The height of * the component is at least its minimum height plus * <code>ipady</code> pixels. * <p> * The default value is 0. * @serial * @see #clone() * @see java.awt.GridBagConstraints#ipadx */ public int ipady; /** {@collect.stats} * Temporary place holder for the x coordinate. * @serial */ int tempX; /** {@collect.stats} * Temporary place holder for the y coordinate. * @serial */ int tempY; /** {@collect.stats} * Temporary place holder for the Width of the component. * @serial */ int tempWidth; /** {@collect.stats} * Temporary place holder for the Height of the component. * @serial */ int tempHeight; /** {@collect.stats} * The minimum width of the component. It is used to calculate * <code>ipady</code>, where the default will be 0. * @serial * @see #ipady */ int minWidth; /** {@collect.stats} * The minimum height of the component. It is used to calculate * <code>ipadx</code>, where the default will be 0. * @serial * @see #ipadx */ int minHeight; // The following fields are only used if the anchor is // one of BASELINE, BASELINE_LEADING or BASELINE_TRAILING. // ascent and descent include the insets and ipady values. transient int ascent; transient int descent; transient Component.BaselineResizeBehavior baselineResizeBehavior; // The folllowing two fields are used if the baseline type is // CENTER_OFFSET. // centerPadding is either 0 or 1 and indicates if // the height needs to be padded by one when calculating where the // baseline lands transient int centerPadding; // Where the baseline lands relative to the center of the component. transient int centerOffset; /* * JDK 1.1 serialVersionUID */ private static final long serialVersionUID = -1000070633030801713L; /** {@collect.stats} * Creates a <code>GridBagConstraint</code> object with * all of its fields set to their default value. */ public GridBagConstraints () { gridx = RELATIVE; gridy = RELATIVE; gridwidth = 1; gridheight = 1; weightx = 0; weighty = 0; anchor = CENTER; fill = NONE; insets = new Insets(0, 0, 0, 0); ipadx = 0; ipady = 0; } /** {@collect.stats} * Creates a <code>GridBagConstraints</code> object with * all of its fields set to the passed-in arguments. * * Note: Because the use of this constructor hinders readability * of source code, this constructor should only be used by * automatic source code generation tools. * * @param gridx The initial gridx value. * @param gridy The initial gridy value. * @param gridwidth The initial gridwidth value. * @param gridheight The initial gridheight value. * @param weightx The initial weightx value. * @param weighty The initial weighty value. * @param anchor The initial anchor value. * @param fill The initial fill value. * @param insets The initial insets value. * @param ipadx The initial ipadx value. * @param ipady The initial ipady value. * * @see java.awt.GridBagConstraints#gridx * @see java.awt.GridBagConstraints#gridy * @see java.awt.GridBagConstraints#gridwidth * @see java.awt.GridBagConstraints#gridheight * @see java.awt.GridBagConstraints#weightx * @see java.awt.GridBagConstraints#weighty * @see java.awt.GridBagConstraints#anchor * @see java.awt.GridBagConstraints#fill * @see java.awt.GridBagConstraints#insets * @see java.awt.GridBagConstraints#ipadx * @see java.awt.GridBagConstraints#ipady * * @since 1.2 */ public GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets, int ipadx, int ipady) { this.gridx = gridx; this.gridy = gridy; this.gridwidth = gridwidth; this.gridheight = gridheight; this.fill = fill; this.ipadx = ipadx; this.ipady = ipady; this.insets = insets; this.anchor = anchor; this.weightx = weightx; this.weighty = weighty; } /** {@collect.stats} * Creates a copy of this grid bag constraint. * @return a copy of this grid bag constraint */ public Object clone () { try { GridBagConstraints c = (GridBagConstraints)super.clone(); c.insets = (Insets)insets.clone(); return c; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } boolean isVerticallyResizable() { return (fill == BOTH || fill == VERTICAL); } }
Java