src/share/classes/java/util/Collections.java

Print this page
rev 3186 : 6880112: Project Coin: Port JDK core library code to use diamond operator


1018      * allows modules to provide users with "read-only" access to internal
1019      * collections.  Query operations on the returned collection "read through"
1020      * to the specified collection, and attempts to modify the returned
1021      * collection, whether direct or via its iterator, result in an
1022      * <tt>UnsupportedOperationException</tt>.<p>
1023      *
1024      * The returned collection does <i>not</i> pass the hashCode and equals
1025      * operations through to the backing collection, but relies on
1026      * <tt>Object</tt>'s <tt>equals</tt> and <tt>hashCode</tt> methods.  This
1027      * is necessary to preserve the contracts of these operations in the case
1028      * that the backing collection is a set or a list.<p>
1029      *
1030      * The returned collection will be serializable if the specified collection
1031      * is serializable.
1032      *
1033      * @param  c the collection for which an unmodifiable view is to be
1034      *         returned.
1035      * @return an unmodifiable view of the specified collection.
1036      */
1037     public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
1038         return new UnmodifiableCollection<T>(c);
1039     }
1040 
1041     /**
1042      * @serial include
1043      */
1044     static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
1045         private static final long serialVersionUID = 1820017752578914078L;
1046 
1047         final Collection<? extends E> c;
1048 
1049         UnmodifiableCollection(Collection<? extends E> c) {
1050             if (c==null)
1051                 throw new NullPointerException();
1052             this.c = c;
1053         }
1054 
1055         public int size()                   {return c.size();}
1056         public boolean isEmpty()            {return c.isEmpty();}
1057         public boolean contains(Object o)   {return c.contains(o);}
1058         public Object[] toArray()           {return c.toArray();}


1092         }
1093         public void clear() {
1094             throw new UnsupportedOperationException();
1095         }
1096     }
1097 
1098     /**
1099      * Returns an unmodifiable view of the specified set.  This method allows
1100      * modules to provide users with "read-only" access to internal sets.
1101      * Query operations on the returned set "read through" to the specified
1102      * set, and attempts to modify the returned set, whether direct or via its
1103      * iterator, result in an <tt>UnsupportedOperationException</tt>.<p>
1104      *
1105      * The returned set will be serializable if the specified set
1106      * is serializable.
1107      *
1108      * @param  s the set for which an unmodifiable view is to be returned.
1109      * @return an unmodifiable view of the specified set.
1110      */
1111     public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
1112         return new UnmodifiableSet<T>(s);
1113     }
1114 
1115     /**
1116      * @serial include
1117      */
1118     static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
1119                                  implements Set<E>, Serializable {
1120         private static final long serialVersionUID = -9215047833775013803L;
1121 
1122         UnmodifiableSet(Set<? extends E> s)     {super(s);}
1123         public boolean equals(Object o) {return o == this || c.equals(o);}
1124         public int hashCode()           {return c.hashCode();}
1125     }
1126 
1127     /**
1128      * Returns an unmodifiable view of the specified sorted set.  This method
1129      * allows modules to provide users with "read-only" access to internal
1130      * sorted sets.  Query operations on the returned sorted set "read
1131      * through" to the specified sorted set.  Attempts to modify the returned
1132      * sorted set, whether direct, via its iterator, or via its
1133      * <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in
1134      * an <tt>UnsupportedOperationException</tt>.<p>
1135      *
1136      * The returned sorted set will be serializable if the specified sorted set
1137      * is serializable.
1138      *
1139      * @param s the sorted set for which an unmodifiable view is to be
1140      *        returned.
1141      * @return an unmodifiable view of the specified sorted set.
1142      */
1143     public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
1144         return new UnmodifiableSortedSet<T>(s);
1145     }
1146 
1147     /**
1148      * @serial include
1149      */
1150     static class UnmodifiableSortedSet<E>
1151                              extends UnmodifiableSet<E>
1152                              implements SortedSet<E>, Serializable {
1153         private static final long serialVersionUID = -4929149591599911165L;
1154         private final SortedSet<E> ss;
1155 
1156         UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
1157 
1158         public Comparator<? super E> comparator() {return ss.comparator();}
1159 
1160         public SortedSet<E> subSet(E fromElement, E toElement) {
1161             return new UnmodifiableSortedSet<E>(ss.subSet(fromElement,toElement));
1162         }
1163         public SortedSet<E> headSet(E toElement) {
1164             return new UnmodifiableSortedSet<E>(ss.headSet(toElement));
1165         }
1166         public SortedSet<E> tailSet(E fromElement) {
1167             return new UnmodifiableSortedSet<E>(ss.tailSet(fromElement));
1168         }
1169 
1170         public E first()                   {return ss.first();}
1171         public E last()                    {return ss.last();}
1172     }
1173 
1174     /**
1175      * Returns an unmodifiable view of the specified list.  This method allows
1176      * modules to provide users with "read-only" access to internal
1177      * lists.  Query operations on the returned list "read through" to the
1178      * specified list, and attempts to modify the returned list, whether
1179      * direct or via its iterator, result in an
1180      * <tt>UnsupportedOperationException</tt>.<p>
1181      *
1182      * The returned list will be serializable if the specified list
1183      * is serializable. Similarly, the returned list will implement
1184      * {@link RandomAccess} if the specified list does.
1185      *
1186      * @param  list the list for which an unmodifiable view is to be returned.
1187      * @return an unmodifiable view of the specified list.
1188      */
1189     public static <T> List<T> unmodifiableList(List<? extends T> list) {
1190         return (list instanceof RandomAccess ?
1191                 new UnmodifiableRandomAccessList<T>(list) :
1192                 new UnmodifiableList<T>(list));
1193     }
1194 
1195     /**
1196      * @serial include
1197      */
1198     static class UnmodifiableList<E> extends UnmodifiableCollection<E>
1199                                   implements List<E> {
1200         private static final long serialVersionUID = -283967356065247728L;
1201         final List<? extends E> list;
1202 
1203         UnmodifiableList(List<? extends E> list) {
1204             super(list);
1205             this.list = list;
1206         }
1207 
1208         public boolean equals(Object o) {return o == this || list.equals(o);}
1209         public int hashCode()           {return list.hashCode();}
1210 
1211         public E get(int index) {return list.get(index);}
1212         public E set(int index, E element) {


1233                 public boolean hasNext()     {return i.hasNext();}
1234                 public E next()              {return i.next();}
1235                 public boolean hasPrevious() {return i.hasPrevious();}
1236                 public E previous()          {return i.previous();}
1237                 public int nextIndex()       {return i.nextIndex();}
1238                 public int previousIndex()   {return i.previousIndex();}
1239 
1240                 public void remove() {
1241                     throw new UnsupportedOperationException();
1242                 }
1243                 public void set(E e) {
1244                     throw new UnsupportedOperationException();
1245                 }
1246                 public void add(E e) {
1247                     throw new UnsupportedOperationException();
1248                 }
1249             };
1250         }
1251 
1252         public List<E> subList(int fromIndex, int toIndex) {
1253             return new UnmodifiableList<E>(list.subList(fromIndex, toIndex));
1254         }
1255 
1256         /**
1257          * UnmodifiableRandomAccessList instances are serialized as
1258          * UnmodifiableList instances to allow them to be deserialized
1259          * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
1260          * This method inverts the transformation.  As a beneficial
1261          * side-effect, it also grafts the RandomAccess marker onto
1262          * UnmodifiableList instances that were serialized in pre-1.4 JREs.
1263          *
1264          * Note: Unfortunately, UnmodifiableRandomAccessList instances
1265          * serialized in 1.4.1 and deserialized in 1.4 will become
1266          * UnmodifiableList instances, as this method was missing in 1.4.
1267          */
1268         private Object readResolve() {
1269             return (list instanceof RandomAccess
1270                     ? new UnmodifiableRandomAccessList<E>(list)
1271                     : this);
1272         }
1273     }
1274 
1275     /**
1276      * @serial include
1277      */
1278     static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>
1279                                               implements RandomAccess
1280     {
1281         UnmodifiableRandomAccessList(List<? extends E> list) {
1282             super(list);
1283         }
1284 
1285         public List<E> subList(int fromIndex, int toIndex) {
1286             return new UnmodifiableRandomAccessList<E>(
1287                 list.subList(fromIndex, toIndex));
1288         }
1289 
1290         private static final long serialVersionUID = -2542308836966382001L;
1291 
1292         /**
1293          * Allows instances to be deserialized in pre-1.4 JREs (which do
1294          * not have UnmodifiableRandomAccessList).  UnmodifiableList has
1295          * a readResolve method that inverts this transformation upon
1296          * deserialization.
1297          */
1298         private Object writeReplace() {
1299             return new UnmodifiableList<E>(list);
1300         }
1301     }
1302 
1303     /**
1304      * Returns an unmodifiable view of the specified map.  This method
1305      * allows modules to provide users with "read-only" access to internal
1306      * maps.  Query operations on the returned map "read through"
1307      * to the specified map, and attempts to modify the returned
1308      * map, whether direct or via its collection views, result in an
1309      * <tt>UnsupportedOperationException</tt>.<p>
1310      *
1311      * The returned map will be serializable if the specified map
1312      * is serializable.
1313      *
1314      * @param  m the map for which an unmodifiable view is to be returned.
1315      * @return an unmodifiable view of the specified map.
1316      */
1317     public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
1318         return new UnmodifiableMap<K,V>(m);
1319     }
1320 
1321     /**
1322      * @serial include
1323      */
1324     private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
1325         private static final long serialVersionUID = -1034234728574286014L;
1326 
1327         private final Map<? extends K, ? extends V> m;
1328 
1329         UnmodifiableMap(Map<? extends K, ? extends V> m) {
1330             if (m==null)
1331                 throw new NullPointerException();
1332             this.m = m;
1333         }
1334 
1335         public int size()                        {return m.size();}
1336         public boolean isEmpty()                 {return m.isEmpty();}
1337         public boolean containsKey(Object key)   {return m.containsKey(key);}
1338         public boolean containsValue(Object val) {return m.containsValue(val);}


