Holding Your Objects
时间:2014-04-28 12:41:47
收藏:0
阅读:445
# Holding your objects
Java provides a number of ways to hold objects :
>1. An array associates numberical indexes to objects. It holds objects
of a known type so that you don‘t have to cast the result when you‘re looking up
an object. It can be multidimensional, and it can hold primitives. However,
**its size cannot be changed once you create it**.
>2. A **Collection** holds single elements, and a **Map** holds
associated pairs. With Java generics, you specify the type of object to be held
in the containers, so you can‘t put the wrong type into a container and you
don‘t have to cast elements when you fetch them out of a container. Both
**Collections** and **Maps** automatically resize themselves as you add more
elements. **A container won‘t hold primitives, but autoboxing takes care of
translating primitives back and forth to the wrapper types held in the
container**.
>3. Like an array, a **List** also associates numerical indexes to
objects - thus, **arrays and Lists are ordered containers**.
>4. Use an **ArrayList** if you‘re doing a lot of random accesses, but a
**LinkedList** if you will be doing a lot of insertions and removals in the
middle of the list.
>5. The behavior of **Queues** and **Stacks** is provided via the
**LinkedList**.
>6. A **Map** is a way to accociate not integral values, but *objects*
with other objects. **HashMaps** are designed for rapid access, whereas a
**TreeMap** keeps its keys in sorted order, and thus is not as fast as a
HashMap. A **LinkedHashMap** keeps its elements in insertion order, but provides
repid access with hashing.
>7. A **Set** only accepts one of each type of object. **HashSets**
provide maximally fast lookups, whereas **TreeSets** keep the elements in sorted
order. **LinkedHashSets** keep elements in insertion order.
>8. There‘s no need to use the legacy classes **Vector**, **Hashtable**,
and **Stack** in new code.
Here‘s a simpleified diagram of the Java containers.
![Alt Java
Containers](http://knerd.qiniudn.com/thinking_in_java_SimpleContainerTaxonomy.png)
You can see that there are really only 4 basic container components -
**Map**, **List**, **Set**, and **Queue** - and only 2 or 3 implementations of
each one.
评论(0)