JAVA容器的使用

ArrayList and LinkedList are both types of List, and you can see from the output that
they both hold elements in the same order in which they are inserted. The difference between
the two is not only performance for certain types of operations, but also that a LinkedList
contains more operations than an ArrayList. These will be explored more fully later in this
chapter. 
HashSet, TreeSet and LinkedHashSet are types of Set. The output shows that a Set will
only hold one of each identical item, but it also shows that the different Set implementations
store the elements differently. The HashSet stores elements using a rather complex
approach that will be explored in the Containers in Depth chapter—all you need to know at
this point is that this technique is the fastest way to retrieve elements, and as a result the
storage order can seem nonsensical (often, you only care whether something is a member of
the Set, not the order in which it appears). If storage order is important, you can use a
TreeSet, which keeps the objects in ascending comparison order, or a LinkedHashSet,
which keeps the objects in the order in which they were added. 
A Map (also called an associative array) allows you to look up an object using a key, like a
simple database. The associated object is called a value. If you have a Map that associates
states with their capitals and you want to know the capital of Ohio, you look it up using
"Ohio" as the key—almost as if you were indexing into an array. Because of this behavior, a
Map only accepts one of each key. 
Map.put(key, value) adds a value (the thing you want) and associates it with a key (the
thing you look it up with). Map.get(key) produces the value associated with that key. The
above example only adds key-value pairs, and does not perform lookups. That will be shown
later. 
Notice that you don’t have to specify (or think about) the size of the Map because it resizes
itself automatically. Also, Maps know how to print themselves, showing the association with
keys and values. The order that the keys and values are held inside the Map is not the
insertion order because the HashMap implementation uses a very fast algorithm that
controls the order. 
282  Thinking in Java  Bruce Eckel The example uses the three basic flavors of Map: HashMap, TreeMap and
LinkedHashMap. Like HashSet, HashMap provides the fastest lookup technique, and
also doesn’t hold its elements in any apparent order. A TreeMap keeps the keys sorted by
ascending comparison order, and a LinkedHashMap keeps the keys in insertion order
while retaining the lookup speed of the HashMap.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值