1346         }
1347         public void putAll(Map<? extends K, ? extends V> m) {
1348             throw new UnsupportedOperationException();
1349         }
1350         public void clear() {
1351             throw new UnsupportedOperationException();
1352         }
1353 
1354         private transient Set<K> keySet = null;
1355         private transient Set<Map.Entry<K,V>> entrySet = null;
1356         private transient Collection<V> values = null;
1357 
1358         public Set<K> keySet() {
1359             if (keySet==null)
1360                 keySet = unmodifiableSet(m.keySet());
1361             return keySet;
1362         }
1363 
1364         public Set<Map.Entry<K,V>> entrySet() {
1365             if (entrySet==null)
1366                 entrySet = new UnmodifiableEntrySet<K,V>(m.entrySet());
1367             return entrySet;
1368         }
1369 
1370         public Collection<V> values() {
1371             if (values==null)
1372                 values = unmodifiableCollection(m.values());
1373             return values;
1374         }
1375 
1376         public boolean equals(Object o) {return o == this || m.equals(o);}
1377         public int hashCode()           {return m.hashCode();}
1378         public String toString()        {return m.toString();}
1379 
1380         /**
1381          * We need this class in addition to UnmodifiableSet as
1382          * Map.Entries themselves permit modification of the backing Map
1383          * via their setValue operation.  This class is subtle: there are
1384          * many possible attacks that must be thwarted.
1385          *
1386          * @serial include
1387          */
1388         static class UnmodifiableEntrySet<K,V>
1389             extends UnmodifiableSet<Map.Entry<K,V>> {
1390             private static final long serialVersionUID = 7854390611657943733L;
1391 
1392             UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
1393                 super((Set)s);
1394             }
1395             public Iterator<Map.Entry<K,V>> iterator() {
1396                 return new Iterator<Map.Entry<K,V>>() {
1397                     private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
1398 
1399                     public boolean hasNext() {
1400                         return i.hasNext();
1401                     }
1402                     public Map.Entry<K,V> next() {
1403                         return new UnmodifiableEntry<K,V>(i.next());
1404                     }
1405                     public void remove() {
1406                         throw new UnsupportedOperationException();
1407                     }
1408                 };
1409             }
1410 
1411             public Object[] toArray() {
1412                 Object[] a = c.toArray();
1413                 for (int i=0; i<a.length; i++)
1414                     a[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)a[i]);
1415                 return a;
1416             }
1417 
1418             public <T> T[] toArray(T[] a) {
1419                 // We don't pass a to c.toArray, to avoid window of
1420                 // vulnerability wherein an unscrupulous multithreaded client
1421                 // could get his hands on raw (unwrapped) Entries from c.
1422                 Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
1423 
1424                 for (int i=0; i<arr.length; i++)
1425                     arr[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)arr[i]);
1426 
1427                 if (arr.length > a.length)
1428                     return (T[])arr;
1429 
1430                 System.arraycopy(arr, 0, a, 0, arr.length);
1431                 if (a.length > arr.length)
1432                     a[arr.length] = null;
1433                 return a;
1434             }
1435 
1436             /**
1437              * This method is overridden to protect the backing set against
1438              * an object with a nefarious equals function that senses
1439              * that the equality-candidate is Map.Entry and calls its
1440              * setValue method.
1441              */
1442             public boolean contains(Object o) {
1443                 if (!(o instanceof Map.Entry))
1444                     return false;
1445                 return c.contains(
1446                     new UnmodifiableEntry<Object,Object>((Map.Entry<?,?>) o));
1447             }
1448 
1449             /**
1450              * The next two methods are overridden to protect against
1451              * an unscrupulous List whose contains(Object o) method senses
1452              * when o is a Map.Entry, and calls o.setValue.
1453              */
1454             public boolean containsAll(Collection<?> coll) {
1455                 Iterator<?> it = coll.iterator();
1456                 while (it.hasNext())
1457                     if (!contains(it.next())) // Invokes safe contains() above
1458                         return false;
1459                 return true;
1460             }
1461             public boolean equals(Object o) {
1462                 if (o == this)
1463                     return true;
1464 
1465                 if (!(o instanceof Set))
1466                     return false;


1500         }
1501     }
1502 
1503     /**
1504      * Returns an unmodifiable view of the specified sorted map.  This method
1505      * allows modules to provide users with "read-only" access to internal
1506      * sorted maps.  Query operations on the returned sorted map "read through"
1507      * to the specified sorted map.  Attempts to modify the returned
1508      * sorted map, whether direct, via its collection views, or via its
1509      * <tt>subMap</tt>, <tt>headMap</tt>, or <tt>tailMap</tt> views, result in
1510      * an <tt>UnsupportedOperationException</tt>.<p>
1511      *
1512      * The returned sorted map will be serializable if the specified sorted map
1513      * is serializable.
1514      *
1515      * @param m the sorted map for which an unmodifiable view is to be
1516      *        returned.
1517      * @return an unmodifiable view of the specified sorted map.
1518      */
1519     public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
1520         return new UnmodifiableSortedMap<K,V>(m);
1521     }
1522 
1523     /**
1524      * @serial include
1525      */
1526     static class UnmodifiableSortedMap<K,V>
1527           extends UnmodifiableMap<K,V>
1528           implements SortedMap<K,V>, Serializable {
1529         private static final long serialVersionUID = -8806743815996713206L;
1530 
1531         private final SortedMap<K, ? extends V> sm;
1532 
1533         UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}
1534 
1535         public Comparator<? super K> comparator() {return sm.comparator();}
1536 
1537         public SortedMap<K,V> subMap(K fromKey, K toKey) {
1538             return new UnmodifiableSortedMap<K,V>(sm.subMap(fromKey, toKey));
1539         }
1540         public SortedMap<K,V> headMap(K toKey) {
1541             return new UnmodifiableSortedMap<K,V>(sm.headMap(toKey));
1542         }
1543         public SortedMap<K,V> tailMap(K fromKey) {
1544             return new UnmodifiableSortedMap<K,V>(sm.tailMap(fromKey));
1545         }
1546 
1547         public K firstKey()           {return sm.firstKey();}
1548         public K lastKey()            {return sm.lastKey();}
1549     }
1550 
1551 
1552     // Synch Wrappers
1553 
1554     /**
1555      * Returns a synchronized (thread-safe) collection backed by the specified
1556      * collection.  In order to guarantee serial access, it is critical that
1557      * <strong>all</strong> access to the backing collection is accomplished
1558      * through the returned collection.<p>
1559      *
1560      * It is imperative that the user manually synchronize on the returned
1561      * collection when iterating over it:
1562      * <pre>
1563      *  Collection c = Collections.synchronizedCollection(myCollection);
1564      *     ...


1566      *      Iterator i = c.iterator(); // Must be in the synchronized block
1567      *      while (i.hasNext())
1568      *         foo(i.next());
1569      *  }
1570      * </pre>
1571      * Failure to follow this advice may result in non-deterministic behavior.
1572      *
1573      * <p>The returned collection does <i>not</i> pass the <tt>hashCode</tt>
1574      * and <tt>equals</tt> operations through to the backing collection, but
1575      * relies on <tt>Object</tt>'s equals and hashCode methods.  This is
1576      * necessary to preserve the contracts of these operations in the case
1577      * that the backing collection is a set or a list.<p>
1578      *
1579      * The returned collection will be serializable if the specified collection
1580      * is serializable.
1581      *
1582      * @param  c the collection to be "wrapped" in a synchronized collection.
1583      * @return a synchronized view of the specified collection.
1584      */
1585     public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
1586         return new SynchronizedCollection<T>(c);
1587     }
1588 
1589     static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
1590         return new SynchronizedCollection<T>(c, mutex);
1591     }
1592 
1593     /**
1594      * @serial include
1595      */
1596     static class SynchronizedCollection<E> implements Collection<E>, Serializable {
1597         private static final long serialVersionUID = 3053995032091335093L;
1598 
1599         final Collection<E> c;  // Backing Collection
1600         final Object mutex;     // Object on which to synchronize
1601 
1602         SynchronizedCollection(Collection<E> c) {
1603             if (c==null)
1604                 throw new NullPointerException();
1605             this.c = c;
1606             mutex = this;
1607         }
1608         SynchronizedCollection(Collection<E> c, Object mutex) {
1609             this.c = c;
1610             this.mutex = mutex;


1669      * It is imperative that the user manually synchronize on the returned
1670      * set when iterating over it:
1671      * <pre>
1672      *  Set s = Collections.synchronizedSet(new HashSet());
1673      *      ...
1674      *  synchronized (s) {
1675      *      Iterator i = s.iterator(); // Must be in the synchronized block
1676      *      while (i.hasNext())
1677      *          foo(i.next());
1678      *  }
1679      * </pre>
1680      * Failure to follow this advice may result in non-deterministic behavior.
1681      *
1682      * <p>The returned set will be serializable if the specified set is
1683      * serializable.
1684      *
1685      * @param  s the set to be "wrapped" in a synchronized set.
1686      * @return a synchronized view of the specified set.
1687      */
1688     public static <T> Set<T> synchronizedSet(Set<T> s) {
1689         return new SynchronizedSet<T>(s);
1690     }
1691 
1692     static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
1693         return new SynchronizedSet<T>(s, mutex);
1694     }
1695 
1696     /**
1697      * @serial include
1698      */
1699     static class SynchronizedSet<E>
1700           extends SynchronizedCollection<E>
1701           implements Set<E> {
1702         private static final long serialVersionUID = 487447009682186044L;
1703 
1704         SynchronizedSet(Set<E> s) {
1705             super(s);
1706         }
1707         SynchronizedSet(Set<E> s, Object mutex) {
1708             super(s, mutex);
1709         }
1710 
1711         public boolean equals(Object o) {
1712             synchronized (mutex) {return c.equals(o);}
1713         }


1737      * or:
1738      * <pre>
1739      *  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
1740      *  SortedSet s2 = s.headSet(foo);
1741      *      ...
1742      *  synchronized (s) {  // Note: s, not s2!!!
1743      *      Iterator i = s2.iterator(); // Must be in the synchronized block
1744      *      while (i.hasNext())
1745      *          foo(i.next());
1746      *  }
1747      * </pre>
1748      * Failure to follow this advice may result in non-deterministic behavior.
1749      *
1750      * <p>The returned sorted set will be serializable if the specified
1751      * sorted set is serializable.
1752      *
1753      * @param  s the sorted set to be "wrapped" in a synchronized sorted set.
1754      * @return a synchronized view of the specified sorted set.
1755      */
1756     public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
1757         return new SynchronizedSortedSet<T>(s);
1758     }
1759 
1760     /**
1761      * @serial include
1762      */
1763     static class SynchronizedSortedSet<E>
1764         extends SynchronizedSet<E>
1765         implements SortedSet<E>
1766     {
1767         private static final long serialVersionUID = 8695801310862127406L;
1768 
1769         private final SortedSet<E> ss;
1770 
1771         SynchronizedSortedSet(SortedSet<E> s) {
1772             super(s);
1773             ss = s;
1774         }
1775         SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
1776             super(s, mutex);
1777             ss = s;
1778         }
1779 
1780         public Comparator<? super E> comparator() {
1781             synchronized (mutex) {return ss.comparator();}
1782         }
1783 
1784         public SortedSet<E> subSet(E fromElement, E toElement) {
1785             synchronized (mutex) {
1786                 return new SynchronizedSortedSet<E>(
1787                     ss.subSet(fromElement, toElement), mutex);
1788             }
1789         }
1790         public SortedSet<E> headSet(E toElement) {
1791             synchronized (mutex) {
1792                 return new SynchronizedSortedSet<E>(ss.headSet(toElement), mutex);
1793             }
1794         }
1795         public SortedSet<E> tailSet(E fromElement) {
1796             synchronized (mutex) {
1797                return new SynchronizedSortedSet<E>(ss.tailSet(fromElement),mutex);
1798             }
1799         }
1800 
1801         public E first() {
1802             synchronized (mutex) {return ss.first();}
1803         }
1804         public E last() {
1805             synchronized (mutex) {return ss.last();}
1806         }
1807     }
1808 
1809     /**
1810      * Returns a synchronized (thread-safe) list backed by the specified
1811      * list.  In order to guarantee serial access, it is critical that
1812      * <strong>all</strong> access to the backing list is accomplished
1813      * through the returned list.<p>
1814      *
1815      * It is imperative that the user manually synchronize on the returned
1816      * list when iterating over it:
1817      * <pre>
1818      *  List list = Collections.synchronizedList(new ArrayList());
1819      *      ...
1820      *  synchronized (list) {
1821      *      Iterator i = list.iterator(); // Must be in synchronized block
1822      *      while (i.hasNext())
1823      *          foo(i.next());
1824      *  }
1825      * </pre>
1826      * Failure to follow this advice may result in non-deterministic behavior.
1827      *
1828      * <p>The returned list will be serializable if the specified list is
1829      * serializable.
1830      *
1831      * @param  list the list to be "wrapped" in a synchronized list.
1832      * @return a synchronized view of the specified list.
1833      */
1834     public static <T> List<T> synchronizedList(List<T> list) {
1835         return (list instanceof RandomAccess ?
1836                 new SynchronizedRandomAccessList<T>(list) :
1837                 new SynchronizedList<T>(list));
1838     }
1839 
1840     static <T> List<T> synchronizedList(List<T> list, Object mutex) {
1841         return (list instanceof RandomAccess ?
1842                 new SynchronizedRandomAccessList<T>(list, mutex) :
1843                 new SynchronizedList<T>(list, mutex));
1844     }
1845 
1846     /**
1847      * @serial include
1848      */
1849     static class SynchronizedList<E>
1850         extends SynchronizedCollection<E>
1851         implements List<E> {
1852         private static final long serialVersionUID = -7754090372962971524L;
1853 
1854         final List<E> list;
1855 
1856         SynchronizedList(List<E> list) {
1857             super(list);
1858             this.list = list;
1859         }
1860         SynchronizedList(List<E> list, Object mutex) {
1861             super(list, mutex);
1862             this.list = list;
1863         }


1886             synchronized (mutex) {return list.indexOf(o);}
1887         }
1888         public int lastIndexOf(Object o) {
1889             synchronized (mutex) {return list.lastIndexOf(o);}
1890         }
1891 
1892         public boolean addAll(int index, Collection<? extends E> c) {
1893             synchronized (mutex) {return list.addAll(index, c);}
1894         }
1895 
1896         public ListIterator<E> listIterator() {
1897             return list.listIterator(); // Must be manually synched by user
1898         }
1899 
1900         public ListIterator<E> listIterator(int index) {
1901             return list.listIterator(index); // Must be manually synched by user
1902         }
1903 
1904         public List<E> subList(int fromIndex, int toIndex) {
1905             synchronized (mutex) {
1906                 return new SynchronizedList<E>(list.subList(fromIndex, toIndex),
1907                                             mutex);
1908             }
1909         }
1910 
1911         /**
1912          * SynchronizedRandomAccessList instances are serialized as
1913          * SynchronizedList instances to allow them to be deserialized
1914          * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).
1915          * This method inverts the transformation.  As a beneficial
1916          * side-effect, it also grafts the RandomAccess marker onto
1917          * SynchronizedList instances that were serialized in pre-1.4 JREs.
1918          *
1919          * Note: Unfortunately, SynchronizedRandomAccessList instances
1920          * serialized in 1.4.1 and deserialized in 1.4 will become
1921          * SynchronizedList instances, as this method was missing in 1.4.
1922          */
1923         private Object readResolve() {
1924             return (list instanceof RandomAccess
1925                     ? new SynchronizedRandomAccessList<E>(list)
1926                     : this);
1927         }
1928     }
1929 
1930     /**
1931      * @serial include
1932      */
1933     static class SynchronizedRandomAccessList<E>
1934         extends SynchronizedList<E>
1935         implements RandomAccess {
1936 
1937         SynchronizedRandomAccessList(List<E> list) {
1938             super(list);
1939         }
1940 
1941         SynchronizedRandomAccessList(List<E> list, Object mutex) {
1942             super(list, mutex);
1943         }
1944 
1945         public List<E> subList(int fromIndex, int toIndex) {
1946             synchronized (mutex) {
1947                 return new SynchronizedRandomAccessList<E>(
1948                     list.subList(fromIndex, toIndex), mutex);
1949             }
1950         }
1951 
1952         private static final long serialVersionUID = 1530674583602358482L;
1953 
1954         /**
1955          * Allows instances to be deserialized in pre-1.4 JREs (which do
1956          * not have SynchronizedRandomAccessList).  SynchronizedList has
1957          * a readResolve method that inverts this transformation upon
1958          * deserialization.
1959          */
1960         private Object writeReplace() {
1961             return new SynchronizedList<E>(list);
1962         }
1963     }
1964 
1965     /**
1966      * Returns a synchronized (thread-safe) map backed by the specified
1967      * map.  In order to guarantee serial access, it is critical that
1968      * <strong>all</strong> access to the backing map is accomplished
1969      * through the returned map.<p>
1970      *
1971      * It is imperative that the user manually synchronize on the returned
1972      * map when iterating over any of its collection views:
1973      * <pre>
1974      *  Map m = Collections.synchronizedMap(new HashMap());
1975      *      ...
1976      *  Set s = m.keySet();  // Needn't be in synchronized block
1977      *      ...
1978      *  synchronized (m) {  // Synchronizing on m, not s!
1979      *      Iterator i = s.iterator(); // Must be in synchronized block
1980      *      while (i.hasNext())
1981      *          foo(i.next());
1982      *  }
1983      * </pre>
1984      * Failure to follow this advice may result in non-deterministic behavior.
1985      *
1986      * <p>The returned map will be serializable if the specified map is
1987      * serializable.
1988      *
1989      * @param  m the map to be "wrapped" in a synchronized map.
1990      * @return a synchronized view of the specified map.
1991      */
1992     public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
1993         return new SynchronizedMap<K,V>(m);
1994     }
1995 
1996     /**
1997      * @serial include
1998      */
1999     private static class SynchronizedMap<K,V>
2000         implements Map<K,V>, Serializable {
2001         private static final long serialVersionUID = 1978198479659022715L;
2002 
2003         private final Map<K,V> m;     // Backing Map
2004         final Object      mutex;        // Object on which to synchronize
2005 
2006         SynchronizedMap(Map<K,V> m) {
2007             if (m==null)
2008                 throw new NullPointerException();
2009             this.m = m;
2010             mutex = this;
2011         }
2012 
2013         SynchronizedMap(Map<K,V> m, Object mutex) {


2034         public V put(K key, V value) {
2035             synchronized (mutex) {return m.put(key, value);}
2036         }
2037         public V remove(Object key) {
2038             synchronized (mutex) {return m.remove(key);}
2039         }
2040         public void putAll(Map<? extends K, ? extends V> map) {
2041             synchronized (mutex) {m.putAll(map);}
2042         }
2043         public void clear() {
2044             synchronized (mutex) {m.clear();}
2045         }
2046 
2047         private transient Set<K> keySet = null;
2048         private transient Set<Map.Entry<K,V>> entrySet = null;
2049         private transient Collection<V> values = null;
2050 
2051         public Set<K> keySet() {
2052             synchronized (mutex) {
2053                 if (keySet==null)
2054                     keySet = new SynchronizedSet<K>(m.keySet(), mutex);
2055                 return keySet;
2056             }
2057         }
2058 
2059         public Set<Map.Entry<K,V>> entrySet() {
2060             synchronized (mutex) {
2061                 if (entrySet==null)
2062                     entrySet = new SynchronizedSet<Map.Entry<K,V>>(m.entrySet(), mutex);
2063                 return entrySet;
2064             }
2065         }
2066 
2067         public Collection<V> values() {
2068             synchronized (mutex) {
2069                 if (values==null)
2070                     values = new SynchronizedCollection<V>(m.values(), mutex);
2071                 return values;
2072             }
2073         }
2074 
2075         public boolean equals(Object o) {
2076             synchronized (mutex) {return m.equals(o);}
2077         }
2078         public int hashCode() {
2079             synchronized (mutex) {return m.hashCode();}
2080         }
2081         public String toString() {
2082             synchronized (mutex) {return m.toString();}
2083         }
2084         private void writeObject(ObjectOutputStream s) throws IOException {
2085             synchronized (mutex) {s.defaultWriteObject();}
2086         }
2087     }
2088 
2089     /**
2090      * Returns a synchronized (thread-safe) sorted map backed by the specified


2112      *  SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2113      *  SortedMap m2 = m.subMap(foo, bar);
2114      *      ...
2115      *  Set s2 = m2.keySet();  // Needn't be in synchronized block
2116      *      ...
2117      *  synchronized (m) {  // Synchronizing on m, not m2 or s2!
2118      *      Iterator i = s.iterator(); // Must be in synchronized block
2119      *      while (i.hasNext())
2120      *          foo(i.next());
2121      *  }
2122      * </pre>
2123      * Failure to follow this advice may result in non-deterministic behavior.
2124      *
2125      * <p>The returned sorted map will be serializable if the specified
2126      * sorted map is serializable.
2127      *
2128      * @param  m the sorted map to be "wrapped" in a synchronized sorted map.
2129      * @return a synchronized view of the specified sorted map.
2130      */
2131     public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
2132         return new SynchronizedSortedMap<K,V>(m);
2133     }
2134 
2135 
2136     /**
2137      * @serial include
2138      */
2139     static class SynchronizedSortedMap<K,V>
2140         extends SynchronizedMap<K,V>
2141         implements SortedMap<K,V>
2142     {
2143         private static final long serialVersionUID = -8798146769416483793L;
2144 
2145         private final SortedMap<K,V> sm;
2146 
2147         SynchronizedSortedMap(SortedMap<K,V> m) {
2148             super(m);
2149             sm = m;
2150         }
2151         SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {
2152             super(m, mutex);
2153             sm = m;
2154         }
2155 
2156         public Comparator<? super K> comparator() {
2157             synchronized (mutex) {return sm.comparator();}
2158         }
2159 
2160         public SortedMap<K,V> subMap(K fromKey, K toKey) {
2161             synchronized (mutex) {
2162                 return new SynchronizedSortedMap<K,V>(
2163                     sm.subMap(fromKey, toKey), mutex);
2164             }
2165         }
2166         public SortedMap<K,V> headMap(K toKey) {
2167             synchronized (mutex) {
2168                 return new SynchronizedSortedMap<K,V>(sm.headMap(toKey), mutex);
2169             }
2170         }
2171         public SortedMap<K,V> tailMap(K fromKey) {
2172             synchronized (mutex) {
2173                return new SynchronizedSortedMap<K,V>(sm.tailMap(fromKey),mutex);
2174             }
2175         }
2176 
2177         public K firstKey() {
2178             synchronized (mutex) {return sm.firstKey();}
2179         }
2180         public K lastKey() {
2181             synchronized (mutex) {return sm.lastKey();}
2182         }
2183     }
2184 
2185     // Dynamically typesafe collection wrappers
2186 
2187     /**
2188      * Returns a dynamically typesafe view of the specified collection.
2189      * Any attempt to insert an element of the wrong type will result in an
2190      * immediate {@link ClassCastException}.  Assuming a collection
2191      * contains no incorrectly typed elements prior to the time a
2192      * dynamically typesafe view is generated, and that all subsequent
2193      * access to the collection takes place through the view, it is


2229      * operations through to the backing collection, but relies on
2230      * {@code Object}'s {@code equals} and {@code hashCode} methods.  This
2231      * is necessary to preserve the contracts of these operations in the case
2232      * that the backing collection is a set or a list.
2233      *
2234      * <p>The returned collection will be serializable if the specified
2235      * collection is serializable.
2236      *
2237      * <p>Since {@code null} is considered to be a value of any reference
2238      * type, the returned collection permits insertion of null elements
2239      * whenever the backing collection does.
2240      *
2241      * @param c the collection for which a dynamically typesafe view is to be
2242      *          returned
2243      * @param type the type of element that {@code c} is permitted to hold
2244      * @return a dynamically typesafe view of the specified collection
2245      * @since 1.5
2246      */
2247     public static <E> Collection<E> checkedCollection(Collection<E> c,
2248                                                       Class<E> type) {
2249         return new CheckedCollection<E>(c, type);
2250     }
2251 
2252     @SuppressWarnings("unchecked")
2253     static <T> T[] zeroLengthArray(Class<T> type) {
2254         return (T[]) Array.newInstance(type, 0);
2255     }
2256 
2257     /**
2258      * @serial include
2259      */
2260     static class CheckedCollection<E> implements Collection<E>, Serializable {
2261         private static final long serialVersionUID = 1578914078182001775L;
2262 
2263         final Collection<E> c;
2264         final Class<E> type;
2265 
2266         void typeCheck(Object o) {
2267             if (o != null && !type.isInstance(o))
2268                 throw new ClassCastException(badElementMsg(o));
2269         }


2361      * set cannot contain an incorrectly typed element.
2362      *
2363      * <p>A discussion of the use of dynamically typesafe views may be
2364      * found in the documentation for the {@link #checkedCollection
2365      * checkedCollection} method.
2366      *
2367      * <p>The returned set will be serializable if the specified set is
2368      * serializable.
2369      *
2370      * <p>Since {@code null} is considered to be a value of any reference
2371      * type, the returned set permits insertion of null elements whenever
2372      * the backing set does.
2373      *
2374      * @param s the set for which a dynamically typesafe view is to be
2375      *          returned
2376      * @param type the type of element that {@code s} is permitted to hold
2377      * @return a dynamically typesafe view of the specified set
2378      * @since 1.5
2379      */
2380     public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
2381         return new CheckedSet<E>(s, type);
2382     }
2383 
2384     /**
2385      * @serial include
2386      */
2387     static class CheckedSet<E> extends CheckedCollection<E>
2388                                  implements Set<E>, Serializable
2389     {
2390         private static final long serialVersionUID = 4694047833775013803L;
2391 
2392         CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
2393 
2394         public boolean equals(Object o) { return o == this || c.equals(o); }
2395         public int hashCode()           { return c.hashCode(); }
2396     }
2397 
2398     /**
2399      * Returns a dynamically typesafe view of the specified sorted set.
2400      * Any attempt to insert an element of the wrong type will result in an
2401      * immediate {@link ClassCastException}.  Assuming a sorted set


2407      *
2408      * <p>A discussion of the use of dynamically typesafe views may be
2409      * found in the documentation for the {@link #checkedCollection
2410      * checkedCollection} method.
2411      *
2412      * <p>The returned sorted set will be serializable if the specified sorted
2413      * set is serializable.
2414      *
2415      * <p>Since {@code null} is considered to be a value of any reference
2416      * type, the returned sorted set permits insertion of null elements
2417      * whenever the backing sorted set does.
2418      *
2419      * @param s the sorted set for which a dynamically typesafe view is to be
2420      *          returned
2421      * @param type the type of element that {@code s} is permitted to hold
2422      * @return a dynamically typesafe view of the specified sorted set
2423      * @since 1.5
2424      */
2425     public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
2426                                                     Class<E> type) {
2427         return new CheckedSortedSet<E>(s, type);
2428     }
2429 
2430     /**
2431      * @serial include
2432      */
2433     static class CheckedSortedSet<E> extends CheckedSet<E>
2434         implements SortedSet<E>, Serializable
2435     {
2436         private static final long serialVersionUID = 1599911165492914959L;
2437         private final SortedSet<E> ss;
2438 
2439         CheckedSortedSet(SortedSet<E> s, Class<E> type) {
2440             super(s, type);
2441             ss = s;
2442         }
2443 
2444         public Comparator<? super E> comparator() { return ss.comparator(); }
2445         public E first()                   { return ss.first(); }
2446         public E last()                    { return ss.last(); }
2447 


2467      *
2468      * <p>A discussion of the use of dynamically typesafe views may be
2469      * found in the documentation for the {@link #checkedCollection
2470      * checkedCollection} method.
2471      *
2472      * <p>The returned list will be serializable if the specified list
2473      * is serializable.
2474      *
2475      * <p>Since {@code null} is considered to be a value of any reference
2476      * type, the returned list permits insertion of null elements whenever
2477      * the backing list does.
2478      *
2479      * @param list the list for which a dynamically typesafe view is to be
2480      *             returned
2481      * @param type the type of element that {@code list} is permitted to hold
2482      * @return a dynamically typesafe view of the specified list
2483      * @since 1.5
2484      */
2485     public static <E> List<E> checkedList(List<E> list, Class<E> type) {
2486         return (list instanceof RandomAccess ?
2487                 new CheckedRandomAccessList<E>(list, type) :
2488                 new CheckedList<E>(list, type));
2489     }
2490 
2491     /**
2492      * @serial include
2493      */
2494     static class CheckedList<E>
2495         extends CheckedCollection<E>
2496         implements List<E>
2497     {
2498         private static final long serialVersionUID = 65247728283967356L;
2499         final List<E> list;
2500 
2501         CheckedList(List<E> list, Class<E> type) {
2502             super(list, type);
2503             this.list = list;
2504         }
2505 
2506         public boolean equals(Object o)  { return o == this || list.equals(o); }
2507         public int hashCode()            { return list.hashCode(); }
2508         public E get(int index)          { return list.get(index); }


2533                 public E next()              { return i.next(); }
2534                 public boolean hasPrevious() { return i.hasPrevious(); }
2535                 public E previous()          { return i.previous(); }
2536                 public int nextIndex()       { return i.nextIndex(); }
2537                 public int previousIndex()   { return i.previousIndex(); }
2538                 public void remove()         {        i.remove(); }
2539 
2540                 public void set(E e) {
2541                     typeCheck(e);
2542                     i.set(e);
2543                 }
2544 
2545                 public void add(E e) {
2546                     typeCheck(e);
2547                     i.add(e);
2548                 }
2549             };
2550         }
2551 
2552         public List<E> subList(int fromIndex, int toIndex) {
2553             return new CheckedList<E>(list.subList(fromIndex, toIndex), type);
2554         }
2555     }
2556 
2557     /**
2558      * @serial include
2559      */
2560     static class CheckedRandomAccessList<E> extends CheckedList<E>
2561                                             implements RandomAccess
2562     {
2563         private static final long serialVersionUID = 1638200125423088369L;
2564 
2565         CheckedRandomAccessList(List<E> list, Class<E> type) {
2566             super(list, type);
2567         }
2568 
2569         public List<E> subList(int fromIndex, int toIndex) {
2570             return new CheckedRandomAccessList<E>(
2571                 list.subList(fromIndex, toIndex), type);
2572         }
2573     }
2574 
2575     /**
2576      * Returns a dynamically typesafe view of the specified map.
2577      * Any attempt to insert a mapping whose key or value have the wrong
2578      * type will result in an immediate {@link ClassCastException}.
2579      * Similarly, any attempt to modify the value currently associated with
2580      * a key will result in an immediate {@link ClassCastException},
2581      * whether the modification is attempted directly through the map
2582      * itself, or through a {@link Map.Entry} instance obtained from the
2583      * map's {@link Map#entrySet() entry set} view.
2584      *
2585      * <p>Assuming a map contains no incorrectly typed keys or values
2586      * prior to the time a dynamically typesafe view is generated, and
2587      * that all subsequent access to the map takes place through the view
2588      * (or one of its collection views), it is <i>guaranteed</i> that the
2589      * map cannot contain an incorrectly typed key or value.
2590      *


2592      * found in the documentation for the {@link #checkedCollection
2593      * checkedCollection} method.
2594      *
2595      * <p>The returned map will be serializable if the specified map is
2596      * serializable.
2597      *
2598      * <p>Since {@code null} is considered to be a value of any reference
2599      * type, the returned map permits insertion of null keys or values
2600      * whenever the backing map does.
2601      *
2602      * @param m the map for which a dynamically typesafe view is to be
2603      *          returned
2604      * @param keyType the type of key that {@code m} is permitted to hold
2605      * @param valueType the type of value that {@code m} is permitted to hold
2606      * @return a dynamically typesafe view of the specified map
2607      * @since 1.5
2608      */
2609     public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
2610                                               Class<K> keyType,
2611                                               Class<V> valueType) {
2612         return new CheckedMap<K,V>(m, keyType, valueType);
2613     }
2614 
2615 
2616     /**
2617      * @serial include
2618      */
2619     private static class CheckedMap<K,V>
2620         implements Map<K,V>, Serializable
2621     {
2622         private static final long serialVersionUID = 5742860141034234728L;
2623 
2624         private final Map<K, V> m;
2625         final Class<K> keyType;
2626         final Class<V> valueType;
2627 
2628         private void typeCheck(Object key, Object value) {
2629             if (key != null && !keyType.isInstance(key))
2630                 throw new ClassCastException(badKeyMsg(key));
2631 
2632             if (value != null && !valueType.isInstance(value))


2661         public Set<K> keySet()                 { return m.keySet(); }
2662         public Collection<V> values()          { return m.values(); }
2663         public boolean equals(Object o)        { return o == this || m.equals(o); }
2664         public int hashCode()                  { return m.hashCode(); }
2665         public String toString()               { return m.toString(); }
2666 
2667         public V put(K key, V value) {
2668             typeCheck(key, value);
2669             return m.put(key, value);
2670         }
2671 
2672         @SuppressWarnings("unchecked")
2673         public void putAll(Map<? extends K, ? extends V> t) {
2674             // Satisfy the following goals:
2675             // - good diagnostics in case of type mismatch
2676             // - all-or-nothing semantics
2677             // - protection from malicious t
2678             // - correct behavior if t is a concurrent map
2679             Object[] entries = t.entrySet().toArray();
2680             List<Map.Entry<K,V>> checked =
2681                 new ArrayList<Map.Entry<K,V>>(entries.length);
2682             for (Object o : entries) {
2683                 Map.Entry<?,?> e = (Map.Entry<?,?>) o;
2684                 Object k = e.getKey();
2685                 Object v = e.getValue();
2686                 typeCheck(k, v);
2687                 checked.add(
2688                     new AbstractMap.SimpleImmutableEntry<K,V>((K) k, (V) v));
2689             }
2690             for (Map.Entry<K,V> e : checked)
2691                 m.put(e.getKey(), e.getValue());
2692         }
2693 
2694         private transient Set<Map.Entry<K,V>> entrySet = null;
2695 
2696         public Set<Map.Entry<K,V>> entrySet() {
2697             if (entrySet==null)
2698                 entrySet = new CheckedEntrySet<K,V>(m.entrySet(), valueType);
2699             return entrySet;
2700         }
2701 
2702         /**
2703          * We need this class in addition to CheckedSet as Map.Entry permits
2704          * modification of the backing Map via the setValue operation.  This
2705          * class is subtle: there are many possible attacks that must be
2706          * thwarted.
2707          *
2708          * @serial exclude
2709          */
2710         static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {
2711             private final Set<Map.Entry<K,V>> s;
2712             private final Class<V> valueType;
2713 
2714             CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {
2715                 this.s = s;
2716                 this.valueType = valueType;
2717             }
2718 


2793                 return s.contains(
2794                     (e instanceof CheckedEntry) ? e : checkedEntry(e, valueType));
2795             }
2796 
2797             /**
2798              * The bulk collection methods are overridden to protect
2799              * against an unscrupulous collection whose contains(Object o)
2800              * method senses when o is a Map.Entry, and calls o.setValue.
2801              */
2802             public boolean containsAll(Collection<?> c) {
2803                 for (Object o : c)
2804                     if (!contains(o)) // Invokes safe contains() above
2805                         return false;
2806                 return true;
2807             }
2808 
2809             public boolean remove(Object o) {
2810                 if (!(o instanceof Map.Entry))
2811                     return false;
2812                 return s.remove(new AbstractMap.SimpleImmutableEntry
2813                                 <Object, Object>((Map.Entry<?,?>)o));
2814             }
2815 
2816             public boolean removeAll(Collection<?> c) {
2817                 return batchRemove(c, false);
2818             }
2819             public boolean retainAll(Collection<?> c) {
2820                 return batchRemove(c, true);
2821             }
2822             private boolean batchRemove(Collection<?> c, boolean complement) {
2823                 boolean modified = false;
2824                 Iterator<Map.Entry<K,V>> it = iterator();
2825                 while (it.hasNext()) {
2826                     if (c.contains(it.next()) != complement) {
2827                         it.remove();
2828                         modified = true;
2829                     }
2830                 }
2831                 return modified;
2832             }
2833 
2834             public boolean equals(Object o) {
2835                 if (o == this)
2836                     return true;
2837                 if (!(o instanceof Set))
2838                     return false;
2839                 Set<?> that = (Set<?>) o;
2840                 return that.size() == s.size()
2841                     && containsAll(that); // Invokes safe containsAll() above
2842             }
2843 
2844             static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,
2845                                                             Class<T> valueType) {
2846                 return new CheckedEntry<K,V,T>(e, valueType);
2847             }
2848 
2849             /**
2850              * This "wrapper class" serves two purposes: it prevents
2851              * the client from modifying the backing Map, by short-circuiting
2852              * the setValue method, and it protects the backing Map against
2853              * an ill-behaved Map.Entry that attempts to modify another
2854              * Map.Entry when asked to perform an equality check.
2855              */
2856             private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {
2857                 private final Map.Entry<K, V> e;
2858                 private final Class<T> valueType;
2859 
2860                 CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {
2861                     this.e = e;
2862                     this.valueType = valueType;
2863                 }
2864 
2865                 public K getKey()        { return e.getKey(); }
2866                 public V getValue()      { return e.getValue(); }
2867                 public int hashCode()    { return e.hashCode(); }
2868                 public String toString() { return e.toString(); }
2869 
2870                 public V setValue(V value) {
2871                     if (value != null && !valueType.isInstance(value))
2872                         throw new ClassCastException(badValueMsg(value));
2873                     return e.setValue(value);
2874                 }
2875 
2876                 private String badValueMsg(Object value) {
2877                     return "Attempt to insert " + value.getClass() +
2878                         " value into map with value type " + valueType;
2879                 }
2880 
2881                 public boolean equals(Object o) {
2882                     if (o == this)
2883                         return true;
2884                     if (!(o instanceof Map.Entry))
2885                         return false;
2886                     return e.equals(new AbstractMap.SimpleImmutableEntry
2887                                     <Object, Object>((Map.Entry<?,?>)o));
2888                 }
2889             }
2890         }
2891     }
2892 
2893     /**
2894      * Returns a dynamically typesafe view of the specified sorted map.
2895      * Any attempt to insert a mapping whose key or value have the wrong
2896      * type will result in an immediate {@link ClassCastException}.
2897      * Similarly, any attempt to modify the value currently associated with
2898      * a key will result in an immediate {@link ClassCastException},
2899      * whether the modification is attempted directly through the map
2900      * itself, or through a {@link Map.Entry} instance obtained from the
2901      * map's {@link Map#entrySet() entry set} view.
2902      *
2903      * <p>Assuming a map contains no incorrectly typed keys or values
2904      * prior to the time a dynamically typesafe view is generated, and
2905      * that all subsequent access to the map takes place through the view
2906      * (or one of its collection views), it is <i>guaranteed</i> that the
2907      * map cannot contain an incorrectly typed key or value.


2910      * found in the documentation for the {@link #checkedCollection
2911      * checkedCollection} method.
2912      *
2913      * <p>The returned map will be serializable if the specified map is
2914      * serializable.
2915      *
2916      * <p>Since {@code null} is considered to be a value of any reference
2917      * type, the returned map permits insertion of null keys or values
2918      * whenever the backing map does.
2919      *
2920      * @param m the map for which a dynamically typesafe view is to be
2921      *          returned
2922      * @param keyType the type of key that {@code m} is permitted to hold
2923      * @param valueType the type of value that {@code m} is permitted to hold
2924      * @return a dynamically typesafe view of the specified map
2925      * @since 1.5
2926      */
2927     public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
2928                                                         Class<K> keyType,
2929                                                         Class<V> valueType) {
2930         return new CheckedSortedMap<K,V>(m, keyType, valueType);
2931     }
2932 
2933     /**
2934      * @serial include
2935      */
2936     static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
2937         implements SortedMap<K,V>, Serializable
2938     {
2939         private static final long serialVersionUID = 1599671320688067438L;
2940 
2941         private final SortedMap<K, V> sm;
2942 
2943         CheckedSortedMap(SortedMap<K, V> m,
2944                          Class<K> keyType, Class<V> valueType) {
2945             super(m, keyType, valueType);
2946             sm = m;
2947         }
2948 
2949         public Comparator<? super K> comparator() { return sm.comparator(); }
2950         public K firstKey()                       { return sm.firstKey(); }


2976      * NoSuchElementException}.
2977      *
2978      * <li>{@link Iterator#remove remove} always throws {@link
2979      * IllegalStateException}.
2980      *
2981      * </ul>
2982      *
2983      * <p>Implementations of this method are permitted, but not
2984      * required, to return the same object from multiple invocations.
2985      *
2986      * @return an empty iterator
2987      * @since 1.7
2988      */
2989     @SuppressWarnings("unchecked")
2990     public static <T> Iterator<T> emptyIterator() {
2991         return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;
2992     }
2993 
2994     private static class EmptyIterator<E> implements Iterator<E> {
2995         static final EmptyIterator<Object> EMPTY_ITERATOR
2996             = new EmptyIterator<Object>();
2997 
2998         public boolean hasNext() { return false; }
2999         public E next() { throw new NoSuchElementException(); }
3000         public void remove() { throw new IllegalStateException(); }
3001     }
3002 
3003     /**
3004      * Returns a list iterator that has no elements.  More precisely,
3005      *
3006      * <ul compact>
3007      *
3008      * <li>{@link Iterator#hasNext hasNext} and {@link
3009      * ListIterator#hasPrevious hasPrevious} always return {@code
3010      * false}.
3011      *
3012      * <li>{@link Iterator#next next} and {@link ListIterator#previous
3013      * previous} always throw {@link NoSuchElementException}.
3014      *
3015      * <li>{@link Iterator#remove remove} and {@link ListIterator#set
3016      * set} always throw {@link IllegalStateException}.


3025      * returns {@code -1}.
3026      *
3027      * </ul>
3028      *
3029      * <p>Implementations of this method are permitted, but not
3030      * required, to return the same object from multiple invocations.
3031      *
3032      * @return an empty list iterator
3033      * @since 1.7
3034      */
3035     @SuppressWarnings("unchecked")
3036     public static <T> ListIterator<T> emptyListIterator() {
3037         return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR;
3038     }
3039 
3040     private static class EmptyListIterator<E>
3041         extends EmptyIterator<E>
3042         implements ListIterator<E>
3043     {
3044         static final EmptyListIterator<Object> EMPTY_ITERATOR
3045             = new EmptyListIterator<Object>();
3046 
3047         public boolean hasPrevious() { return false; }
3048         public E previous() { throw new NoSuchElementException(); }
3049         public int nextIndex()     { return 0; }
3050         public int previousIndex() { return -1; }
3051         public void set(E e) { throw new IllegalStateException(); }
3052         public void add(E e) { throw new UnsupportedOperationException(); }
3053     }
3054 
3055     /**
3056      * Returns an enumeration that has no elements.  More precisely,
3057      *
3058      * <ul compact>
3059      *
3060      * <li>{@link Enumeration#hasMoreElements hasMoreElements} always
3061      * returns {@code false}.
3062      *
3063      * <li> {@link Enumeration#nextElement nextElement} always throws
3064      * {@link NoSuchElementException}.
3065      *
3066      * </ul>
3067      *
3068      * <p>Implementations of this method are permitted, but not
3069      * required, to return the same object from multiple invocations.
3070      *
3071      * @return an empty enumeration
3072      * @since 1.7
3073      */
3074     @SuppressWarnings("unchecked")
3075     public static <T> Enumeration<T> emptyEnumeration() {
3076         return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;
3077     }
3078 
3079     private static class EmptyEnumeration<E> implements Enumeration<E> {
3080         static final EmptyEnumeration<Object> EMPTY_ENUMERATION
3081             = new EmptyEnumeration<Object>();
3082 
3083         public boolean hasMoreElements() { return false; }
3084         public E nextElement() { throw new NoSuchElementException(); }
3085     }
3086 
3087     /**
3088      * The empty set (immutable).  This set is serializable.
3089      *
3090      * @see #emptySet()
3091      */
3092     @SuppressWarnings("unchecked")
3093     public static final Set EMPTY_SET = new EmptySet<Object>();
3094 
3095     /**
3096      * Returns the empty set (immutable).  This set is serializable.
3097      * Unlike the like-named field, this method is parameterized.
3098      *
3099      * <p>This example illustrates the type-safe way to obtain an empty set:
3100      * <pre>
3101      *     Set&lt;String&gt; s = Collections.emptySet();
3102      * </pre>
3103      * Implementation note:  Implementations of this method need not
3104      * create a separate <tt>Set</tt> object for each call.   Using this
3105      * method is likely to have comparable cost to using the like-named
3106      * field.  (Unlike this method, the field does not provide type safety.)
3107      *
3108      * @see #EMPTY_SET
3109      * @since 1.5
3110      */
3111     @SuppressWarnings("unchecked")
3112     public static final <T> Set<T> emptySet() {
3113         return (Set<T>) EMPTY_SET;


3133         public Object[] toArray() { return new Object[0]; }
3134 
3135         public <T> T[] toArray(T[] a) {
3136             if (a.length > 0)
3137                 a[0] = null;
3138             return a;
3139         }
3140 
3141         // Preserves singleton property
3142         private Object readResolve() {
3143             return EMPTY_SET;
3144         }
3145     }
3146 
3147     /**
3148      * The empty list (immutable).  This list is serializable.
3149      *
3150      * @see #emptyList()
3151      */
3152     @SuppressWarnings("unchecked")
3153     public static final List EMPTY_LIST = new EmptyList<Object>();
3154 
3155     /**
3156      * Returns the empty list (immutable).  This list is serializable.
3157      *
3158      * <p>This example illustrates the type-safe way to obtain an empty list:
3159      * <pre>
3160      *     List&lt;String&gt; s = Collections.emptyList();
3161      * </pre>
3162      * Implementation note:  Implementations of this method need not
3163      * create a separate <tt>List</tt> object for each call.   Using this
3164      * method is likely to have comparable cost to using the like-named
3165      * field.  (Unlike this method, the field does not provide type safety.)
3166      *
3167      * @see #EMPTY_LIST
3168      * @since 1.5
3169      */
3170     @SuppressWarnings("unchecked")
3171     public static final <T> List<T> emptyList() {
3172         return (List<T>) EMPTY_LIST;
3173     }


