Common collection methods in Java

Source: Internet
Author: User

When using Java, we all encounter collections, but Java APIs provide multiple collections.

In general, the collection classes used in Java APIs all implement the collection interface. Its class inheritance structure is as follows:

Collection <-- list <-- Vector
Collection <-- list <-- arraylist
Collection <-- list <-- items list
Collection <-- set <-- hashset
Collection <-- set <-- hashset <-- revoke hashset
Collection <-- set <-- sortedset <-- treeset

Vector: Array-based list encapsulates some functions not available in array for our convenience. It cannot be restricted by array. The performance cannot surpass array. Therefore, when possible, we need to use array more. Another important point is vector: sychronized, which is the only difference between vector and arraylist.

Arraylist: Like vector, it is an array-based linked list, but the difference is that arraylist is not synchronized. Therefore, the performance is better than that of vector, but when running in a multi-threaded environment, you need to manage the synchronization of threads on your own.

Shortlist: Struct list is different from the previous two types of list. It is not based on array, so it is not limited by Array Performance. Each node contains two aspects: 1. Data of the node itself; 2. Information of the next node (nextnode ). SoWhen you add a shard list and delete it, you do not need to move a large amount of data like an array-based list.. You only need to change the relevant information of nextnode. This is the advantage of listing.

List summary:

1. All lists can only contain tables composed of a single object of different types, rather than key-value pairs. Example: [Tom, 1, C];

2. All lists can have the same elements. For example, the vector can have [Tom, koo, too, koo];

3. All lists can have null elements, such as [Tom, null, 1];

4. array-based list (vector, arraylist) is suitable for queries, while sorted list (linked list) is suitable for adding and deleting operations.

Hashset: Although set and list all implement the collection interface, their implementation methods are quite different. List is basically based on array. However, set is implemented based on hashmap, which is the fundamental difference between set and list. The hashset storage method uses the key in hashmap as the corresponding storage item of the set. Look at the add (Object
OBJ.
Public Boolean add (Object OBJ)
{
Return map. Put (OBJ, present) = NULL;
}

This is also the root reason why repeated items cannot be found in the set as in the list, because the key of hashmap cannot be duplicated.

Linkedhashset: A subclass of hashset, a linked list.

Treeset: A subclass of sortedset. Unlike hashset, treeset is ordered. It is implemented through sortedmap.

Set summary:

1. Set is implemented based on map (hashmap );

2. Elements in the set cannot be repeated. If you use the add (Object OBJ) method to add an existing object, the previous object will be overwritten.

Why use a collection class?

When you do not know the number of data to be stored, or you need a more flexible method than the array subscript access mechanism, you need to use the collection class.

 
Understanding collection classes

The Collection class is stored in the Java. util package.
The Collection class stores object references instead of objects. For convenient expression, we call the objects in the Set refer to the reference of objects in the set ).
Set types include set, list, and map ).

(1) Set
Set is the simplest kind of set. Its objects are not sorted in a specific way, but simply add objects to the set, as if they were put in a pocket.
Access and operations to members in a set are performed through reference of the Set object, so there cannot be repeated objects in the set.
There are also multiple variants in the set to implement sorting and other functions, such as treeset, which adds objects to the set and then inserts them into the ordered Object Sequence according to some comparison rules. It implements the sortedset interface, that is, the method of adding object comparison. Through iteration of objects in a set, we can get a set of objects in ascending order.

(2) List
The main feature of a list is that its objects are stored in a linear manner, with no specific order. There is only one beginning and one end. Of course, it is different from a set with no order at all.
In the data structure, the list is represented by arrays and vectors, linked lists, stacks, and queues.
The collection classes of the implementation list are frequently used in our daily work and will be detailed in the following notes.

(3) ing
There is a significant difference between ing and set or list. Each item in the ing is paired. Each object stored in the ing has a related key object, which determines the storage location of the object in the ing. The corresponding keywords must be provided during object retrieval, just like a word in a dictionary. The keyword should be unique.
The keyword itself cannot determine the storage location of an object. It needs to process a hashing technique to generate an integer called hash code,

Hash code is usually used as a offset. The offset is relative to the starting position of the memory area allocated to the ing, and the storage location of the keyword/object pair is determined. Ideally, hash processing should generate evenly distributed values within a given range, and each keyword should obtain different hash codes.

Collection class Introduction
Java. util has 13 classes that can be used to manage collection objects. They support collection, list, or ing sets. The following is a brief introduction to these classes.

