1 <!DOCTYPE html>
   2 <!--
   3  Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
   4  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5 
   6  This code is free software; you can redistribute it and/or modify it
   7  under the terms of the GNU General Public License version 2 only, as
   8  published by the Free Software Foundation.  Oracle designates this
   9  particular file as subject to the "Classpath" exception as provided
  10  by Oracle in the LICENSE file that accompanied this code.
  11 
  12  This code is distributed in the hope that it will be useful, but WITHOUT
  13  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  version 2 for more details (a copy is included in the LICENSE file that
  16  accompanied this code).
  17 
  18  You should have received a copy of the GNU General Public License version
  19  2 along with this work; if not, write to the Free Software Foundation,
  20  Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21 
  22  Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  23  or visit www.oracle.com if you need additional information or have any
  24  questions.
  25 -->
  26 <html lang="en-US">
  27 <head>
  28 <title>Java Collections API Design FAQ</title>
  29 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  30 </head>
  31 <body>
  32 <h2>Java Collections API Design FAQ</h2>
  33 <!-- Body text begins here -->
  34 <hr>
  35 This document answers frequently asked questions concerning the
  36 design of the Java collections framework. It is derived from the
  37 large volume of traffic on the collections-comments alias. It
  38 serves as a design rationale for the collections framework.
  39 <h3>Core Interfaces - General Questions</h3>
  40 <ol>
  41 <li><a href="#a1"><b>Why don't you support immutability directly in
  42 the core collection interfaces so that you can do away with
  43 <em>optional operations</em> (and
  44 UnsupportedOperationException)?</b></a></li>
  45 <li><a href="#a2"><b>Won't programmers have to surround any code
  46 that calls optional operations with a try-catch clause in case they
  47 throw an UnsupportedOperationException?</b></a></li>
  48 <li><a href="#a3"><b>Why isn't there a core interface for "bags"
  49 (AKA multisets)?</b></a></li>
  50 <li><a href="#a28"><b>Why didn't you use "Beans-style names" for
  51 consistency?</b></a></li>
  52 </ol>
  53 <h3>Collection Interface</h3>
  54 <ol>
  55 <li><a href="#a5"><b>Why doesn't Collection extend Cloneable and
  56 Serializable?</b></a></li>
  57 <li><a href="#a6"><b>Why don't you provide an "apply" method in
  58 Collection to apply a given method ("upcall") to all the elements
  59 of the Collection?</b></a></li>
  60 <li><a href="#a7"><b>Why didn't you provide a "Predicate" interface,
  61 and related methods (e.g., a method to find the first element in
  62 the Collection satisfying the predicate)?</b></a></li>
  63 <li><a href="#a8"><b>Why don't you provide a form of the addAll
  64 method that takes an Enumeration (or an Iterator)?</b></a></li>
  65 <li><a href="#a9"><b>Why don't the concrete implementations in the
  66 JDK have Enumeration (or Iterator) constructors?</b></a></li>
  67 <li><a href="#a10"><b>Why don't you provide an Iterator.add
  68 method?</b></a></li>
  69 </ol>
  70 <h3>List Interface</h3>
  71 <ol>
  72 <li><a href="#a11"><b>Why don't you rename the List interface to
  73 Sequence; doesn't "list" generally suggest "linked list"? Also,
  74 doesn't it conflict with java.awt.List?</b></a></li>
  75 <li><a href="#a12"><b>Why don't you rename List's set method to
  76 replace, to avoid confusion with Set.</b></a></li>
  77 </ol>
  78 <h3>Map Interface</h3>
  79 <ol>
  80 <li><a href="#a14"><b>Why doesn't Map extend
  81 Collection?</b></a></li>
  82 </ol>
  83 <h3>Iterator Interface</h3>
  84 <ol>
  85 <li><a href="#a18"><b>Why doesn't Iterator extend
  86 Enumeration?</b></a></li>
  87 <li><a href="#a19"><b>Why don't you provide an Iterator.peek method
  88 that allows you to look at the next element in an iteration without
  89 advancing the iterator?</b></a></li>
  90 </ol>
  91 <h3>Miscellaneous</h3>
  92 <ol>
  93 <li><a href="#a23"><b>Why did you write a new collections framework
  94 instead of adopting JGL (a preexisting collections package from
  95 ObjectSpace, Inc.) into the JDK?</b></a></li>
  96 <li><a href="#a26"><b>Why don't you eliminate all of the methods and
  97 classes that return "views" (Collections backed by other
  98 collection-like objects). This would greatly reduce
  99 aliasing.</b></a></li>
 100 <li><a href="#a27"><b>Why don't you provide for "observable"
 101 collections that send out Events when they're
 102 modified?</b></a></li>
 103 </ol>
 104 <hr>
 105 <h3>Core Interfaces - General Questions</h3>
 106 <ol>
 107 <li><a id="a1"><b>Why don't you support immutability
 108 directly in the core collection interfaces so that you can do away
 109 with <em>optional operations</em> (and
 110 UnsupportedOperationException)?</b></a>
 111 <p>This is the most controversial design decision in the whole API.
 112 Clearly, static (compile time) type checking is highly desirable,
 113 and is the norm in Java. We would have supported it if we believed
 114 it were feasible. Unfortunately, attempts to achieve this goal
 115 cause an explosion in the size of the interface hierarchy, and do
 116 not succeed in eliminating the need for runtime exceptions (though
 117 they reduce it substantially).</p>
 118 <p>Doug Lea, who wrote a popular Java collections package that did
 119 reflect mutability distinctions in its interface hierarchy, no
 120 longer believes it is a viable approach, based on user experience
 121 with his collections package. In his words (from personal
 122 correspondence) "Much as it pains me to say it, strong static
 123 typing does not work for collection interfaces in Java."</p>
 124 <p>To illustrate the problem in gory detail, suppose you want to
 125 add the notion of modifiability to the Hierarchy. You need four new
 126 interfaces: ModifiableCollection, ModifiableSet, ModifiableList,
 127 and ModifiableMap. What was previously a simple hierarchy is now a
 128 messy heterarchy. Also, you need a new Iterator interface for use
 129 with unmodifiable Collections, that does not contain the remove
 130 operation. Now can you do away with UnsupportedOperationException?
 131 Unfortunately not.</p>
 132 <p>Consider arrays. They implement most of the List operations, but
 133 not remove and add. They are "fixed-size" Lists. If you want to
 134 capture this notion in the hierarchy, you have to add two new
 135 interfaces: VariableSizeList and VariableSizeMap. You don't have to
 136 add VariableSizeCollection and VariableSizeSet, because they'd be
 137 identical to ModifiableCollection and ModifiableSet, but you might
 138 choose to add them anyway for consistency's sake. Also, you need a
 139 new variety of ListIterator that doesn't support the add and remove
 140 operations, to go along with unmodifiable List. Now we're up to ten
 141 or twelve interfaces, plus two new Iterator interfaces, instead of
 142 our original four. Are we done? No.</p>
 143 <p>Consider logs (such as error logs, audit logs and journals for
 144 recoverable data objects). They are natural append-only sequences,
 145 that support all of the List operations except for remove and set
 146 (replace). They require a new core interface, and a new
 147 iterator.</p>
 148 <p>And what about immutable Collections, as opposed to unmodifiable
 149 ones? (i.e., Collections that cannot be changed by the client AND
 150 will never change for any other reason). Many argue that this is
 151 the most important distinction of all, because it allows multiple
 152 threads to access a collection concurrently without the need for
 153 synchronization. Adding this support to the type hierarchy requires
 154 four more interfaces.</p>
 155 <p>Now we're up to twenty or so interfaces and five iterators, and
 156 it's almost certain that there are still collections arising in
 157 practice that don't fit cleanly into any of the interfaces. For
 158 example, the <em>collection-views</em> returned by Map are natural
 159 delete-only collections. Also, there are collections that will
 160 reject certain elements on the basis of their value, so we still
 161 haven't done away with runtime exceptions.</p>
 162 <p>When all was said and done, we felt that it was a sound
 163 engineering compromise to sidestep the whole issue by providing a
 164 very small set of core interfaces that can throw a runtime
 165 exception.</p>
 166 </li>
 167 <li><a id="a2"><b>Won't programmers have to surround any
 168 code that calls optional operations with a try-catch clause in case
 169 they throw an UnsupportedOperationException?</b></a>
 170 <p>It was never our intention that programs should catch these
 171 exceptions: that's why they're unchecked (runtime) exceptions. They
 172 should only arise as a result of programming errors, in which case,
 173 your program will halt due to the uncaught exception.</p>
 174 </li>
 175 <li><a id="a3"><b>Why isn't there a core interface for
 176 "bags" (AKA multisets)?</b></a>
 177 <p>The Collection interface provides this functionality. We are not
 178 providing any public implementations of this interface, as we think
 179 that it wouldn't be used frequently enough to "pull its weight." We
 180 occasionally return such Collections, which are implemented easily
 181 atop AbstractCollection (for example, the Collection returned by
 182 Map.values).</p>
 183 </li>
 184 <li><a id="a28"><b>Why didn't you use "Beans-style
 185 names" for consistency?</b></a>
 186 <p>While the names of the new collections methods do not adhere to
 187 the "Beans naming conventions", we believe that they are
 188 reasonable, consistent and appropriate to their purpose. It should
 189 be remembered that the Beans naming conventions do not apply to the
 190 JDK as a whole; the AWT did adopt these conventions, but that
 191 decision was somewhat controversial. We suspect that the
 192 collections APIs will be used quite pervasively, often with
 193 multiple method calls on a single line of code, so it is important
 194 that the names be short. Consider, for example, the Iterator
 195 methods. Currently, a loop over a collection looks like this:</p>
 196 <pre>
 197     for (Iterator i = c.iterator(); i.hasNext(); )
 198         System.out.println(i.next());
 199 </pre>
 200 Everything fits neatly on one line, even if the Collection name is
 201 a long expression. If we named the methods "getIterator",
 202 "hasNextElement" and "getNextElement", this would no longer be the
 203 case. Thus, we adopted the "traditional" JDK style rather than the
 204 Beans style.</li>
 205 </ol>
 206 <hr>
 207 <h3>Collection Interface</h3>
 208 <ol>
 209 <li><a id="a5"><b>Why doesn't Collection extend Cloneable
 210 and Serializable?</b></a>
 211 <p>Many Collection implementations (including all of the ones
 212 provided by the JDK) will have a public clone method, but it would
 213 be mistake to require it of all Collections. For example, what does
 214 it mean to clone a Collection that's backed by a terabyte SQL
 215 database? Should the method call cause the company to requisition a
 216 new disk farm? Similar arguments hold for serializable.</p>
 217 <p>If the client doesn't know the actual type of a Collection, it's
 218 much more flexible and less error prone to have the client decide
 219 what type of Collection is desired, create an empty Collection of
 220 this type, and use the addAll method to copy the elements of the
 221 original collection into the new one.</p>
 222 </li>
 223 <li><a id="a6"><b>Why don't you provide an "apply" method
 224 in Collection to apply a given method ("upcall") to all the
 225 elements of the Collection?</b></a>
 226 <p>This is what is referred to as an "Internal Iterator" in the
 227 "Design Patterns" book (Gamma et al.). We considered providing it,
 228 but decided not to as it seems somewhat redundant to support
 229 internal and external iterators, and Java already has a precedent
 230 for external iterators (with Enumerations). The "throw weight" of
 231 this functionality is increased by the fact that it requires a
 232 public interface to describe upcalls.</p>
 233 </li>
 234 <li><a id="a7"><b>Why didn't you provide a "Predicate"
 235 interface, and related methods (e.g., a method to find the first
 236 element in the Collection satisfying the predicate)?</b></a>
 237 <p>It's easy to implement this functionality atop Iterators, and
 238 the resulting code may actually look cleaner as the user can inline
 239 the predicate. Thus, it's not clear whether this facility pulls its
 240 weight. It could be added to the Collections class at a later date
 241 (implemented atop Iterator), if it's deemed useful.</p>
 242 </li>
 243 <li><a id="a8"><b>Why don't you provide a form of the
 244 addAll method that takes an Enumeration (or an Iterator)?</b></a>
 245 <p>Because we don't believe in using Enumerations (or Iterators) as
 246 "poor man's collections." This was occasionally done in prior
 247 releases, but now that we have the Collection interface, it is the
 248 preferred way to pass around abstract collections of objects.</p>
 249 </li>
 250 <li><a id="a9"><b>Why don't the concrete implementations
 251 in the JDK have Enumeration (or Iterator) constructors?</b></a>
 252 <p>Again, this is an instance of an Enumeration serving as a "poor
 253 man's collection" and we're trying to discourage that. Note
 254 however, that we strongly suggest that all concrete implementations
 255 should have constructors that take a Collection (and create a new
 256 Collection with the same elements).</p>
 257 </li>
 258 <li><a id="a10"><b>Why don't you provide an Iterator.add
 259 method?</b></a>
 260 <p>The semantics are unclear, given that the contract for Iterator
 261 makes no guarantees about the order of iteration. Note, however,
 262 that ListIterator does provide an add operation, as it does
 263 guarantee the order of the iteration.</p>
 264 </li>
 265 </ol>
 266 <hr>
 267 <h3>List Interface</h3>
 268 <ol>
 269 <li><a id="a11"><b>Why don't you rename the List
 270 interface to Sequence; doesn't "list" generally suggest "linked
 271 list"? Also, doesn't it conflict with java.awt.List?</b></a>
 272 <p>People were evenly divided as to whether List suggests linked
 273 lists. Given the implementation naming convention,
 274 &lt;<em>Implementation</em>&gt;&lt;<em>Interface</em>&gt;, there
 275 was a strong desire to keep the core interface names short. Also,
 276 several existing names (AbstractSequentialList, LinkedList) would
 277 have been decidedly worse if we changed List to Sequence. The
 278 naming conflict can be dealt with by the following incantation:</p>
 279 <pre>
 280     import java.util.*;
 281     import java.awt.*;
 282     import java.util.List;   // Dictates interpretation of "List"
 283 </pre></li>
 284 <li><a id="a12"><b>Why don't you rename List's set
 285 method to replace, to avoid confusion with Set.</b></a>
 286 <p>It was decided that the "set/get" naming convention was strongly
 287 enough enshrined in the language that we'd stick with it.</p>
 288 </li>
 289 </ol>
 290 <hr>
 291 <h3>Map Interface</h3>
 292 <ol>
 293 <li><a id="a14"><b>Why doesn't Map extend
 294 Collection?</b></a>
 295 <p>This was by design. We feel that mappings are not collections
 296 and collections are not mappings. Thus, it makes little sense for
 297 Map to extend the Collection interface (or vice versa).</p>
 298 <p>If a Map is a Collection, what are the elements? The only
 299 reasonable answer is "Key-value pairs", but this provides a very
 300 limited (and not particularly useful) Map abstraction. You can't
 301 ask what value a given key maps to, nor can you delete the entry
 302 for a given key without knowing what value it maps to.</p>
 303 <p>Collection could be made to extend Map, but this raises the
 304 question: what are the keys? There's no really satisfactory answer,
 305 and forcing one leads to an unnatural interface.</p>
 306 <p>Maps can be <em>viewed</em> as Collections (of keys, values, or
 307 pairs), and this fact is reflected in the three "Collection view
 308 operations" on Maps (keySet, entrySet, and values). While it is, in
 309 principle, possible to view a List as a Map mapping indices to
 310 elements, this has the nasty property that deleting an element from
 311 the List changes the Key associated with every element before the
 312 deleted element. That's why we don't have a map view operation on
 313 Lists.</p>
 314 </li>
 315 </ol>
 316 <hr>
 317 <h3>Iterator Interface</h3>
 318 <ol>
 319 <li><a id="a18"><b>Why doesn't Iterator extend
 320 Enumeration?</b></a>
 321 <p>We view the method names for Enumeration as unfortunate. They're
 322 very long, and very frequently used. Given that we were adding a
 323 method and creating a whole new framework, we felt that it would be
 324 foolish not to take advantage of the opportunity to improve the
 325 names. Of course we could support the new and old names in
 326 Iterator, but it doesn't seem worthwhile.</p>
 327 </li>
 328 <li><a id="a19"><b>Why don't you provide an
 329 Iterator.peek method that allows you to look at the next element in
 330 an iteration without advancing the iterator?</b></a>
 331 <p>It can be implemented atop the current Iterators (a similar
 332 pattern to java.io.PushbackInputStream). We believe that its use
 333 would be rare enough that it isn't worth including in the interface
 334 that everyone has to implement.</p>
 335 </li>
 336 </ol>
 337 <hr>
 338 <h3>Miscellaneous</h3>
 339 <ol>
 340 <li><a id="a23"><b>Why did you write a new collections
 341 framework instead of adopting JGL (a preexisting collections
 342 package from ObjectSpace, Inc.) into the JDK?</b></a>
 343 <p>If you examine the goals for our Collections framework (in the
 344 Overview), you'll see that we are not really "playing in the same
 345 space" as JGL. Quoting from the "Design Goals" Section of the Java
 346 Collections Overview: "Our main design goal was to produce an API
 347 that was reasonably small, both in size, and (more importantly) in
 348 'conceptual weight.'"</p>
 349 <p>JGL consists of approximately 130 classes and interfaces; its
 350 main goal was consistency with the C++ Standard Template Library
 351 (STL). This was <em>not</em> one of our goals. Java has
 352 traditionally stayed away from C++'s more complex features (e.g.,
 353 multiple inheritance, operator overloading). Our entire framework,
 354 including all infrastructure, contains approximately 25 classes and
 355 interfaces.</p>
 356 <p>While this may cause some discomfort for some C++ programmers,
 357 we feel that it will be good for Java in the long run. As the Java
 358 libraries mature, they inevitably grow, but we are trying as hard
 359 as we can to keep them small and manageable, so that Java continues
 360 to be an easy, fun language to learn and to use.</p>
 361 </li>
 362 <li><a id="a26"><b>Why don't you eliminate all of the
 363 methods and classes that return "views" (Collections backed by
 364 other collection-like objects). This would greatly reduce
 365 aliasing.</b></a>
 366 <p>Given that we provide core collection interfaces behind which
 367 programmers can "hide" their own implementations, there will be
 368 aliased collections whether the JDK provides them or not.
 369 Eliminating all views from the JDK would greatly increase the cost
 370 of common operations like making a Collection out of an array, and
 371 would do away with many useful facilities (like synchronizing
 372 wrappers). One view that we see as being particularly useful is
 373 <a href=
 374 "../List.html#subList-int-int-">List.subList</a>.
 375 The existence of this method means that people who write methods
 376 taking List on input do not have to write secondary forms taking an
 377 offset and a length (as they do for arrays).</p>
 378 </li>
 379 <li><a id="a27"><b>Why don't you provide for
 380 "observable" collections that send out Events when they're
 381 modified?</b></a>
 382 <p>Primarily, resource constraints. If we're going to commit to
 383 such an API, it has to be something that works for everyone, that
 384 we can live with for the long haul. We may provide such a facility
 385 some day. In the meantime, it's not difficult to implement such a
 386 facility on top of the public APIs.</p>
 387 </li>
 388 </ol>
 389 <hr>
 390 <p style="font-size:smaller">
 391 Copyright &copy; 1998, 2017, Oracle and/or its affiliates. 500 Oracle Parkway<br>
 392     Redwood Shores, CA 94065 USA. All rights reserved.</p>
 393 <!-- Body text ends here -->
 394 </body>
 395 </html>