3207 
3208         public boolean equals(Object o) {
3209             return (o instanceof List) && ((List<?>)o).isEmpty();
3210         }
3211 
3212         public int hashCode() { return 1; }
3213 
3214         // Preserves singleton property
3215         private Object readResolve() {
3216             return EMPTY_LIST;
3217         }
3218     }
3219 
3220     /**
3221      * The empty map (immutable).  This map is serializable.
3222      *
3223      * @see #emptyMap()
3224      * @since 1.3
3225      */
3226     @SuppressWarnings("unchecked")
3227     public static final Map EMPTY_MAP = new EmptyMap<Object,Object>();
3228 
3229     /**
3230      * Returns the empty map (immutable).  This map is serializable.
3231      *
3232      * <p>This example illustrates the type-safe way to obtain an empty set:
3233      * <pre>
3234      *     Map&lt;String, Date&gt; s = Collections.emptyMap();
3235      * </pre>
3236      * Implementation note:  Implementations of this method need not
3237      * create a separate <tt>Map</tt> object for each call.   Using this
3238      * method is likely to have comparable cost to using the like-named
3239      * field.  (Unlike this method, the field does not provide type safety.)
3240      *
3241      * @see #EMPTY_MAP
3242      * @since 1.5
3243      */
3244     @SuppressWarnings("unchecked")
3245     public static final <K,V> Map<K,V> emptyMap() {
3246         return (Map<K,V>) EMPTY_MAP;
3247     }