Set:
Hashset: Use the implementation of a set of hashmap. Although the set definition is unordered, there must be some method to find an object quite efficiently. Using a hashmap object to store and retrieve a set is implemented within a fixed period of time.

Treeset: The implementation of object sorting sets in ascending order in a set. This means that obtaining the first iterator from a treeset object will provide the object in ascending order. The treeset class uses a treemap.

List:
Vector: Implement a table similar to an array and automatically increase the capacity to accommodate the elements you need. Using subscript to store and retrieve objects is just like in a standard array. You can also use an iterator to retrieve objects from a vector. Vector is the only synchronization container class !! The performance is good when two or more threads access the same time.

Stsck: This class is derived from the vector and the method implementation stack is added! A post-import, first-out storage structure.

Shortlist: Implement a linked list. The linked list defined by this class can also be used as a stack or queue.

Arraylist: Implement an array. It can be scaled and accessed like a linked list. It provides functions similar to the Vector class but is not synchronized.

Ing:
Hashtable: To implement an image, all keys must be not empty. To work efficiently, the key-Defining class must implement the hashcode () method and equal () method. This class is an inheritance implemented by Java and can be better used in other classes that implement the image.

Hashmap: Implement an image, allow the storage of null objects, and allow the key to be null (because the key must be unique, of course, only one can be ).

Weakhashmap: Implements an image like this: normally, if a key is no longer referenced to an object, the key/object pair will be discarded. In contrast to hashmap, the key in the image maintains the lifecycle of the key/object pair, although the program using the image does not reference the key and therefore cannot retrieve the object.

Treemap: To implement such an image, objects are listed in ascending order by buttons.

Both set and list are extended by the public interface collection, so they can be referenced using a variable of the collection type. This means that any list or set can be referenced in this way, except for the ing Class (but not completely excluded, because a list can be obtained from the ing .) Therefore, the standard way to pass a list or set to a method is to use collection parameters.

Vector or arraylist. Which one is better? Why?
The answer to this question cannot be generalized. Sometimes it is better to use a vector. Sometimes it is an arraylist. Sometimes these two are not the best choices. Don't expect a simple affirmative answer, because it depends on what you use them. There are four factors to consider:

(1) API

(2) synchronous processing

(3) data growth

(4) usage mode

We will discuss these four aspects one by one.

API
This is the description in Java programming language (Addison-Wesley, June 2000) compiled by Ken Arnold. vector is similar to arraylist .. From the API perspective, these two classes are very similar. But there are still some major differences between them.

Synchronization

The vector is synchronized. Some 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 synchronization requirements will affect the execution efficiency, it is a good choice to use arraylist if you do not need a thread-safe set, this avoids unnecessary performance overhead due to synchronization.

Data Growth

In terms of the internal implementation mechanism, both arraylist and vector use arrays to control objects in the set. When you add elements to these two types, if the number of elements exceeds the current length of the internal array, both of them need to extend the length of the internal array, by default, vector automatically doubles the length of the original array, and arraylist is 50% of the original length. Therefore, the space occupied by this set is always larger than what you actually need. Therefore, if you want to save a large amount of data in the collection, using vector has some advantages, because you can avoid unnecessary resource overhead by setting the initialization size of the collection.

Usage mode

In arraylist and vector, it takes the same time to search for data from a specified position (through an index) or add or remove an element at the end of the set, this time is represented by O (1. However, if an element is added or removed from another position in the Set, the time consumed will grow linearly: O (n-I), where N represents the number of elements in the set, I indicates the index location where the element is added or removed. Why? It is assumed that all elements after the I and I elements in the collection must be displaced during the above operations. What does all this mean?
This means that you can only search for elements at a specific position or add or remove elements at the end of the set. You can use vector or arraylist. For other operations, you 'd better select another set operation class.
For example, the time spent by the linklist collection class to add or remove any element in the set is the same-O (1 ), however, it is slow to index an element-O (I), where I is the index position. it is also easy to use arraylist, because you can simply use indexes instead of creating iterator objects. Linklist also creates an object for each inserted element, so you need to understand that it also brings additional overhead.

Finally, in practical Java, Peter Haggar recommends using a simple array instead of vector or arraylist. This is especially true for programs with high execution efficiency requirements. Array is used to avoid synchronization, additional method calls, and unnecessary Space reallocation.

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.