Java Collection details (collection and map interfaces)

Source: Internet
Author: User
Tags iterable java util

In the Java util package there are two parent interfaces for all collections collection and map, their parent-child relationships:
Java.util
+collection This interface extends self---java.lang.iterable interface
+list interface
-arraylist class
-linkedlist class
-vector class This class is implemented synchronously.

+queue interface
+ not commonly used, not in this table.

+set interface
+sortedset interface
-treeset class
-hashset

+map interface
The-hashmap class (in addition to being unsynchronized and allowing null keys/values to be used, is roughly the same as Hashtable.)
-hashtable class This class is implemented synchronously and does not allow the use of NULL key values
+sortedmap interface
-treemap class

The following is a brief description of the many interfaces and classes: First of all, you can't start with arrays (array)
One, Array, Arrays

Array is the most efficient of all Java "storage and random access to a series of objects".

1.
High efficiency, but the capacity is fixed and cannot be changed dynamically.
One drawback of array is that it is not possible to determine how many elements are actually stored, and length simply tells us the capacity of the array.

2, Java has a arrays class, specifically used to manipulate the array.
The arrays has a set of static functions,
Equals (): Compares two arrays for equality. Array has the same number of elements, and all corresponding element 22 is equal.
Fill (): Fills the value into the array.
Sort (): Used to sort the array.
BinarySearch (): Looks for elements in a sorted array.
System.arraycopy (): Copy of Array.


Second, Collection, Map

If you do not know exactly how many objects you need to write your program, and you need to automatically expand capacity when you are running out of space, you need to use the Container class library, which is not applicable.

1. The difference between Collection and Map

The number of elements stored in the container is different.
collection type, with only one element per position.
Map type, holding Key-value pair, like a small database.

2, the purpose of JAVA2 container class library is "Save Object", it is divided into two categories, the respective sub-class relationship

Collection
--list: Elements are stored in a specific order. So the order taken out may be different from the order in which it is put.
--arraylist/linkedlist/vector
--set: cannot contain duplicate elements
--hashset/treeset
Map
--hashmap
--hashtable
--treemap

MAP----A pair of "key-value pairs" objects, that is, its elements are paired objects, the most typical application is a data dictionary, and there are other widely used. In addition, map can return a set of all its keys and all its values, or a set consisting of its key-value pairs, and can also extend a multidimensional map like an array, as long as each "value" of the key-value pairs in the map is a map. Collection.

Collection 1. iterators

An iterator is a design pattern that is an object that can traverse and select objects in a sequence, and the developer does not need to know the underlying structure of the sequence. Iterators are often referred to as "lightweight" objects because they are less expensive to create.

The iterator functionality in Java is relatively simple and can only be moved one way:

(1) Use method iterator () requires the container to return a iterator. The first time you call Iterator's next () method, it returns the first element of a sequence. Note: The iterator () method is an Java.lang.Iterable interface that is inherited by collection.


(2) Use Next () to get the next element in the sequence.

(3) Use Hasnext () to check if there are elements in the sequence.

(4) use remove () to delete the newly returned element of the iterator.

Iterator is the simplest implementation of Java iterators, with more functionality for the listiterator of list design, which can traverse the list in two directions or insert and delete elements from a list.

function method of 2.List

List (interface): Order is the most important feature of the list; It ensures that elements are maintained in a specific order. The list adds a number of methods to collection, allowing you to insert and remove elements to the middle of the list (only recommended for linkedlist use). A list can generate Listiterator, which can be used to traverse a list in two directions or to insert and delete elements from the middle of a list.

ArrayList: A list implemented by an array. It allows for fast random access to elements, but it is slow to insert and remove elements into the list. Listiterator should only be used to traverse the ArrayList backward, rather than to insert and delete elements, as this is much larger than the linkedlist overhead.