3269         }
3270 
3271         public int hashCode()                      {return 0;}
3272 
3273         // Preserves singleton property
3274         private Object readResolve() {
3275             return EMPTY_MAP;
3276         }
3277     }
3278 
3279     // Singleton collections
3280 
3281     /**
3282      * Returns an immutable set containing only the specified object.
3283      * The returned set is serializable.
3284      *
3285      * @param o the sole object to be stored in the returned set.
3286      * @return an immutable set containing only the specified object.
3287      */
3288     public static <T> Set<T> singleton(T o) {
3289         return new SingletonSet<T>(o);
3290     }
3291 
3292     static <E> Iterator<E> singletonIterator(final E e) {
3293         return new Iterator<E>() {
3294             private boolean hasNext = true;
3295             public boolean hasNext() {
3296                 return hasNext;
3297             }
3298             public E next() {
3299                 if (hasNext) {
3300                     hasNext = false;
3301                     return e;
3302                 }
3303                 throw new NoSuchElementException();
3304             }
3305             public void remove() {
3306                 throw new UnsupportedOperationException();
3307             }
3308         };
3309     }


3322         SingletonSet(E e) {element = e;}
3323 
3324         public Iterator<E> iterator() {
3325             return singletonIterator(element);
3326         }
3327 
3328         public int size() {return 1;}
3329 
3330         public boolean contains(Object o) {return eq(o, element);}
3331     }
3332 
3333     /**
3334      * Returns an immutable list containing only the specified object.
3335      * The returned list is serializable.
3336      *
3337      * @param o the sole object to be stored in the returned list.
3338      * @return an immutable list containing only the specified object.
3339      * @since 1.3
3340      */
3341     public static <T> List<T> singletonList(T o) {
3342         return new SingletonList<T>(o);
3343     }
3344 
3345     /**
3346      * @serial include
3347      */
3348     private static class SingletonList<E>
3349         extends AbstractList<E>
3350         implements RandomAccess, Serializable {
3351 
3352         private static final long serialVersionUID = 3093736618740652951L;
3353 
3354         private final E element;
3355 
3356         SingletonList(E obj)                {element = obj;}
3357 
3358         public Iterator<E> iterator() {
3359             return singletonIterator(element);
3360         }
3361 
3362         public int size()                   {return 1;}


3364         public boolean contains(Object obj) {return eq(obj, element);}
3365 
3366         public E get(int index) {
3367             if (index != 0)
3368               throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
3369             return element;
3370         }
3371     }
3372 
3373     /**
3374      * Returns an immutable map, mapping only the specified key to the
3375      * specified value.  The returned map is serializable.
3376      *
3377      * @param key the sole key to be stored in the returned map.
3378      * @param value the value to which the returned map maps <tt>key</tt>.
3379      * @return an immutable map containing only the specified key-value
3380      *         mapping.
3381      * @since 1.3
3382      */
3383     public static <K,V> Map<K,V> singletonMap(K key, V value) {
3384         return new SingletonMap<K,V>(key, value);
3385     }
3386 
3387     /**
3388      * @serial include
3389      */
3390     private static class SingletonMap<K,V>
3391           extends AbstractMap<K,V>
3392           implements Serializable {
3393         private static final long serialVersionUID = -6979724477215052911L;
3394 
3395         private final K k;
3396         private final V v;
3397 
3398         SingletonMap(K key, V value) {
3399             k = key;
3400             v = value;
3401         }
3402 
3403         public int size()                          {return 1;}
3404 


3406 
3407         public boolean containsKey(Object key)     {return eq(key, k);}
3408 
3409         public boolean containsValue(Object value) {return eq(value, v);}
3410 
3411         public V get(Object key)                   {return (eq(key, k) ? v : null);}
3412 
3413         private transient Set<K> keySet = null;
3414         private transient Set<Map.Entry<K,V>> entrySet = null;
3415         private transient Collection<V> values = null;
3416 
3417         public Set<K> keySet() {
3418             if (keySet==null)
3419                 keySet = singleton(k);
3420             return keySet;
3421         }
3422 
3423         public Set<Map.Entry<K,V>> entrySet() {
3424             if (entrySet==null)
3425                 entrySet = Collections.<Map.Entry<K,V>>singleton(
3426                     new SimpleImmutableEntry<K,V>(k, v));
3427             return entrySet;
3428         }
3429 
3430         public Collection<V> values() {
3431             if (values==null)
3432                 values = singleton(v);
3433             return values;
3434         }
3435 
3436     }
3437 
3438     // Miscellaneous
3439 
3440     /**
3441      * Returns an immutable list consisting of <tt>n</tt> copies of the
3442      * specified object.  The newly allocated data object is tiny (it contains
3443      * a single reference to the data object).  This method is useful in
3444      * combination with the <tt>List.addAll</tt> method to grow lists.
3445      * The returned list is serializable.
3446      *
3447      * @param  n the number of elements in the returned list.
3448      * @param  o the element to appear repeatedly in the returned list.
3449      * @return an immutable list consisting of <tt>n</tt> copies of the
3450      *         specified object.
3451      * @throws IllegalArgumentException if {@code n < 0}
3452      * @see    List#addAll(Collection)
3453      * @see    List#addAll(int, Collection)
3454      */
3455     public static <T> List<T> nCopies(int n, T o) {
3456         if (n < 0)
3457             throw new IllegalArgumentException("List length = " + n);
3458         return new CopiesList<T>(n, o);
3459     }
3460 
3461     /**
3462      * @serial include
3463      */
3464     private static class CopiesList<E>
3465         extends AbstractList<E>
3466         implements RandomAccess, Serializable
3467     {
3468         private static final long serialVersionUID = 2739099268398711800L;
3469 
3470         final int n;
3471         final E element;
3472 
3473         CopiesList(int n, E e) {
3474             assert n >= 0;
3475             this.n = n;
3476             element = e;
3477         }
3478 


3512                 a = (T[])java.lang.reflect.Array
3513                     .newInstance(a.getClass().getComponentType(), n);
3514                 if (element != null)
3515                     Arrays.fill(a, 0, n, element);
3516             } else {
3517                 Arrays.fill(a, 0, n, element);
3518                 if (a.length > n)
3519                     a[n] = null;
3520             }
3521             return a;
3522         }
3523 
3524         public List<E> subList(int fromIndex, int toIndex) {
3525             if (fromIndex < 0)
3526                 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
3527             if (toIndex > n)
3528                 throw new IndexOutOfBoundsException("toIndex = " + toIndex);
3529             if (fromIndex > toIndex)
3530                 throw new IllegalArgumentException("fromIndex(" + fromIndex +
3531                                                    ") > toIndex(" + toIndex + ")");
3532             return new CopiesList<E>(toIndex - fromIndex, element);
3533         }
3534     }
3535 
3536     /**
3537      * Returns a comparator that imposes the reverse of the <i>natural
3538      * ordering</i> on a collection of objects that implement the
3539      * <tt>Comparable</tt> interface.  (The natural ordering is the ordering
3540      * imposed by the objects' own <tt>compareTo</tt> method.)  This enables a
3541      * simple idiom for sorting (or maintaining) collections (or arrays) of
3542      * objects that implement the <tt>Comparable</tt> interface in
3543      * reverse-natural-order.  For example, suppose a is an array of
3544      * strings. Then: <pre>
3545      *          Arrays.sort(a, Collections.reverseOrder());
3546      * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
3547      *
3548      * The returned comparator is serializable.
3549      *
3550      * @return a comparator that imposes the reverse of the <i>natural
3551      *         ordering</i> on a collection of objects that implement
3552      *         the <tt>Comparable</tt> interface.


3578      * Returns a comparator that imposes the reverse ordering of the specified
3579      * comparator.  If the specified comparator is null, this method is
3580      * equivalent to {@link #reverseOrder()} (in other words, it returns a
3581      * comparator that imposes the reverse of the <i>natural ordering</i> on a
3582      * collection of objects that implement the Comparable interface).
3583      *
3584      * <p>The returned comparator is serializable (assuming the specified
3585      * comparator is also serializable or null).
3586      *
3587      * @return a comparator that imposes the reverse ordering of the
3588      *         specified comparator
3589      * @since 1.5
3590      */
3591     public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
3592         if (cmp == null)
3593             return reverseOrder();
3594 
3595         if (cmp instanceof ReverseComparator2)
3596             return ((ReverseComparator2<T>)cmp).cmp;
3597 
3598         return new ReverseComparator2<T>(cmp);
3599     }
3600 
3601     /**
3602      * @serial include
3603      */
3604     private static class ReverseComparator2<T> implements Comparator<T>,
3605         Serializable
3606     {
3607         private static final long serialVersionUID = 4374092139857L;
3608 
3609         /**
3610          * The comparator specified in the static factory.  This will never
3611          * be null, as the static factory returns a ReverseComparator
3612          * instance if its argument is null.
3613          *
3614          * @serial
3615          */
3616         final Comparator<T> cmp;
3617 
3618         ReverseComparator2(Comparator<T> cmp) {


3657             }
3658         };
3659     }
3660 
3661     /**
3662      * Returns an array list containing the elements returned by the
3663      * specified enumeration in the order they are returned by the
3664      * enumeration.  This method provides interoperability between
3665      * legacy APIs that return enumerations and new APIs that require
3666      * collections.
3667      *
3668      * @param e enumeration providing elements for the returned
3669      *          array list
3670      * @return an array list containing the elements returned
3671      *         by the specified enumeration.
3672      * @since 1.4
3673      * @see Enumeration
3674      * @see ArrayList
3675      */
3676     public static <T> ArrayList<T> list(Enumeration<T> e) {
3677         ArrayList<T> l = new ArrayList<T>();
3678         while (e.hasMoreElements())
3679             l.add(e.nextElement());
3680         return l;
3681     }
3682 
3683     /**
3684      * Returns true if the specified arguments are equal, or both null.
3685      */
3686     static boolean eq(Object o1, Object o2) {
3687         return o1==null ? o2==null : o1.equals(o2);
3688     }
3689 
3690     /**
3691      * Returns the number of elements in the specified collection equal to the
3692      * specified object.  More formally, returns the number of elements
3693      * <tt>e</tt> in the collection such that
3694      * <tt>(o == null ? e == null : o.equals(e))</tt>.
3695      *
3696      * @param c the collection in which to determine the frequency
3697      *     of <tt>o</tt>


3802      * exactly one method invocation on the backing map or its <tt>keySet</tt>
3803      * view, with one exception.  The <tt>addAll</tt> method is implemented
3804      * as a sequence of <tt>put</tt> invocations on the backing map.
3805      *
3806      * <p>The specified map must be empty at the time this method is invoked,
3807      * and should not be accessed directly after this method returns.  These
3808      * conditions are ensured if the map is created empty, passed directly
3809      * to this method, and no reference to the map is retained, as illustrated
3810      * in the following code fragment:
3811      * <pre>
3812      *    Set&lt;Object&gt; weakHashSet = Collections.newSetFromMap(
3813      *        new WeakHashMap&lt;Object, Boolean&gt;());
3814      * </pre>
3815      *
3816      * @param map the backing map
3817      * @return the set backed by the map
3818      * @throws IllegalArgumentException if <tt>map</tt> is not empty
3819      * @since 1.6
3820      */
3821     public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
3822         return new SetFromMap<E>(map);
3823     }
3824 
3825     /**
3826      * @serial include
3827      */
3828     private static class SetFromMap<E> extends AbstractSet<E>
3829         implements Set<E>, Serializable
3830     {
3831         private final Map<E, Boolean> m;  // The backing map
3832         private transient Set<E> s;       // Its keySet
3833 
3834         SetFromMap(Map<E, Boolean> map) {
3835             if (!map.isEmpty())
3836                 throw new IllegalArgumentException("Map is non-empty");
3837             m = map;
3838             s = map.keySet();
3839         }
3840 
3841         public void clear()               {        m.clear(); }
3842         public int size()                 { return m.size(); }


3866     }
3867 
3868     /**
3869      * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
3870      * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>,
3871      * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This
3872      * view can be useful when you would like to use a method
3873      * requiring a <tt>Queue</tt> but you need Lifo ordering.
3874      *
3875      * <p>Each method invocation on the queue returned by this method
3876      * results in exactly one method invocation on the backing deque, with
3877      * one exception.  The {@link Queue#addAll addAll} method is
3878      * implemented as a sequence of {@link Deque#addFirst addFirst}
3879      * invocations on the backing deque.
3880      *
3881      * @param deque the deque
3882      * @return the queue
3883      * @since  1.6
3884      */
3885     public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
3886         return new AsLIFOQueue<T>(deque);
3887     }
3888 
3889     /**
3890      * @serial include
3891      */
3892     static class AsLIFOQueue<E> extends AbstractQueue<E>
3893         implements Queue<E>, Serializable {
3894         private static final long serialVersionUID = 1802017725587941708L;
3895         private final Deque<E> q;
3896         AsLIFOQueue(Deque<E> q)           { this.q = q; }
3897         public boolean add(E e)           { q.addFirst(e); return true; }
3898         public boolean offer(E e)         { return q.offerFirst(e); }
3899         public E poll()                   { return q.pollFirst(); }
3900         public E remove()                 { return q.removeFirst(); }
3901         public E peek()                   { return q.peekFirst(); }
3902         public E element()                { return q.getFirst(); }
3903         public void clear()               {        q.clear(); }
3904         public int size()                 { return q.size(); }
3905         public boolean isEmpty()          { return q.isEmpty(); }
3906         public boolean contains(Object o) { return q.contains(o); }


1018      * allows modules to provide users with "read-only" access to internal
1019      * collections.  Query operations on the returned collection "read through"
1020      * to the specified collection, and attempts to modify the returned
1021      * collection, whether direct or via its iterator, result in an
1022      * <tt>UnsupportedOperationException</tt>.<p>
1023      *
1024      * The returned collection does <i>not</i> pass the hashCode and equals
1025      * operations through to the backing collection, but relies on
1026      * <tt>Object</tt>'s <tt>equals</tt> and <tt>hashCode</tt> methods.  This
1027      * is necessary to preserve the contracts of these operations in the case
1028      * that the backing collection is a set or a list.<p>
1029      *
1030      * The returned collection will be serializable if the specified collection
1031      * is serializable.
1032      *
1033      * @param  c the collection for which an unmodifiable view is to be
1034      *         returned.
1035      * @return an unmodifiable view of the specified collection.
1036      */
1037     public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
1038         return new UnmodifiableCollection<>(c);
1039     }
1040 
1041     /**
1042      * @serial include
1043      */
1044     static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
1045         private static final long serialVersionUID = 1820017752578914078L;
1046 
1047         final Collection<? extends E> c;
1048 
1049         UnmodifiableCollection(Collection<? extends E> c) {
1050             if (c==null)
1051                 throw new NullPointerException();
1052             this.c = c;
1053         }
1054 
1055         public int size()                   {return c.size();}
1056         public boolean isEmpty()            {return c.isEmpty();}
1057         public boolean contains(Object o)   {return c.contains(o);}
1058         public Object[] toArray()           {return c.toArray();}


