1. 程式人生 > >Java中的Collection與Map

Java中的Collection與Map

LinkedList:連結串列方式實現List ArrayList:以陣列的方式實現List 如果要查詢一個特定的元素且不知道他的位置,你需要訪問所有的元素直到找到相匹配的。如果集合中的元素很多,那將是費時的。如果你不關心元素的順序,有種資料結構能讓你更快地查詢元素。缺點是這種資料結構不能控制元素出現的順序。 The Java collections library supplies(提供) a HashSet class that implements a set based on a hash table. A tree set is a sorted collection.the sorting is accomplished by a tree data structure. (Red-black tree is a self-balancing binary search tree.紅黑樹是一個自平衡的二叉查詢樹。)Adding an element to a tree is slower than adding it to a hash table. But it is still much faster than checking for duplicates in an array or linked list.(但他仍比在陣列中重複地核對要快得多) A double-ended queue, or deque(雙端佇列), lets you efficiently add or remove elements at the head and tail(尾). Adding elements in the middle is not supported. Java SE(標準版) 6 introduced a Deque interface. It is implemented by the ArrayDeque and LinkedList classes, both of which provide deques whose size grows as needed. The priority queue makes use of an elegant and efficient data structure called a heap. A set is a collection that lets you quickly find an existing element. However, to look up an element, you need to have an exact copy of the element to find. That isn’t a very common lookup—usually, you have some key information, and you want to look up the associated element. The map data structure serves that purpose. A map stores key/value pairs. You can find a value if you provide the key. A hash map
hashes the keys, and a tree map uses an ordering on the keys to organize them in a search tree. Keys must be unique. You cannot store two values with the same key. If you call the put method twice with the same key, the second value replaces the first one. “counts.put(word, counts.getOrDefault(word, 0) + 1);”(避免第一次取不到值) 或用 counts.merge(word, 1, Integer::sum); associates word with 1 if the key wasn’t previously present, and otherwise combines the previous value and 1, using the Integer::sum function.