LinkedList: Lists implemented by the list. Sequential access is optimized to insert and delete in the middle of the list with little overhead and random access is relatively slow (available ArrayList instead). It has methods AddFirst (), AddLast (), GetFirst (), GetLast (), Removefirst (), Removelast (), and these methods (not defined in any interface or base class) Enables LinkedList to be used as stacks, queues, and bidirectional queues.

function method of 3.Set

Set (interface): Each element that is stored in the set must be unique, which is also different from the list, because set does not save duplicate elements. The object that joins the set must define the Equals () method to ensure the uniqueness of the object. The set has exactly the same interface as the collection. The set interface does not guarantee the order in which elements are maintained.

Hashset:hashset can quickly locate an element, and the object stored in HashSet must define HASHCODE ().

TreeSet: The set of the hold order, the bottom is the tree structure. Use it to extract ordered sequences from the set.

Linkedhashset: has hashset query speed, and internally uses the chain list to maintain the order of elements (the Order of insertions). The result is displayed in the order in which the elements are inserted when iterating through the set using Iterators.

HashSet uses a hash function to sort the elements, which is specifically designed for quick queries, treeset the data structure of the red-black tree, and linkedhashset internally uses hashing to speed up the query, while maintaining the order of the elements using the linked list, Makes it seem that elements are saved in the order in which they are inserted. It is important to note that when generating your own classes, the set needs to maintain the order in which the elements are stored, so implement the comparable interface and define the CompareTo () method.

3. Other Features

* List,set,map holds objects as Object type.
* Collection, List, Set, map are all interfaces and cannot be instantiated.
ArrayList, vectors, HashTable, and HashMap are inherited from them, and these can be instantiated.
* The vector container knows exactly what type of object it holds. Vectors do not perform boundary checks.


Third, collections

Collections is a helper class for the collection class. Provides a series of static methods for searching, sorting, threading, and so on for various collections.
A class--arrays equivalent to a similar operation on an array.
For example, Collections.max (Collection coll); Take the largest element in the Coll.
Collections.sort (list list); Sort elements in List


Iv. How to choose?

1, the difference between the container class and the array, playable
* The container class can only hold object references (pointers to objects), rather than copy the object information to a position in a sequence.
* Once the object is placed in the container, the object's type information is lost.

2.
* In various lists, the best practice is to use ArrayList as the default choice. When inserting and deleting frequently, use LinkedList ();
Vector is always slower than ArrayList, so try to avoid it.
* In various sets, hashset is usually better than hashtree (INSERT, find). Use TreeSet only if you need to produce a sorted sequence.
The only reason for the existence of Hashtree: the ability to maintain the ordering state of its elements.
* In a variety of maps
The HashMap is used for quick lookups.
* When the number of elements is fixed, use array, because array efficiency is the highest.


Conclusion: The most commonly used is arraylist,hashset,hashmap,array. Also, we will find a pattern, which is sorted by treexxx.


Attention:

1. Collection does not have a get () method to get an element. Elements can only be traversed by iterator ().
2. Set and collection have identical interfaces.
3, List, you can use the Get () method to remove one element at a time. Use numbers to select one of a bunch of objects, get (0) .... (Add/get)
4, generally use ArrayList. Use LinkedList to construct stack stacks, queue queues.

5, map with put (K,V)/get (k), you can also use ContainsKey ()/containsvalue () to check if it contains a key/value.
HashMap will use the object's hashcode to quickly find the key.
* Hashing
The hash code is the transformation of the object's information into a unique int value, stored in an array.
We all know that the array lookup speed is the fastest in all storage structures. So, you can speed up lookups.

When a collision occurs, let the array point to multiple values. That is, the array generates a table of cassia at each location.

6, the element in the map, you can extract the key sequence, the value sequence alone.
Use Keyset () to extract the key sequence and generate a set for all keys in the map.
Use values () to extract the value sequence and generate a collection for all values in the map.

Why a build set, a Build collection? That's because key is always unique and value allows repetition

Java Collection details (collection and map interfaces)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.