1092         }
1093         public void clear() {
1094             throw new UnsupportedOperationException();
1095         }
1096     }
1097 
1098     /**
1099      * Returns an unmodifiable view of the specified set.  This method allows
1100      * modules to provide users with "read-only" access to internal sets.
1101      * Query operations on the returned set "read through" to the specified
1102      * set, and attempts to modify the returned set, whether direct or via its
1103      * iterator, result in an <tt>UnsupportedOperationException</tt>.<p>
1104      *
1105      * The returned set will be serializable if the specified set
1106      * is serializable.
1107      *
1108      * @param  s the set for which an unmodifiable view is to be returned.
1109      * @return an unmodifiable view of the specified set.
1110      */
1111     public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
1112         return new UnmodifiableSet<>(s);
1113     }
1114 
1115     /**
1116      * @serial include
1117      */
1118     static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
1119                                  implements Set<E>, Serializable {
1120         private static final long serialVersionUID = -9215047833775013803L;
1121 
1122         UnmodifiableSet(Set<? extends E> s)     {super(s);}
1123         public boolean equals(Object o) {return o == this || c.equals(o);}
1124         public int hashCode()           {return c.hashCode();}
1125     }
1126 
1127     /**
1128      * Returns an unmodifiable view of the specified sorted set.  This method
1129      * allows modules to provide users with "read-only" access to internal
1130      * sorted sets.  Query operations on the returned sorted set "read
1131      * through" to the specified sorted set.  Attempts to modify the returned
1132      * sorted set, whether direct, via its iterator, or via its
1133      * <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in
1134      * an <tt>UnsupportedOperationException</tt>.<p>
1135      *
1136      * The returned sorted set will be serializable if the specified sorted set
1137      * is serializable.
1138      *
1139      * @param s the sorted set for which an unmodifiable view is to be
1140      *        returned.
1141      * @return an unmodifiable view of the specified sorted set.
1142      */
1143     public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
1144         return new UnmodifiableSortedSet<>(s);
1145     }
1146 
1147     /**
1148      * @serial include
1149      */
1150     static class UnmodifiableSortedSet<E>
1151                              extends UnmodifiableSet<E>
1152                              implements SortedSet<E>, Serializable {
1153         private static final long serialVersionUID = -4929149591599911165L;
1154         private final SortedSet<E> ss;
1155 
1156         UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
1157 
1158         public Comparator<? super E> comparator() {return ss.comparator();}
1159 
1160         public SortedSet<E> subSet(E fromElement, E toElement) {
1161             return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
1162         }
1163         public SortedSet<E> headSet(E toElement) {
1164             return new UnmodifiableSortedSet<>(ss.headSet(toElement));
1165         }
1166         public SortedSet<E> tailSet(E fromElement) {
1167             return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
1168         }
1169 
1170         public E first()                   {return ss.first();}
1171         public E last()                    {return ss.last();}
1172     }
1173 
1174     /**
1175      * Returns an unmodifiable view of the specified list.  This method allows
1176      * modules to provide users with "read-only" access to internal
1177      * lists.  Query operations on the returned list "read through" to the
1178      * specified list, and attempts to modify the returned list, whether
1179      * direct or via its iterator, result in an
1180      * <tt>UnsupportedOperationException</tt>.<p>
1181      *
1182      * The returned list will be serializable if the specified list
1183      * is serializable. Similarly, the returned list will implement
1184      * {@link RandomAccess} if the specified list does.
1185      *
1186      * @param  list the list for which an unmodifiable view is to be returned.
1187      * @return an unmodifiable view of the specified list.
1188      */
1189     public static <T> List<T> unmodifiableList(List<? extends T> list) {
1190         return (list instanceof RandomAccess ?
1191                 new UnmodifiableRandomAccessList<>(list) :
1192                 new UnmodifiableList<>(list));
1193     }
1194 
1195     /**
1196      * @serial include
1197      */
1198     static class UnmodifiableList<E> extends UnmodifiableCollection<E>
1199                                   implements List<E> {
1200         private static final long serialVersionUID = -283967356065247728L;
1201         final List<? extends E> list;
1202 
1203         UnmodifiableList(List<? extends E> list) {
1204             super(list);
1205             this.list = list;
1206         }
1207 
1208         public boolean equals(Object o) {return o == this || list.equals(o);}
1209         public int hashCode()           {return list.hashCode();}
1210 
1211         public E get(int index) {return list.get(index);}
1212         public E set(int index, E element) {


1233                 public boolean hasNext()     {return i.hasNext();}
1234                 public E next()              {return i.next();}
1235                 public boolean hasPrevious() {return i.hasPrevious();}
1236                 public E previous()          {return i.previous();}
1237                 public int nextIndex()       {return i.nextIndex();}
1238                 public int previousIndex()   {return i.previousIndex();}
1239 
1240                 public void remove() {
1241                     throw new UnsupportedOperationException();
1242                 }
1243                 public void set(E e) {
1244                     throw new UnsupportedOperationException();
1245                 }
1246                 public void add(E e) {
1247                     throw new UnsupportedOperationException();
1248                 }
1249             };
1250         }
1251 
1252         public List<E> subList(int fromIndex, int toIndex) {
1253             return new UnmodifiableList<>(list.subList(fromIndex, toIndex));
1254         }
1255 
1256         /**
1257          * UnmodifiableRandomAccessList instances are serialized as
1258          * UnmodifiableList instances to allow them to be deserialized
1259          * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
1260          * This method inverts the transformation.  As a beneficial
1261          * side-effect, it also grafts the RandomAccess marker onto
1262          * UnmodifiableList instances that were serialized in pre-1.4 JREs.
1263          *
1264          * Note: Unfortunately, UnmodifiableRandomAccessList instances
1265          * serialized in 1.4.1 and deserialized in 1.4 will become
1266          * UnmodifiableList instances, as this method was missing in 1.4.
1267          */
1268         private Object readResolve() {
1269             return (list instanceof RandomAccess
1270                     ? new UnmodifiableRandomAccessList<>(list)
1271                     : this);
1272         }
1273     }
1274 
1275     /**
1276      * @serial include
1277      */
1278     static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>
1279                                               implements RandomAccess
1280     {
1281         UnmodifiableRandomAccessList(List<? extends E> list) {
1282             super(list);
1283         }
1284 
1285         public List<E> subList(int fromIndex, int toIndex) {
1286             return new UnmodifiableRandomAccessList<>(
1287                 list.subList(fromIndex, toIndex));
1288         }
1289 
1290         private static final long serialVersionUID = -2542308836966382001L;
1291 
1292         /**
1293          * Allows instances to be deserialized in pre-1.4 JREs (which do
1294          * not have UnmodifiableRandomAccessList).  UnmodifiableList has
1295          * a readResolve method that inverts this transformation upon
1296          * deserialization.
1297          */
1298         private Object writeReplace() {
1299             return new UnmodifiableList<>(list);
1300         }
1301     }
1302 
1303     /**
1304      * Returns an unmodifiable view of the specified map.  This method
1305      * allows modules to provide users with "read-only" access to internal
1306      * maps.  Query operations on the returned map "read through"
1307      * to the specified map, and attempts to modify the returned
1308      * map, whether direct or via its collection views, result in an
1309      * <tt>UnsupportedOperationException</tt>.<p>
1310      *
1311      * The returned map will be serializable if the specified map
1312      * is serializable.
1313      *
1314      * @param  m the map for which an unmodifiable view is to be returned.
1315      * @return an unmodifiable view of the specified map.
1316      */
1317     public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
1318         return new UnmodifiableMap<>(m);
1319     }
1320 
1321     /**
1322      * @serial include
1323      */
1324     private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
1325         private static final long serialVersionUID = -1034234728574286014L;
1326 
1327         private final Map<? extends K, ? extends V> m;
1328 
1329         UnmodifiableMap(Map<? extends K, ? extends V> m) {
1330             if (m==null)
1331                 throw new NullPointerException();
1332             this.m = m;
1333         }
1334 
1335         public int size()                        {return m.size();}
1336         public boolean isEmpty()                 {return m.isEmpty();}
1337         public boolean containsKey(Object key)   {return m.containsKey(key);}
1338         public boolean containsValue(Object val) {return m.containsValue(val);}


