Containers in Java

Source: Internet
Author: User
Tags repetition

Linear table, linked list, collection, hash table is a commonly used data structure, in the Java development, JDK has provided us with a series of corresponding classes to achieve the basic data structure. These classes are in the Java.util package.

Collection

├list

│├linkedlist

│├arraylist

│└vector

│└stack

└set

Map

├hashtable

├hashmap

└weakhashmap


Mainly divided into two branches:

Collection and map, where objects stored in a map are stored in a name-value pair, such as:<name,value>

is the realization of the dictionary.

The two interfaces that are derived from the collection interface are list and set.

One of the features of the list is that it can be repeated in order. Set is characterized by: no order, but not repetition.

What is repetition.

Not to say that there are two compartments in the container with the same object, repetition is: a.equals (b) = = true; So, when we customize the object as the storage element of the container, We have to rewrite the Java.lang.Object equals method, and the default equals of object returns true only if the parameter being compared is itself, obviously not what we want, so we have to override it, and if we override equals we must override Hashcode ( method, because when our object is the key to the dictionary map, our positioning is the same as the Hashcode method, so as to improve efficiency. Note: Two objects equals True,hashcode must return the same int; however, if the equals return false,hashcode is not necessarily different.

The rewriting of them is not easy, and will be discussed in detail later.


List interface

The list is an ordered collection, using this interface to precisely control where each element is inserted. The user can access the elements in the list, similar to the Java array, by using the index (the position of the element in the list, similar to the array subscript).

Unlike the set mentioned below, the list allows the same elements.

In addition to the iterator () method with the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface, There are a number of add () listiterator that allow adding, deleting, setting elements, and traversing forward or backwards.

Common classes that implement the list interface are Linkedlist,arraylist,vector and stack.

LinkedList class

LinkedList implements the list interface, allowing null elements. Additionally LinkedList provides additional Get,remove,insert methods at LinkedList's header or tail. These operations enable LinkedList to be used as stacks (stack), queues (queue), or bidirectional queues (deque).

Note that LinkedList does not have a synchronization method. If multiple threads access a list at the same time, you must implement access synchronization yourself. One workaround is to construct a synchronized list when the list is created:

List List = Collections.synchronizedlist (new LinkedList (...));

ArrayList class

ArrayList implements a variable sized array. It allows all elements, including null. ArrayList is not synchronized.

The Size,isempty,get,set method runs at a constant time. However, the Add method cost is the allocated constant, and the time of O (n) is required to add n elements. The other methods run at a linear time.

Each ArrayList instance has a capacity (Capacity), which is the size of the array used to store the elements. This capacity can automatically increase as new elements are added, but the growth algorithm is not defined. When you need to insert a large number of elements, you can call the Ensurecapacity method before inserting to increase the capacity of the ArrayList to increase the insertion efficiency.

Like LinkedList, ArrayList is also unsynchronized (unsynchronized).

In general, these two can be used, because it is not synchronized, so the efficiency is high.

Vector class

Vectors are very similar to ArrayList, but vectors are synchronized. Iterator created by vector, although the same interface was created with ArrayList, but because vectors are synchronized, and when one iterator is created and is being used, another thread changes the state of the vector (for example, Add or remove some elements), the concurrentmodificationexception is thrown when the iterator method is invoked, so the exception must be caught.

Stack class

Stack inherits from the vector, implementing a LIFO stack. Stack provides 5 additional methods that allow vectors to be used as stacks. Basic push and Pop methods, and Peek method to get the top of the stack elements, empty method test stack is empty, the search method detects an element in the stack position. Stack is just created after stack is empty.

Set interface

The constructor of the set has a constraint, and the Passed-in collection parameter cannot contain duplicate elements.


Map interface

Note that the map does not inherit the collection interface, and the map provides a mapping of key to value. A map cannot contain the same key, and each key can map only one value. The map interface provides a view of 3 collections, which can be treated as a set of key sets, a set of value sets, or a set of key-value mappings.

Hashtable class

Hashtable inherits the map interface and implements a hash table of key-value mappings. Any object that is Non-null (non-null) can be a key or value.

Adding data using put (key, value), fetching data using get (key), the time cost of these two basic operations is constant.

Hashtable adjusts performance by initial capacity and load factor two parameters. Typically, the default load factor 0.75 achieves a better balance of time and space. Increasing the load factor saves space but the corresponding lookup time increases, which can affect operations like get and put.

The Hashtable is synchronized.


HashMap class

HashMap is similar to Hashtable, except that HashMap is unsynchronized and allows NULL, that is, null value and null key. , but when HashMap is treated as collection (the values () method returns collection), its iterative child operation time cost is proportional to the capacity of the HashMap. Therefore, if the performance of an iterative operation is significant, do not set the HASHMAP initialization capacity too high, or the load factor too low.

Weakhashmap class

Weakhashmap is an improved hashmap, which implements a "weak reference" to key, and if a key is no longer referenced externally, the key can be reclaimed by GC.

In general, the selection of data structure:

More search and less re-election ArrayList

More change and less search LinkedList

If a large amount of data is retrieved to select the map, details:

If you are involved in stacks, queues, and other operations, you should consider using the list, for the need to quickly insert, delete elements, should use LinkedList, if you need to quickly randomly access elements, you should use ArrayList.

If the program is in a single-threaded environment, or if access is only done in one thread, it is more efficient to consider a class that is not synchronized, and should use a synchronized class if multiple threads might be working on a class at the same time.

Special attention should be paid to the operation of the hash table, where the object of the key is correctly hashcode the Equals and the method.

Try to return the interface instead of the actual type, such as returning a list instead of ArrayList, so that if you need to replace ArrayList with LinkedList later, the client code does not have to change. This is for abstract programming.

Sync Sex

Vectors are synchronized. Some of the methods in this class ensure that the objects in the vector are thread safe. ArrayList is asynchronous, so the objects in ArrayList are not thread safe. Because the requirements of synchronization can affect the efficiency of execution, it is a good choice to use ArrayList if you do not need a thread-safe collection, which avoids the unnecessary performance overhead of synchronization.

Data growth

From an internal implementation mechanism, both ArrayList and vectors use Arrays (array) to control objects in the collection. When you add elements to both types, if the number of elements exceeds the current length of the internal array they all need to extend the length of the internal array, the vector automatically increases the original one times the length of the array by default, ArrayList is the original 50%, So at the end of the collection you get a lot more space than you really need. So if you want to save a lot of data in a collection, there are some advantages to using vectors because you can avoid unnecessary resource overhead by setting the initialization size of the collection.


Auxiliary class Java.lang.Collections

This class encapsulates some of the list's algorithms, including sorting, reverse, random ordering, and so on.


Important interfaces to implement:

Comparable interface, the CompareTo method that uses this interface when two objects involve comparison operations.


Iterator interface for use when traversing.


JDK1.5 new Features:

1 generic type:

such as: ArrayList <Object>

Avoids the consumption of type conversions during the use process.


2 automatic basic data type packaging and reconciliation package.

This article from Csdn Blog, reprinted please indicate the source: http://blog.csdn.net/weizhaozhe/archive/2009/02/22/3921206.aspx

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.