1346         }
1347         public void putAll(Map<? extends K, ? extends V> m) {
1348             throw new UnsupportedOperationException();
1349         }
1350         public void clear() {
1351             throw new UnsupportedOperationException();
1352         }
1353 
1354         private transient Set<K> keySet = null;
1355         private transient Set<Map.Entry<K,V>> entrySet = null;
1356         private transient Collection<V> values = null;
1357 
1358         public Set<K> keySet() {
1359             if (keySet==null)
1360                 keySet = unmodifiableSet(m.keySet());
1361             return keySet;
1362         }
1363 
1364         public Set<Map.Entry<K,V>> entrySet() {
1365             if (entrySet==null)
1366                 entrySet = new UnmodifiableEntrySet<>(m.entrySet());
1367             return entrySet;
1368         }
1369 
1370         public Collection<V> values() {
1371             if (values==null)
1372                 values = unmodifiableCollection(m.values());
1373             return values;
1374         }
1375 
1376         public boolean equals(Object o) {return o == this || m.equals(o);}
1377         public int hashCode()           {return m.hashCode();}
1378         public String toString()        {return m.toString();}
1379 
1380         /**
1381          * We need this class in addition to UnmodifiableSet as
1382          * Map.Entries themselves permit modification of the backing Map
1383          * via their setValue operation.  This class is subtle: there are
1384          * many possible attacks that must be thwarted.
1385          *
1386          * @serial include
1387          */
1388         static class UnmodifiableEntrySet<K,V>
1389             extends UnmodifiableSet<Map.Entry<K,V>> {
1390             private static final long serialVersionUID = 7854390611657943733L;
1391 
1392             UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
1393                 super((Set)s);
1394             }
1395             public Iterator<Map.Entry<K,V>> iterator() {
1396                 return new Iterator<Map.Entry<K,V>>() {
1397                     private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
1398 
1399                     public boolean hasNext() {
1400                         return i.hasNext();
1401                     }
1402                     public Map.Entry<K,V> next() {
1403                         return new UnmodifiableEntry<>(i.next());
1404                     }
1405                     public void remove() {
1406                         throw new UnsupportedOperationException();
1407                     }
1408                 };
1409             }
1410 
1411             public Object[] toArray() {
1412                 Object[] a = c.toArray();
1413                 for (int i=0; i<a.length; i++)
1414                     a[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)a[i]);
1415                 return a;
1416             }
1417 
1418             public <T> T[] toArray(T[] a) {
1419                 // We don't pass a to c.toArray, to avoid window of
1420                 // vulnerability wherein an unscrupulous multithreaded client
1421                 // could get his hands on raw (unwrapped) Entries from c.
1422                 Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
1423 
1424                 for (int i=0; i<arr.length; i++)
1425                     arr[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)arr[i]);
1426 
1427                 if (arr.length > a.length)
1428                     return (T[])arr;
1429 
1430                 System.arraycopy(arr, 0, a, 0, arr.length);
1431                 if (a.length > arr.length)
1432                     a[arr.length] = null;
1433                 return a;
1434             }
1435 
1436             /**
1437              * This method is overridden to protect the backing set against
1438              * an object with a nefarious equals function that senses
1439              * that the equality-candidate is Map.Entry and calls its
1440              * setValue method.
1441              */
1442             public boolean contains(Object o) {
1443                 if (!(o instanceof Map.Entry))
1444                     return false;
1445                 return c.contains(
1446                     new UnmodifiableEntry<>((Map.Entry<?,?>) o));
1447             }
1448 
1449             /**
1450              * The next two methods are overridden to protect against
1451              * an unscrupulous List whose contains(Object o) method senses
1452              * when o is a Map.Entry, and calls o.setValue.
1453              */
1454             public boolean containsAll(Collection<?> coll) {
1455                 Iterator<?> it = coll.iterator();
1456                 while (it.hasNext())
1457                     if (!contains(it.next())) // Invokes safe contains() above
1458                         return false;
1459                 return true;
1460             }
1461             public boolean equals(Object o) {
1462                 if (o == this)
1463                     return true;
1464 
1465                 if (!(o instanceof Set))
1466                     return false;


1500         }
1501     }
1502 
1503     /**
1504      * Returns an unmodifiable view of the specified sorted map.  This method
1505      * allows modules to provide users with "read-only" access to internal
1506      * sorted maps.  Query operations on the returned sorted map "read through"
1507      * to the specified sorted map.  Attempts to modify the returned
1508      * sorted map, whether direct, via its collection views, or via its
1509      * <tt>subMap</tt>, <tt>headMap</tt>, or <tt>tailMap</tt> views, result in
1510      * an <tt>UnsupportedOperationException</tt>.<p>
1511      *
1512      * The returned sorted map will be serializable if the specified sorted map
1513      * is serializable.
1514      *
1515      * @param m the sorted map for which an unmodifiable view is to be
1516      *        returned.
1517      * @return an unmodifiable view of the specified sorted map.
1518      */
1519     public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
1520         return new UnmodifiableSortedMap<>(m);
1521     }
1522 
1523     /**
1524      * @serial include
1525      */
1526     static class UnmodifiableSortedMap<K,V>
1527           extends UnmodifiableMap<K,V>
1528           implements SortedMap<K,V>, Serializable {
1529         private static final long serialVersionUID = -8806743815996713206L;
1530 
1531         private final SortedMap<K, ? extends V> sm;
1532 
1533         UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}
1534 
1535         public Comparator<? super K> comparator() {return sm.comparator();}
1536 
1537         public SortedMap<K,V> subMap(K fromKey, K toKey) {
1538             return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey));
1539         }
1540         public SortedMap<K,V> headMap(K toKey) {
1541             return new UnmodifiableSortedMap<>(sm.headMap(toKey));
1542         }
1543         public SortedMap<K,V> tailMap(K fromKey) {
1544             return new UnmodifiableSortedMap<>(sm.tailMap(fromKey));
1545         }
1546 
1547         public K firstKey()           {return sm.firstKey();}
1548         public K lastKey()            {return sm.lastKey();}
1549     }
1550 
1551 
1552     // Synch Wrappers
1553 
1554     /**
1555      * Returns a synchronized (thread-safe) collection backed by the specified
1556      * collection.  In order to guarantee serial access, it is critical that
1557      * <strong>all</strong> access to the backing collection is accomplished
1558      * through the returned collection.<p>
1559      *
1560      * It is imperative that the user manually synchronize on the returned
1561      * collection when iterating over it:
1562      * <pre>
1563      *  Collection c = Collections.synchronizedCollection(myCollection);
1564      *     ...


1566      *      Iterator i = c.iterator(); // Must be in the synchronized block
1567      *      while (i.hasNext())
1568      *         foo(i.next());
1569      *  }
1570      * </pre>
1571      * Failure to follow this advice may result in non-deterministic behavior.
1572      *
1573      * <p>The returned collection does <i>not</i> pass the <tt>hashCode</tt>
1574      * and <tt>equals</tt> operations through to the backing collection, but
1575      * relies on <tt>Object</tt>'s equals and hashCode methods.  This is
1576      * necessary to preserve the contracts of these operations in the case
1577      * that the backing collection is a set or a list.<p>
1578      *
1579      * The returned collection will be serializable if the specified collection
1580      * is serializable.
1581      *
1582      * @param  c the collection to be "wrapped" in a synchronized collection.
1583      * @return a synchronized view of the specified collection.
1584      */
1585     public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
1586         return new SynchronizedCollection<>(c);
1587     }
1588 
1589     static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
1590         return new SynchronizedCollection<>(c, mutex);
1591     }
1592 
1593     /**
1594      * @serial include
1595      */
1596     static class SynchronizedCollection<E> implements Collection<E>, Serializable {
1597         private static final long serialVersionUID = 3053995032091335093L;
1598 
1599         final Collection<E> c;  // Backing Collection
1600         final Object mutex;     // Object on which to synchronize
1601 
1602         SynchronizedCollection(Collection<E> c) {
1603             if (c==null)
1604                 throw new NullPointerException();
1605             this.c = c;
1606             mutex = this;
1607         }
1608         SynchronizedCollection(Collection<E> c, Object mutex) {
1609             this.c = c;
1610             this.mutex = mutex;


1669      * It is imperative that the user manually synchronize on the returned
1670      * set when iterating over it:
1671      * <pre>
1672      *  Set s = Collections.synchronizedSet(new HashSet());
1673      *      ...
1674      *  synchronized (s) {
1675      *      Iterator i = s.iterator(); // Must be in the synchronized block
1676      *      while (i.hasNext())
1677      *          foo(i.next());
1678      *  }
1679      * </pre>
1680      * Failure to follow this advice may result in non-deterministic behavior.
1681      *
1682      * <p>The returned set will be serializable if the specified set is
1683      * serializable.
1684      *
1685      * @param  s the set to be "wrapped" in a synchronized set.
1686      * @return a synchronized view of the specified set.
1687      */
1688     public static <T> Set<T> synchronizedSet(Set<T> s) {
1689         return new SynchronizedSet<>(s);
1690     }
1691 
1692     static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
1693         return new SynchronizedSet<>(s, mutex);
1694     }
1695 
1696     /**
1697      * @serial include
1698      */
1699     static class SynchronizedSet<E>
1700           extends SynchronizedCollection<E>
1701           implements Set<E> {
1702         private static final long serialVersionUID = 487447009682186044L;
1703 
1704         SynchronizedSet(Set<E> s) {
1705             super(s);
1706         }
1707         SynchronizedSet(Set<E> s, Object mutex) {
1708             super(s, mutex);
1709         }
1710 
1711         public boolean equals(Object o) {
1712             synchronized (mutex) {return c.equals(o);}
1713         }


1737      * or:
1738      * <pre>
1739      *  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
1740      *  SortedSet s2 = s.headSet(foo);
1741      *      ...
1742      *  synchronized (s) {  // Note: s, not s2!!!
1743      *      Iterator i = s2.iterator(); // Must be in the synchronized block
1744      *      while (i.hasNext())
1745      *          foo(i.next());
1746      *  }
1747      * </pre>
1748      * Failure to follow this advice may result in non-deterministic behavior.
1749      *
1750      * <p>The returned sorted set will be serializable if the specified
1751      * sorted set is serializable.
1752      *
1753      * @param  s the sorted set to be "wrapped" in a synchronized sorted set.
1754      * @return a synchronized view of the specified sorted set.
1755      */
1756     public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
1757         return new SynchronizedSortedSet<>(s);
1758     }
1759 
1760     /**
1761      * @serial include
1762      */
1763     static class SynchronizedSortedSet<E>
1764         extends SynchronizedSet<E>
1765         implements SortedSet<E>
1766     {
1767         private static final long serialVersionUID = 8695801310862127406L;
1768 
1769         private final SortedSet<E> ss;
1770 
1771         SynchronizedSortedSet(SortedSet<E> s) {
1772             super(s);
1773             ss = s;
1774         }
1775         SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
1776             super(s, mutex);
1777             ss = s;
1778         }
1779 
1780         public Comparator<? super E> comparator() {
1781             synchronized (mutex) {return ss.comparator();}
1782         }
1783 
1784         public SortedSet<E> subSet(E fromElement, E toElement) {
1785             synchronized (mutex) {
1786                 return new SynchronizedSortedSet<>(
1787                     ss.subSet(fromElement, toElement), mutex);
1788             }
1789         }
1790         public SortedSet<E> headSet(E toElement) {
1791             synchronized (mutex) {
1792                 return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);
1793             }
1794         }
1795         public SortedSet<E> tailSet(E fromElement) {
1796             synchronized (mutex) {
1797                return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);
1798             }
1799         }
1800 
1801         public E first() {
1802             synchronized (mutex) {return ss.first();}
1803         }
1804         public E last() {
1805             synchronized (mutex) {return ss.last();}
1806         }
1807     }
1808 
1809     /**
1810      * Returns a synchronized (thread-safe) list backed by the specified
1811      * list.  In order to guarantee serial access, it is critical that
1812      * <strong>all</strong> access to the backing list is accomplished
1813      * through the returned list.<p>
1814      *
1815      * It is imperative that the user manually synchronize on the returned
1816      * list when iterating over it:
1817      * <pre>
1818      *  List list = Collections.synchronizedList(new ArrayList());
1819      *      ...
1820      *  synchronized (list) {
1821      *      Iterator i = list.iterator(); // Must be in synchronized block
1822      *      while (i.hasNext())
1823      *          foo(i.next());
1824      *  }
1825      * </pre>
1826      * Failure to follow this advice may result in non-deterministic behavior.
1827      *
1828      * <p>The returned list will be serializable if the specified list is
1829      * serializable.
1830      *
1831      * @param  list the list to be "wrapped" in a synchronized list.
1832      * @return a synchronized view of the specified list.
1833      */
1834     public static <T> List<T> synchronizedList(List<T> list) {
1835         return (list instanceof RandomAccess ?
1836                 new SynchronizedRandomAccessList<>(list) :
1837                 new SynchronizedList<>(list));
1838     }
1839 
1840     static <T> List<T> synchronizedList(List<T> list, Object mutex) {
1841         return (list instanceof RandomAccess ?
1842                 new SynchronizedRandomAccessList<>(list, mutex) :
1843                 new SynchronizedList<>(list, mutex));
1844     }
1845 
1846     /**
1847      * @serial include
1848      */
1849     static class SynchronizedList<E>
1850         extends SynchronizedCollection<E>
1851         implements List<E> {
1852         private static final long serialVersionUID = -7754090372962971524L;
1853 
1854         final List<E> list;
1855 
1856         SynchronizedList(List<E> list) {
1857             super(list);
1858             this.list = list;
1859         }
1860         SynchronizedList(List<E> list, Object mutex) {
1861             super(list, mutex);
1862             this.list = list;
1863         }


1886             synchronized (mutex) {return list.indexOf(o);}
1887         }
1888         public int lastIndexOf(Object o) {
1889             synchronized (mutex) {return list.lastIndexOf(o);}
1890         }
1891 
1892         public boolean addAll(int index, Collection<? extends E> c) {
1893             synchronized (mutex) {return list.addAll(index, c);}
1894         }
1895 
1896         public ListIterator<E> listIterator() {
1897             return list.listIterator(); // Must be manually synched by user
1898         }
1899 
1900         public ListIterator<E> listIterator(int index) {
1901             return list.listIterator(index); // Must be manually synched by user
1902         }
1903 
1904         public List<E> subList(int fromIndex, int toIndex) {
1905             synchronized (mutex) {
1906                 return new SynchronizedList<>(list.subList(fromIndex, toIndex),
1907                                             mutex);
1908             }
1909         }
1910 
1911         /**
1912          * SynchronizedRandomAccessList instances are serialized as
1913          * SynchronizedList instances to allow them to be deserialized
1914          * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).
1915          * This method inverts the transformation.  As a beneficial
1916          * side-effect, it also grafts the RandomAccess marker onto
1917          * SynchronizedList instances that were serialized in pre-1.4 JREs.
1918          *
1919          * Note: Unfortunately, SynchronizedRandomAccessList instances
1920          * serialized in 1.4.1 and deserialized in 1.4 will become
1921          * SynchronizedList instances, as this method was missing in 1.4.
1922          */
1923         private Object readResolve() {
1924             return (list instanceof RandomAccess
1925                     ? new SynchronizedRandomAccessList<>(list)
1926                     : this);
1927         }
1928     }
1929 
1930     /**
1931      * @serial include
1932      */
1933     static class SynchronizedRandomAccessList<E>
1934         extends SynchronizedList<E>
1935         implements RandomAccess {
1936 
1937         SynchronizedRandomAccessList(List<E> list) {
1938             super(list);
1939         }
1940 
1941         SynchronizedRandomAccessList(List<E> list, Object mutex) {
1942             super(list, mutex);
1943         }
1944 
1945         public List<E> subList(int fromIndex, int toIndex) {
1946             synchronized (mutex) {
1947                 return new SynchronizedRandomAccessList<>(
1948                     list.subList(fromIndex, toIndex), mutex);
1949             }
1950         }
1951 
1952         private static final long serialVersionUID = 1530674583602358482L;
1953 
1954         /**
1955          * Allows instances to be deserialized in pre-1.4 JREs (which do
1956          * not have SynchronizedRandomAccessList).  SynchronizedList has
1957          * a readResolve method that inverts this transformation upon
1958          * deserialization.
1959          */
1960         private Object writeReplace() {
1961             return new SynchronizedList<>(list);
1962         }
1963     }
1964 
1965     /**
1966      * Returns a synchronized (thread-safe) map backed by the specified
1967      * map.  In order to guarantee serial access, it is critical that
1968      * <strong>all</strong> access to the backing map is accomplished
1969      * through the returned map.<p>
1970      *
1971      * It is imperative that the user manually synchronize on the returned
1972      * map when iterating over any of its collection views:
1973      * <pre>
1974      *  Map m = Collections.synchronizedMap(new HashMap());
1975      *      ...
1976      *  Set s = m.keySet();  // Needn't be in synchronized block
1977      *      ...
1978      *  synchronized (m) {  // Synchronizing on m, not s!
1979      *      Iterator i = s.iterator(); // Must be in synchronized block
1980      *      while (i.hasNext())
1981      *          foo(i.next());
1982      *  }
1983      * </pre>
1984      * Failure to follow this advice may result in non-deterministic behavior.
1985      *
1986      * <p>The returned map will be serializable if the specified map is
1987      * serializable.
1988      *
1989      * @param  m the map to be "wrapped" in a synchronized map.
1990      * @return a synchronized view of the specified map.
1991      */
1992     public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
1993         return new SynchronizedMap<>(m);
1994     }
1995 
1996     /**
1997      * @serial include
1998      */
1999     private static class SynchronizedMap<K,V>
2000         implements Map<K,V>, Serializable {
2001         private static final long serialVersionUID = 1978198479659022715L;
2002 
2003         private final Map<K,V> m;     // Backing Map
2004         final Object      mutex;        // Object on which to synchronize
2005 
2006         SynchronizedMap(Map<K,V> m) {
2007             if (m==null)
2008                 throw new NullPointerException();
2009             this.m = m;
2010             mutex = this;
2011         }
2012 
2013         SynchronizedMap(Map<K,V> m, Object mutex) {


2034         public V put(K key, V value) {
2035             synchronized (mutex) {return m.put(key, value);}
2036         }
2037         public V remove(Object key) {
2038             synchronized (mutex) {return m.remove(key);}
2039         }
2040         public void putAll(Map<? extends K, ? extends V> map) {
2041             synchronized (mutex) {m.putAll(map);}
2042         }
2043         public void clear() {
2044             synchronized (mutex) {m.clear();}
2045         }
2046 
2047         private transient Set<K> keySet = null;
2048         private transient Set<Map.Entry<K,V>> entrySet = null;
2049         private transient Collection<V> values = null;
2050 
2051         public Set<K> keySet() {
2052             synchronized (mutex) {
2053                 if (keySet==null)
2054                     keySet = new SynchronizedSet<>(m.keySet(), mutex);
2055                 return keySet;
2056             }
2057         }
2058 
2059         public Set<Map.Entry<K,V>> entrySet() {
2060             synchronized (mutex) {
2061                 if (entrySet==null)
2062                     entrySet = new SynchronizedSet<>(m.entrySet(), mutex);
2063                 return entrySet;
2064             }
2065         }
2066 
2067         public Collection<V> values() {
2068             synchronized (mutex) {
2069                 if (values==null)
2070                     values = new SynchronizedCollection<>(m.values(), mutex);
2071                 return values;
2072             }
2073         }
2074 
2075         public boolean equals(Object o) {
2076             synchronized (mutex) {return m.equals(o);}
2077         }
2078         public int hashCode() {
2079             synchronized (mutex) {return m.hashCode();}
2080         }
2081         public String toString() {
2082             synchronized (mutex) {return m.toString();}
2083         }
2084         private void writeObject(ObjectOutputStream s) throws IOException {
2085             synchronized (mutex) {s.defaultWriteObject();}
2086         }
2087     }
2088 
2089     /**
2090      * Returns a synchronized (thread-safe) sorted map backed by the specified


2112      *  SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2113      *  SortedMap m2 = m.subMap(foo, bar);
2114      *      ...
2115      *  Set s2 = m2.keySet();  // Needn't be in synchronized block
2116      *      ...
2117      *  synchronized (m) {  // Synchronizing on m, not m2 or s2!
2118      *      Iterator i = s.iterator(); // Must be in synchronized block
2119      *      while (i.hasNext())
2120      *          foo(i.next());
2121      *  }
2122      * </pre>
2123      * Failure to follow this advice may result in non-deterministic behavior.
2124      *
2125      * <p>The returned sorted map will be serializable if the specified
2126      * sorted map is serializable.
2127      *
2128      * @param  m the sorted map to be "wrapped" in a synchronized sorted map.
2129      * @return a synchronized view of the specified sorted map.
2130      */
2131     public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
2132         return new SynchronizedSortedMap<>(m);
2133     }
2134 
2135 
2136     /**
2137      * @serial include
2138      */
2139     static class SynchronizedSortedMap<K,V>
2140         extends SynchronizedMap<K,V>
2141         implements SortedMap<K,V>
2142     {
2143         private static final long serialVersionUID = -8798146769416483793L;
2144 
2145         private final SortedMap<K,V> sm;
2146 
2147         SynchronizedSortedMap(SortedMap<K,V> m) {
2148             super(m);
2149             sm = m;
2150         }
2151         SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {
2152             super(m, mutex);
2153             sm = m;
2154         }
2155 
2156         public Comparator<? super K> comparator() {
2157             synchronized (mutex) {return sm.comparator();}
2158         }
2159 
2160         public SortedMap<K,V> subMap(K fromKey, K toKey) {
2161             synchronized (mutex) {
2162                 return new SynchronizedSortedMap<>(
2163                     sm.subMap(fromKey, toKey), mutex);
2164             }
2165         }
2166         public SortedMap<K,V> headMap(K toKey) {
2167             synchronized (mutex) {
2168                 return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);
2169             }
2170         }
2171         public SortedMap<K,V> tailMap(K fromKey) {
2172             synchronized (mutex) {
2173                return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);
2174             }
2175         }
2176 
2177         public K firstKey() {
2178             synchronized (mutex) {return sm.firstKey();}
2179         }
2180         public K lastKey() {
2181             synchronized (mutex) {return sm.lastKey();}
2182         }
2183     }
2184 
2185     // Dynamically typesafe collection wrappers
2186 
2187     /**
2188      * Returns a dynamically typesafe view of the specified collection.
2189      * Any attempt to insert an element of the wrong type will result in an
2190      * immediate {@link ClassCastException}.  Assuming a collection
2191      * contains no incorrectly typed elements prior to the time a
2192      * dynamically typesafe view is generated, and that all subsequent
2193      * access to the collection takes place through the view, it is


2229      * operations through to the backing collection, but relies on
2230      * {@code Object}'s {@code equals} and {@code hashCode} methods.  This
2231      * is necessary to preserve the contracts of these operations in the case
2232      * that the backing collection is a set or a list.
2233      *
2234      * <p>The returned collection will be serializable if the specified
2235      * collection is serializable.
2236      *
2237      * <p>Since {@code null} is considered to be a value of any reference
2238      * type, the returned collection permits insertion of null elements
2239      * whenever the backing collection does.
2240      *
2241      * @param c the collection for which a dynamically typesafe view is to be
2242      *          returned
2243      * @param type the type of element that {@code c} is permitted to hold
2244      * @return a dynamically typesafe view of the specified collection
2245      * @since 1.5
2246      */
2247     public static <E> Collection<E> checkedCollection(Collection<E> c,
2248                                                       Class<E> type) {
2249         return new CheckedCollection<>(c, type);
2250     }
2251 
2252     @SuppressWarnings("unchecked")
2253     static <T> T[] zeroLengthArray(Class<T> type) {
2254         return (T[]) Array.newInstance(type, 0);
2255     }
2256 
2257     /**
2258      * @serial include
2259      */
2260     static class CheckedCollection<E> implements Collection<E>, Serializable {
2261         private static final long serialVersionUID = 1578914078182001775L;
2262 
2263         final Collection<E> c;
2264         final Class<E> type;
2265 
2266         void typeCheck(Object o) {
2267             if (o != null && !type.isInstance(o))
2268                 throw new ClassCastException(badElementMsg(o));
2269         }


2361      * set cannot contain an incorrectly typed element.
2362      *
2363      * <p>A discussion of the use of dynamically typesafe views may be
2364      * found in the documentation for the {@link #checkedCollection
2365      * checkedCollection} method.
2366      *
2367      * <p>The returned set will be serializable if the specified set is
2368      * serializable.
2369      *
2370      * <p>Since {@code null} is considered to be a value of any reference
2371      * type, the returned set permits insertion of null elements whenever
2372      * the backing set does.
2373      *
2374      * @param s the set for which a dynamically typesafe view is to be
2375      *          returned
2376      * @param type the type of element that {@code s} is permitted to hold
2377      * @return a dynamically typesafe view of the specified set
2378      * @since 1.5
2379      */
2380     public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
2381         return new CheckedSet<>(s, type);
2382     }
2383 
2384     /**
2385      * @serial include
2386      */
2387     static class CheckedSet<E> extends CheckedCollection<E>
2388                                  implements Set<E>, Serializable
2389     {
2390         private static final long serialVersionUID = 4694047833775013803L;
2391 
2392         CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
2393 
2394         public boolean equals(Object o) { return o == this || c.equals(o); }
2395         public int hashCode()           { return c.hashCode(); }
2396     }
2397 
2398     /**
2399      * Returns a dynamically typesafe view of the specified sorted set.
2400      * Any attempt to insert an element of the wrong type will result in an
2401      * immediate {@link ClassCastException}.  Assuming a sorted set


2407      *
2408      * <p>A discussion of the use of dynamically typesafe views may be
2409      * found in the documentation for the {@link #checkedCollection
2410      * checkedCollection} method.
2411      *
2412      * <p>The returned sorted set will be serializable if the specified sorted
2413      * set is serializable.
2414      *
2415      * <p>Since {@code null} is considered to be a value of any reference
2416      * type, the returned sorted set permits insertion of null elements
2417      * whenever the backing sorted set does.
2418      *
2419      * @param s the sorted set for which a dynamically typesafe view is to be
2420      *          returned
2421      * @param type the type of element that {@code s} is permitted to hold
2422      * @return a dynamically typesafe view of the specified sorted set
2423      * @since 1.5
2424      */
2425     public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
2426                                                     Class<E> type) {
2427         return new CheckedSortedSet<>(s, type);
2428     }
2429 
2430     /**
2431      * @serial include
2432      */
2433     static class CheckedSortedSet<E> extends CheckedSet<E>
2434         implements SortedSet<E>, Serializable
2435     {
2436         private static final long serialVersionUID = 1599911165492914959L;
2437         private final SortedSet<E> ss;
2438 
2439         CheckedSortedSet(SortedSet<E> s, Class<E> type) {
2440             super(s, type);
2441             ss = s;
2442         }
2443 
2444         public Comparator<? super E> comparator() { return ss.comparator(); }
2445         public E first()                   { return ss.first(); }
2446         public E last()                    { return ss.last(); }
2447 


2467      *
2468      * <p>A discussion of the use of dynamically typesafe views may be
2469      * found in the documentation for the {@link #checkedCollection
2470      * checkedCollection} method.
2471      *
2472      * <p>The returned list will be serializable if the specified list
2473      * is serializable.
2474      *
2475      * <p>Since {@code null} is considered to be a value of any reference
2476      * type, the returned list permits insertion of null elements whenever
2477      * the backing list does.
2478      *
2479      * @param list the list for which a dynamically typesafe view is to be
2480      *             returned
2481      * @param type the type of element that {@code list} is permitted to hold
2482      * @return a dynamically typesafe view of the specified list
2483      * @since 1.5
2484      */
2485     public static <E> List<E> checkedList(List<E> list, Class<E> type) {
2486         return (list instanceof RandomAccess ?
2487                 new CheckedRandomAccessList<>(list, type) :
2488                 new CheckedList<>(list, type));
2489     }
2490 
2491     /**
2492      * @serial include
2493      */
2494     static class CheckedList<E>
2495         extends CheckedCollection<E>
2496         implements List<E>
2497     {
2498         private static final long serialVersionUID = 65247728283967356L;
2499         final List<E> list;
2500 
2501         CheckedList(List<E> list, Class<E> type) {
2502             super(list, type);
2503             this.list = list;
2504         }
2505 
2506         public boolean equals(Object o)  { return o == this || list.equals(o); }
2507         public int hashCode()            { return list.hashCode(); }
2508         public E get(int index)          { return list.get(index); }


2533                 public E next()              { return i.next(); }
2534                 public boolean hasPrevious() { return i.hasPrevious(); }
2535                 public E previous()          { return i.previous(); }
2536                 public int nextIndex()       { return i.nextIndex(); }
2537                 public int previousIndex()   { return i.previousIndex(); }
2538                 public void remove()         {        i.remove(); }
2539 
2540                 public void set(E e) {
2541                     typeCheck(e);
2542                     i.set(e);
2543                 }
2544 
2545                 public void add(E e) {
2546                     typeCheck(e);
2547                     i.add(e);
2548                 }
2549             };
2550         }
2551 
2552         public List<E> subList(int fromIndex, int toIndex) {
2553             return new CheckedList<>(list.subList(fromIndex, toIndex), type);
2554         }
2555     }
2556 
2557     /**
2558      * @serial include
2559      */
2560     static class CheckedRandomAccessList<E> extends CheckedList<E>
2561                                             implements RandomAccess
2562     {
2563         private static final long serialVersionUID = 1638200125423088369L;
2564 
2565         CheckedRandomAccessList(List<E> list, Class<E> type) {
2566             super(list, type);
2567         }
2568 
2569         public List<E> subList(int fromIndex, int toIndex) {
2570             return new CheckedRandomAccessList<>(
2571                 list.subList(fromIndex, toIndex), type);
2572         }
2573     }
2574 
2575     /**
2576      * Returns a dynamically typesafe view of the specified map.
2577      * Any attempt to insert a mapping whose key or value have the wrong
2578      * type will result in an immediate {@link ClassCastException}.
2579      * Similarly, any attempt to modify the value currently associated with
2580      * a key will result in an immediate {@link ClassCastException},
2581      * whether the modification is attempted directly through the map
2582      * itself, or through a {@link Map.Entry} instance obtained from the
2583      * map's {@link Map#entrySet() entry set} view.
2584      *
2585      * <p>Assuming a map contains no incorrectly typed keys or values
2586      * prior to the time a dynamically typesafe view is generated, and
2587      * that all subsequent access to the map takes place through the view
2588      * (or one of its collection views), it is <i>guaranteed</i> that the
2589      * map cannot contain an incorrectly typed key or value.
2590      *


2592      * found in the documentation for the {@link #checkedCollection
2593      * checkedCollection} method.
2594      *
2595      * <p>The returned map will be serializable if the specified map is
2596      * serializable.
2597      *
2598      * <p>Since {@code null} is considered to be a value of any reference
2599      * type, the returned map permits insertion of null keys or values
2600      * whenever the backing map does.
2601      *
2602      * @param m the map for which a dynamically typesafe view is to be
2603      *          returned
2604      * @param keyType the type of key that {@code m} is permitted to hold
2605      * @param valueType the type of value that {@code m} is permitted to hold
2606      * @return a dynamically typesafe view of the specified map
2607      * @since 1.5
2608      */
2609     public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
2610                                               Class<K> keyType,
2611                                               Class<V> valueType) {
2612         return new CheckedMap<>(m, keyType, valueType);
2613     }
2614 
2615 
2616     /**
2617      * @serial include
2618      */
2619     private static class CheckedMap<K,V>
2620         implements Map<K,V>, Serializable
2621     {
2622         private static final long serialVersionUID = 5742860141034234728L;
2623 
2624         private final Map<K, V> m;
2625         final Class<K> keyType;
2626         final Class<V> valueType;
2627 
2628         private void typeCheck(Object key, Object value) {
2629             if (key != null && !keyType.isInstance(key))
2630                 throw new ClassCastException(badKeyMsg(key));
2631 
2632             if (value != null && !valueType.isInstance(value))


2661         public Set<K> keySet()                 { return m.keySet(); }
2662         public Collection<V> values()          { return m.values(); }
2663         public boolean equals(Object o)        { return o == this || m.equals(o); }
2664         public int hashCode()                  { return m.hashCode(); }
2665         public String toString()               { return m.toString(); }
2666 
2667         public V put(K key, V value) {
2668             typeCheck(key, value);
2669             return m.put(key, value);
2670         }
2671 
2672         @SuppressWarnings("unchecked")
2673         public void putAll(Map<? extends K, ? extends V> t) {
2674             // Satisfy the following goals:
2675             // - good diagnostics in case of type mismatch
2676             // - all-or-nothing semantics
2677             // - protection from malicious t
2678             // - correct behavior if t is a concurrent map
2679             Object[] entries = t.entrySet().toArray();
2680             List<Map.Entry<K,V>> checked =
2681                 new ArrayList<>(entries.length);
2682             for (Object o : entries) {
2683                 Map.Entry<?,?> e = (Map.Entry<?,?>) o;
2684                 Object k = e.getKey();
2685                 Object v = e.getValue();
2686                 typeCheck(k, v);
2687                 checked.add(
2688                     new AbstractMap.SimpleImmutableEntry<>((K) k, (V) v));
2689             }
2690             for (Map.Entry<K,V> e : checked)
2691                 m.put(e.getKey(), e.getValue());
2692         }
2693 
2694         private transient Set<Map.Entry<K,V>> entrySet = null;
2695 
2696         public Set<Map.Entry<K,V>> entrySet() {
2697             if (entrySet==null)
2698                 entrySet = new CheckedEntrySet<>(m.entrySet(), valueType);
2699             return entrySet;
2700         }
2701 
2702         /**
2703          * We need this class in addition to CheckedSet as Map.Entry permits
2704          * modification of the backing Map via the setValue operation.  This
2705          * class is subtle: there are many possible attacks that must be
2706          * thwarted.
2707          *
2708          * @serial exclude
2709          */
2710         static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {
2711             private final Set<Map.Entry<K,V>> s;
2712             private final Class<V> valueType;
2713 
2714             CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {
2715                 this.s = s;
2716                 this.valueType = valueType;
2717             }
2718 


2793                 return s.contains(
2794                     (e instanceof CheckedEntry) ? e : checkedEntry(e, valueType));
2795             }
2796 
2797             /**
2798              * The bulk collection methods are overridden to protect
2799              * against an unscrupulous collection whose contains(Object o)
2800              * method senses when o is a Map.Entry, and calls o.setValue.
2801              */
2802             public boolean containsAll(Collection<?> c) {
2803                 for (Object o : c)
2804                     if (!contains(o)) // Invokes safe contains() above
2805                         return false;
2806                 return true;
2807             }
2808 
2809             public boolean remove(Object o) {
2810                 if (!(o instanceof Map.Entry))
2811                     return false;
2812                 return s.remove(new AbstractMap.SimpleImmutableEntry
2813                                 <>((Map.Entry<?,?>)o));
2814             }
2815 
2816             public boolean removeAll(Collection<?> c) {
2817                 return batchRemove(c, false);
2818             }
2819             public boolean retainAll(Collection<?> c) {
2820                 return batchRemove(c, true);
2821             }
2822             private boolean batchRemove(Collection<?> c, boolean complement) {
2823                 boolean modified = false;
2824                 Iterator<Map.Entry<K,V>> it = iterator();
2825                 while (it.hasNext()) {
2826                     if (c.contains(it.next()) != complement) {
2827                         it.remove();
2828                         modified = true;
2829                     }
2830                 }
2831                 return modified;
2832             }
2833 
2834             public boolean equals(Object o) {
2835                 if (o == this)
2836                     return true;
2837                 if (!(o instanceof Set))
2838                     return false;
2839                 Set<?> that = (Set<?>) o;
2840                 return that.size() == s.size()
2841                     && containsAll(that); // Invokes safe containsAll() above
2842             }
2843 
2844             static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,
2845                                                             Class<T> valueType) {
2846                 return new CheckedEntry<>(e, valueType);
2847             }
2848 
2849             /**
2850              * This "wrapper class" serves two purposes: it prevents
2851              * the client from modifying the backing Map, by short-circuiting
2852              * the setValue method, and it protects the backing Map against
2853              * an ill-behaved Map.Entry that attempts to modify another
2854              * Map.Entry when asked to perform an equality check.
2855              */
2856             private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {
2857                 private final Map.Entry<K, V> e;
2858                 private final Class<T> valueType;
2859 
2860                 CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {
2861                     this.e = e;
2862                     this.valueType = valueType;
2863                 }
2864 
2865                 public K getKey()        { return e.getKey(); }
2866                 public V getValue()      { return e.getValue(); }
2867                 public int hashCode()    { return e.hashCode(); }
2868                 public String toString() { return e.toString(); }
2869 
2870                 public V setValue(V value) {
2871                     if (value != null && !valueType.isInstance(value))
2872                         throw new ClassCastException(badValueMsg(value));
2873                     return e.setValue(value);
2874                 }
2875 
2876                 private String badValueMsg(Object value) {
2877                     return "Attempt to insert " + value.getClass() +
2878                         " value into map with value type " + valueType;
2879                 }
2880 
2881                 public boolean equals(Object o) {
2882                     if (o == this)
2883                         return true;
2884                     if (!(o instanceof Map.Entry))
2885                         return false;
2886                     return e.equals(new AbstractMap.SimpleImmutableEntry
2887                                     <>((Map.Entry<?,?>)o));
2888                 }
2889             }
2890         }
2891     }
2892 
2893     /**
2894      * Returns a dynamically typesafe view of the specified sorted map.
2895      * Any attempt to insert a mapping whose key or value have the wrong
2896      * type will result in an immediate {@link ClassCastException}.
2897      * Similarly, any attempt to modify the value currently associated with
2898      * a key will result in an immediate {@link ClassCastException},
2899      * whether the modification is attempted directly through the map
2900      * itself, or through a {@link Map.Entry} instance obtained from the
2901      * map's {@link Map#entrySet() entry set} view.
2902      *
2903      * <p>Assuming a map contains no incorrectly typed keys or values
2904      * prior to the time a dynamically typesafe view is generated, and
2905      * that all subsequent access to the map takes place through the view
2906      * (or one of its collection views), it is <i>guaranteed</i> that the
2907      * map cannot contain an incorrectly typed key or value.


2910      * found in the documentation for the {@link #checkedCollection
2911      * checkedCollection} method.
2912      *
2913      * <p>The returned map will be serializable if the specified map is
2914      * serializable.
2915      *
2916      * <p>Since {@code null} is considered to be a value of any reference
2917      * type, the returned map permits insertion of null keys or values
2918      * whenever the backing map does.
2919      *
2920      * @param m the map for which a dynamically typesafe view is to be
2921      *          returned
2922      * @param keyType the type of key that {@code m} is permitted to hold
2923      * @param valueType the type of value that {@code m} is permitted to hold
2924      * @return a dynamically typesafe view of the specified map
2925      * @since 1.5
2926      */
2927     public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
2928                                                         Class<K> keyType,
2929                                                         Class<V> valueType) {
2930         return new CheckedSortedMap<>(m, keyType, valueType);
2931     }
2932 
2933     /**
2934      * @serial include
2935      */
2936     static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
2937         implements SortedMap<K,V>, Serializable
2938     {
2939         private static final long serialVersionUID = 1599671320688067438L;
2940 
2941         private final SortedMap<K, V> sm;
2942 
2943         CheckedSortedMap(SortedMap<K, V> m,
2944                          Class<K> keyType, Class<V> valueType) {
2945             super(m, keyType, valueType);
2946             sm = m;
2947         }
2948 
2949         public Comparator<? super K> comparator() { return sm.comparator(); }
2950         public K firstKey()                       { return sm.firstKey(); }


2976      * NoSuchElementException}.
2977      *
2978      * <li>{@link Iterator#remove remove} always throws {@link
2979      * IllegalStateException}.
2980      *
2981      * </ul>
2982      *
2983      * <p>Implementations of this method are permitted, but not
2984      * required, to return the same object from multiple invocations.
2985      *
2986      * @return an empty iterator
2987      * @since 1.7
2988      */
2989     @SuppressWarnings("unchecked")
2990     public static <T> Iterator<T> emptyIterator() {
2991         return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;
2992     }
2993 
2994     private static class EmptyIterator<E> implements Iterator<E> {
2995         static final EmptyIterator<Object> EMPTY_ITERATOR
2996             = new EmptyIterator<>();
2997 
2998         public boolean hasNext() { return false; }
2999         public E next() { throw new NoSuchElementException(); }
3000         public void remove() { throw new IllegalStateException(); }
3001     }
3002 
3003     /**
3004      * Returns a list iterator that has no elements.  More precisely,
3005      *
3006      * <ul compact>
3007      *
3008      * <li>{@link Iterator#hasNext hasNext} and {@link
3009      * ListIterator#hasPrevious hasPrevious} always return {@code
3010      * false}.
3011      *
3012      * <li>{@link Iterator#next next} and {@link ListIterator#previous
3013      * previous} always throw {@link NoSuchElementException}.
3014      *
3015      * <li>{@link Iterator#remove remove} and {@link ListIterator#set
3016      * set} always throw {@link IllegalStateException}.


3025      * returns {@code -1}.
3026      *
3027      * </ul>
3028      *
3029      * <p>Implementations of this method are permitted, but not
3030      * required, to return the same object from multiple invocations.
3031      *
3032      * @return an empty list iterator
3033      * @since 1.7
3034      */
3035     @SuppressWarnings("unchecked")
3036     public static <T> ListIterator<T> emptyListIterator() {
3037         return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR;
3038     }
3039 
3040     private static class EmptyListIterator<E>
3041         extends EmptyIterator<E>
3042         implements ListIterator<E>
3043     {
3044         static final EmptyListIterator<Object> EMPTY_ITERATOR
3045             = new EmptyListIterator<>();
3046 
3047         public boolean hasPrevious() { return false; }
3048         public E previous() { throw new NoSuchElementException(); }
3049         public int nextIndex()     { return 0; }
3050         public int previousIndex() { return -1; }
3051         public void set(E e) { throw new IllegalStateException(); }
3052         public void add(E e) { throw new UnsupportedOperationException(); }
3053     }
3054 
3055     /**
3056      * Returns an enumeration that has no elements.  More precisely,
3057      *
3058      * <ul compact>
3059      *
3060      * <li>{@link Enumeration#hasMoreElements hasMoreElements} always
3061      * returns {@code false}.
3062      *
3063      * <li> {@link Enumeration#nextElement nextElement} always throws
3064      * {@link NoSuchElementException}.
3065      *
3066      * </ul>
3067      *
3068      * <p>Implementations of this method are permitted, but not
3069      * required, to return the same object from multiple invocations.
3070      *
3071      * @return an empty enumeration
3072      * @since 1.7
3073      */
3074     @SuppressWarnings("unchecked")
3075     public static <T> Enumeration<T> emptyEnumeration() {
3076         return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;
3077     }
3078 
3079     private static class EmptyEnumeration<E> implements Enumeration<E> {
3080         static final EmptyEnumeration<Object> EMPTY_ENUMERATION
3081             = new EmptyEnumeration<>();
3082 
3083         public boolean hasMoreElements() { return false; }
3084         public E nextElement() { throw new NoSuchElementException(); }
3085     }
3086 
3087     /**
3088      * The empty set (immutable).  This set is serializable.
3089      *
3090      * @see #emptySet()
3091      */
3092     @SuppressWarnings("unchecked")
3093     public static final Set EMPTY_SET = new EmptySet<>();
3094 
3095     /**
3096      * Returns the empty set (immutable).  This set is serializable.
3097      * Unlike the like-named field, this method is parameterized.
3098      *
3099      * <p>This example illustrates the type-safe way to obtain an empty set:
3100      * <pre>
3101      *     Set&lt;String&gt; s = Collections.emptySet();
3102      * </pre>
3103      * Implementation note:  Implementations of this method need not
3104      * create a separate <tt>Set</tt> object for each call.   Using this
3105      * method is likely to have comparable cost to using the like-named
3106      * field.  (Unlike this method, the field does not provide type safety.)
3107      *
3108      * @see #EMPTY_SET
3109      * @since 1.5
3110      */
3111     @SuppressWarnings("unchecked")
3112     public static final <T> Set<T> emptySet() {
3113         return (Set<T>) EMPTY_SET;


3133         public Object[] toArray() { return new Object[0]; }
3134 
3135         public <T> T[] toArray(T[] a) {
3136             if (a.length > 0)
3137                 a[0] = null;
3138             return a;
3139         }
3140 
3141         // Preserves singleton property
3142         private Object readResolve() {
3143             return EMPTY_SET;
3144         }
3145     }
3146 
3147     /**
3148      * The empty list (immutable).  This list is serializable.
3149      *
3150      * @see #emptyList()
3151      */
3152     @SuppressWarnings("unchecked")
3153     public static final List EMPTY_LIST = new EmptyList<>();
3154 
3155     /**
3156      * Returns the empty list (immutable).  This list is serializable.
3157      *
3158      * <p>This example illustrates the type-safe way to obtain an empty list:
3159      * <pre>
3160      *     List&lt;String&gt; s = Collections.emptyList();
3161      * </pre>
3162      * Implementation note:  Implementations of this method need not
3163      * create a separate <tt>List</tt> object for each call.   Using this
3164      * method is likely to have comparable cost to using the like-named
3165      * field.  (Unlike this method, the field does not provide type safety.)
3166      *
3167      * @see #EMPTY_LIST
3168      * @since 1.5
3169      */
3170     @SuppressWarnings("unchecked")
3171     public static final <T> List<T> emptyList() {
3172         return (List<T>) EMPTY_LIST;
3173     }


3207 
3208         public boolean equals(Object o) {
3209             return (o instanceof List) && ((List<?>)o).isEmpty();
3210         }
3211 
3212         public int hashCode() { return 1; }
3213 
3214         // Preserves singleton property
3215         private Object readResolve() {
3216             return EMPTY_LIST;
3217         }
3218     }
3219 
3220     /**
3221      * The empty map (immutable).  This map is serializable.
3222      *
3223      * @see #emptyMap()
3224      * @since 1.3
3225      */
3226     @SuppressWarnings("unchecked")
3227     public static final Map EMPTY_MAP = new EmptyMap<>();
3228 
3229     /**
3230      * Returns the empty map (immutable).  This map is serializable.
3231      *
3232      * <p>This example illustrates the type-safe way to obtain an empty set:
3233      * <pre>
3234      *     Map&lt;String, Date&gt; s = Collections.emptyMap();
3235      * </pre>
3236      * Implementation note:  Implementations of this method need not
3237      * create a separate <tt>Map</tt> object for each call.   Using this
3238      * method is likely to have comparable cost to using the like-named
3239      * field.  (Unlike this method, the field does not provide type safety.)
3240      *
3241      * @see #EMPTY_MAP
3242      * @since 1.5
3243      */
3244     @SuppressWarnings("unchecked")
3245     public static final <K,V> Map<K,V> emptyMap() {
3246         return (Map<K,V>) EMPTY_MAP;
3247     }


3269         }
3270 
3271         public int hashCode()                      {return 0;}
3272 
3273         // Preserves singleton property
3274         private Object readResolve() {
3275             return EMPTY_MAP;
3276         }
3277     }
3278 
3279     // Singleton collections
3280 
3281     /**
3282      * Returns an immutable set containing only the specified object.
3283      * The returned set is serializable.
3284      *
3285      * @param o the sole object to be stored in the returned set.
3286      * @return an immutable set containing only the specified object.
3287      */
3288     public static <T> Set<T> singleton(T o) {
3289         return new SingletonSet<>(o);
3290     }
3291 
3292     static <E> Iterator<E> singletonIterator(final E e) {
3293         return new Iterator<E>() {
3294             private boolean hasNext = true;
3295             public boolean hasNext() {
3296                 return hasNext;
3297             }
3298             public E next() {
3299                 if (hasNext) {
3300                     hasNext = false;
3301                     return e;
3302                 }
3303                 throw new NoSuchElementException();
3304             }
3305             public void remove() {
3306                 throw new UnsupportedOperationException();
3307             }
3308         };
3309     }


3322         SingletonSet(E e) {element = e;}
3323 
3324         public Iterator<E> iterator() {
3325             return singletonIterator(element);
3326         }
3327 
3328         public int size() {return 1;}
3329 
3330         public boolean contains(Object o) {return eq(o, element);}
3331     }
3332 
3333     /**
3334      * Returns an immutable list containing only the specified object.
3335      * The returned list is serializable.
3336      *
3337      * @param o the sole object to be stored in the returned list.
3338      * @return an immutable list containing only the specified object.
3339      * @since 1.3
3340      */
3341     public static <T> List<T> singletonList(T o) {
3342         return new SingletonList<>(o);
3343     }
3344 
3345     /**
3346      * @serial include
3347      */
3348     private static class SingletonList<E>
3349         extends AbstractList<E>
3350         implements RandomAccess, Serializable {
3351 
3352         private static final long serialVersionUID = 3093736618740652951L;
3353 
3354         private final E element;
3355 
3356         SingletonList(E obj)                {element = obj;}
3357 
3358         public Iterator<E> iterator() {
3359             return singletonIterator(element);
3360         }
3361 
3362         public int size()                   {return 1;}


3364         public boolean contains(Object obj) {return eq(obj, element);}
3365 
3366         public E get(int index) {
3367             if (index != 0)
3368               throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
3369             return element;
3370         }
3371     }
3372 
3373     /**
3374      * Returns an immutable map, mapping only the specified key to the
3375      * specified value.  The returned map is serializable.
3376      *
3377      * @param key the sole key to be stored in the returned map.
3378      * @param value the value to which the returned map maps <tt>key</tt>.
3379      * @return an immutable map containing only the specified key-value
3380      *         mapping.
3381      * @since 1.3
3382      */
3383     public static <K,V> Map<K,V> singletonMap(K key, V value) {
3384         return new SingletonMap<>(key, value);
3385     }
3386 
3387     /**
3388      * @serial include
3389      */
3390     private static class SingletonMap<K,V>
3391           extends AbstractMap<K,V>
3392           implements Serializable {
3393         private static final long serialVersionUID = -6979724477215052911L;
3394 
3395         private final K k;
3396         private final V v;
3397 
3398         SingletonMap(K key, V value) {
3399             k = key;
3400             v = value;
3401         }
3402 
3403         public int size()                          {return 1;}
3404 


3406 
3407         public boolean containsKey(Object key)     {return eq(key, k);}
3408 
3409         public boolean containsValue(Object value) {return eq(value, v);}
3410 
3411         public V get(Object key)                   {return (eq(key, k) ? v : null);}
3412 
3413         private transient Set<K> keySet = null;
3414         private transient Set<Map.Entry<K,V>> entrySet = null;
3415         private transient Collection<V> values = null;
3416 
3417         public Set<K> keySet() {
3418             if (keySet==null)
3419                 keySet = singleton(k);
3420             return keySet;
3421         }
3422 
3423         public Set<Map.Entry<K,V>> entrySet() {
3424             if (entrySet==null)
3425                 entrySet = Collections.<Map.Entry<K,V>>singleton(
3426                     new SimpleImmutableEntry<>(k, v));
3427             return entrySet;
3428         }
3429 
3430         public Collection<V> values() {
3431             if (values==null)
3432                 values = singleton(v);
3433             return values;
3434         }
3435 
3436     }
3437 
3438     // Miscellaneous
3439 
3440     /**
3441      * Returns an immutable list consisting of <tt>n</tt> copies of the
3442      * specified object.  The newly allocated data object is tiny (it contains
3443      * a single reference to the data object).  This method is useful in
3444      * combination with the <tt>List.addAll</tt> method to grow lists.
3445      * The returned list is serializable.
3446      *
3447      * @param  n the number of elements in the returned list.
3448      * @param  o the element to appear repeatedly in the returned list.
3449      * @return an immutable list consisting of <tt>n</tt> copies of the
3450      *         specified object.
3451      * @throws IllegalArgumentException if {@code n < 0}
3452      * @see    List#addAll(Collection)
3453      * @see    List#addAll(int, Collection)
3454      */
3455     public static <T> List<T> nCopies(int n, T o) {
3456         if (n < 0)
3457             throw new IllegalArgumentException("List length = " + n);
3458         return new CopiesList<>(n, o);
3459     }
3460 
3461     /**
3462      * @serial include
3463      */
3464     private static class CopiesList<E>
3465         extends AbstractList<E>
3466         implements RandomAccess, Serializable
3467     {
3468         private static final long serialVersionUID = 2739099268398711800L;
3469 
3470         final int n;
3471         final E element;
3472 
3473         CopiesList(int n, E e) {
3474             assert n >= 0;
3475             this.n = n;
3476             element = e;
3477         }
3478 


3512                 a = (T[])java.lang.reflect.Array
3513                     .newInstance(a.getClass().getComponentType(), n);
3514                 if (element != null)
3515                     Arrays.fill(a, 0, n, element);
3516             } else {
3517                 Arrays.fill(a, 0, n, element);
3518                 if (a.length > n)
3519                     a[n] = null;
3520             }
3521             return a;
3522         }
3523 
3524         public List<E> subList(int fromIndex, int toIndex) {
3525             if (fromIndex < 0)
3526                 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
3527             if (toIndex > n)
3528                 throw new IndexOutOfBoundsException("toIndex = " + toIndex);
3529             if (fromIndex > toIndex)
3530                 throw new IllegalArgumentException("fromIndex(" + fromIndex +
3531                                                    ") > toIndex(" + toIndex + ")");
3532             return new CopiesList<>(toIndex - fromIndex, element);
3533         }
3534     }
3535 
3536     /**
3537      * Returns a comparator that imposes the reverse of the <i>natural
3538      * ordering</i> on a collection of objects that implement the
3539      * <tt>Comparable</tt> interface.  (The natural ordering is the ordering
3540      * imposed by the objects' own <tt>compareTo</tt> method.)  This enables a
3541      * simple idiom for sorting (or maintaining) collections (or arrays) of
3542      * objects that implement the <tt>Comparable</tt> interface in
3543      * reverse-natural-order.  For example, suppose a is an array of
3544      * strings. Then: <pre>
3545      *          Arrays.sort(a, Collections.reverseOrder());
3546      * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
3547      *
3548      * The returned comparator is serializable.
3549      *
3550      * @return a comparator that imposes the reverse of the <i>natural
3551      *         ordering</i> on a collection of objects that implement
3552      *         the <tt>Comparable</tt> interface.


3578      * Returns a comparator that imposes the reverse ordering of the specified
3579      * comparator.  If the specified comparator is null, this method is
3580      * equivalent to {@link #reverseOrder()} (in other words, it returns a
3581      * comparator that imposes the reverse of the <i>natural ordering</i> on a
3582      * collection of objects that implement the Comparable interface).
3583      *
3584      * <p>The returned comparator is serializable (assuming the specified
3585      * comparator is also serializable or null).
3586      *
3587      * @return a comparator that imposes the reverse ordering of the
3588      *         specified comparator
3589      * @since 1.5
3590      */
3591     public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
3592         if (cmp == null)
3593             return reverseOrder();
3594 
3595         if (cmp instanceof ReverseComparator2)
3596             return ((ReverseComparator2<T>)cmp).cmp;
3597 
3598         return new ReverseComparator2<>(cmp);
3599     }
3600 
3601     /**
3602      * @serial include
3603      */
3604     private static class ReverseComparator2<T> implements Comparator<T>,
3605         Serializable
3606     {
3607         private static final long serialVersionUID = 4374092139857L;
3608 
3609         /**
3610          * The comparator specified in the static factory.  This will never
3611          * be null, as the static factory returns a ReverseComparator
3612          * instance if its argument is null.
3613          *
3614          * @serial
3615          */
3616         final Comparator<T> cmp;
3617 
3618         ReverseComparator2(Comparator<T> cmp) {


3657             }
3658         };
3659     }
3660 
3661     /**
3662      * Returns an array list containing the elements returned by the
3663      * specified enumeration in the order they are returned by the
3664      * enumeration.  This method provides interoperability between
3665      * legacy APIs that return enumerations and new APIs that require
3666      * collections.
3667      *
3668      * @param e enumeration providing elements for the returned
3669      *          array list
3670      * @return an array list containing the elements returned
3671      *         by the specified enumeration.
3672      * @since 1.4
3673      * @see Enumeration
3674      * @see ArrayList
3675      */
3676     public static <T> ArrayList<T> list(Enumeration<T> e) {
3677         ArrayList<T> l = new ArrayList<>();
3678         while (e.hasMoreElements())
3679             l.add(e.nextElement());
3680         return l;
3681     }
3682 
3683     /**
3684      * Returns true if the specified arguments are equal, or both null.
3685      */
3686     static boolean eq(Object o1, Object o2) {
3687         return o1==null ? o2==null : o1.equals(o2);
3688     }
3689 
3690     /**
3691      * Returns the number of elements in the specified collection equal to the
3692      * specified object.  More formally, returns the number of elements
3693      * <tt>e</tt> in the collection such that
3694      * <tt>(o == null ? e == null : o.equals(e))</tt>.
3695      *
3696      * @param c the collection in which to determine the frequency
3697      *     of <tt>o</tt>


3802      * exactly one method invocation on the backing map or its <tt>keySet</tt>
3803      * view, with one exception.  The <tt>addAll</tt> method is implemented
3804      * as a sequence of <tt>put</tt> invocations on the backing map.
3805      *
3806      * <p>The specified map must be empty at the time this method is invoked,
3807      * and should not be accessed directly after this method returns.  These
3808      * conditions are ensured if the map is created empty, passed directly
3809      * to this method, and no reference to the map is retained, as illustrated
3810      * in the following code fragment:
3811      * <pre>
3812      *    Set&lt;Object&gt; weakHashSet = Collections.newSetFromMap(
3813      *        new WeakHashMap&lt;Object, Boolean&gt;());
3814      * </pre>
3815      *
3816      * @param map the backing map
3817      * @return the set backed by the map
3818      * @throws IllegalArgumentException if <tt>map</tt> is not empty
3819      * @since 1.6
3820      */
3821     public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
3822         return new SetFromMap<>(map);
3823     }
3824 
3825     /**
3826      * @serial include
3827      */
3828     private static class SetFromMap<E> extends AbstractSet<E>
3829         implements Set<E>, Serializable
3830     {
3831         private final Map<E, Boolean> m;  // The backing map
3832         private transient Set<E> s;       // Its keySet
3833 
3834         SetFromMap(Map<E, Boolean> map) {
3835             if (!map.isEmpty())
3836                 throw new IllegalArgumentException("Map is non-empty");
3837             m = map;
3838             s = map.keySet();
3839         }
3840 
3841         public void clear()               {        m.clear(); }
3842         public int size()                 { return m.size(); }


3866     }
3867 
3868     /**
3869      * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
3870      * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>,
3871      * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This
3872      * view can be useful when you would like to use a method
3873      * requiring a <tt>Queue</tt> but you need Lifo ordering.
3874      *
3875      * <p>Each method invocation on the queue returned by this method
3876      * results in exactly one method invocation on the backing deque, with
3877      * one exception.  The {@link Queue#addAll addAll} method is
3878      * implemented as a sequence of {@link Deque#addFirst addFirst}
3879      * invocations on the backing deque.
3880      *
3881      * @param deque the deque
3882      * @return the queue
3883      * @since  1.6
3884      */
3885     public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
3886         return new AsLIFOQueue<>(deque);
3887     }
3888 
3889     /**
3890      * @serial include
3891      */
3892     static class AsLIFOQueue<E> extends AbstractQueue<E>
3893         implements Queue<E>, Serializable {
3894         private static final long serialVersionUID = 1802017725587941708L;
3895         private final Deque<E> q;
3896         AsLIFOQueue(Deque<E> q)           { this.q = q; }
3897         public boolean add(E e)           { q.addFirst(e); return true; }
3898         public boolean offer(E e)         { return q.offerFirst(e); }
3899         public E poll()                   { return q.pollFirst(); }
3900         public E remove()                 { return q.removeFirst(); }
3901         public E peek()                   { return q.peekFirst(); }
3902         public E element()                { return q.getFirst(); }
3903         public void clear()               {        q.clear(); }
3904         public int size()                 { return q.size(); }
3905         public boolean isEmpty()          { return q.isEmpty(); }
3906         public boolean contains(Object o) { return q.contains(o); }