The Java Collection framework has to say

Source: Internet
Author: User

First of all, both classes implement the list interface, and the list interface has three implementation classes, namely ArrayList, Vector, and LinkedList. The list is used to hold multiple elements, to maintain the order of elements, and to allow the repetition of elements. The related differences between the 3 specific implementation classes are as follows:

    1. ArrayList is the most commonly used list implementation class, implemented internally by an array, which allows for fast random access to elements. The disadvantage of an array is that there can be no interval between each element, and when the array size does not meet the need to increase storage capacity, it is necessary to copy the data of the array into the new storage space. When inserting or deleting elements from the middle of a ArrayList, it is necessary to copy, move, and cost the array. Therefore, it is suitable for random lookups and traversal, and is not suitable for insertions and deletions.
    2. Vectors, like ArrayList, are also implemented through arrays, except that it supports thread synchronization, where only one thread can write vectors at a time, avoiding inconsistencies caused by simultaneous writing of multiple threads, but achieving synchronization requires a high cost, so Accessing it is slower than accessing ArrayList.
    3. LinkedList is used to store data in a linked list structure, which is very suitable for the dynamic insertion and deletion of data, and the random access and traversal speed is relatively slow. In addition, he provides methods that are not defined in the list interface, specifically for manipulating the header and footer elements, and can be used as stacks, queues, and bidirectional queues.

Look at the Java source code, and find that when the size of the array is not enough, you need to re-establish the array, and then copy the elements into the new array, the size of the ArrayList and vector extended array is different.

In ArrayList:

1 public boolean Add (E e) {
2
3 ensurecapacity (size + 1); Add elements to determine if they can be accommodated. Create a new array if you can't.
4
5 elementdata[size++] = e;
6
7 return true;
8
3 ·
10
One public void ensurecapacity (int mincapacity) {
12
modcount++;
14
oldcapacity int = elementdata.length;
16
if (Mincapacity > Oldcapacity) {
18
Object olddata[] = elementdata; This trip did not see the usefulness, do not know what the developers think
20
int newcapacity = (oldcapacity * 3)/2 + 1; Increase the size of the new array
22
if (Newcapacity < mincapacity)
24
newcapacity = mincapacity;
26
+//mincapacity is usually close to size, so the is a win:
28
Elementdata = arrays.copyof (Elementdata, newcapacity);
30
31}
32
33}
34
35

In Vector:

1 private void Ensurecapacityhelper (int mincapacity) {
2
3 int oldcapacity = Elementdata.length;
4
5 if (Mincapacity > Oldcapacity) {
6
7 object[] OldData = elementdata;
8
9 int newcapacity = (capacityincrement > 0)?
10
One (oldcapacity + capacityincrement): (oldcapacity * 2);
12
if (Newcapacity < mincapacity) {
14
newcapacity = mincapacity;
16
17}
18
Elementdata = arrays.copyof (Elementdata, newcapacity);
20
21}
22
23}
24
25

The differences between ArrayList and vectors are as follows:

    1. ArrayList default is 50% + 1 when memory is insufficient, vector is 1 time times the default extension.
    2. The vector provides the indexof (obj, start) interface, ArrayList not.
    3. Vectors are thread-safe, but in most cases do not use vectors, because thread safety requires greater overhead.

Summarize:


1) Hierarchical structure of the Java Collection framework

2) operations on collections and linear tables using common methods defined by the collection interface

3) traversing the collection using the iterator interface

4) Use the JDK's enhanced for loop instead of iteration iterator for collection traversal

5) familiar with the set interface to understand when and how to use Hashset,linkedhashset or Treehashset to store elements

6) using the comparator interface to compare elements

7) Familiarity with the list interface to learn when and how to use ArrayList or LinkedList to store elements
8) distinguish between vectors and ArrayList, and learn how to use vectors and stacks

9) Simplify program design by using the general type of JDK1.5

10) Understand the difference between collection and map, know when and how to use Hashmap,linkedhashmap,treehashmap to store

11) using static methods in the Collections class
12) using static methods in the Arrays class


The above is the content of the Java collection Framework, if you are not familiar with the article, it is necessary to take a good look.

--------------------------------------------------------------------------------------------------------------- ------------------------------------

The Java Collection schema supports 3 types of collections: Rule set (set), Linear table (list), and diagram (map), respectively, defined in Set,list,map. A set instance stores a set of distinct elements (collections), a list instance stores a set of sequential elements (tables), a map that stores a set of objects---a mapping of key values


The overall architecture is as follows, very important, including the inheritance relationship, implementation of the classification, at a glance:

Collection interface:

Set interface:

HashSet Concrete Class

Linkedhashset Concrete Class

TreeSet Concrete Class

List interface:
ArrayList Concrete Class

LinkedList Concrete Class

Vector class vectors specific classes

Stack Concrete Class


Map interface:
HashMap class

Linkedhashmap class

TreeMap class
    
--------------------------------------------------------------------------------------------------------------- ------------------------------------



1) First of all, collection interface, which is the root interface of processing object collection, provides some common methods, size,iterator,add,remove something

2) Both the set and the list interface are extended from Collection,set is a set of high school mathematics, not allowed to repeat, disorderly. List is like a table, can be repeated, elements in the table is placed in order.

3) Then for the 3 implementations of the set interface:

The HashSet object must implement the Hashcode method, Javaapi Most classes implement the Hashcode method.
Linkedhashset implements an extension to the HashSet, supports the ordering of elements within the ruleset, has no order in the HashSet, and in Linkedhashset, it can be extracted in the order in which the elements are inserted into the collection
TreeSet guarantees that the elements of the set are orderly, there are 2 ways to achieve comparability between objects: 1, objects added to TreeSet implement the comparable interface, 2, specify a comparer for the elements of the ruleset (Comparator)

Tips for use:

If you want to extract the elements in the order in which they are inserted into the collection, with Linkedhashset, its elements are stored in the order in which they are added

If there is no above demand, should use hashset, its efficiency is higher than linkedhashset

Linkedhashset just keep order in the order in which they are added, and to add order attributes to the collection elements, you need to use TreeSet (the collection element has a sort relationship).


4) Again, several implementations of the list

The most important of course is ArrayList (unsynchronized) and LinkedList, a list of dynamically expanding capacity using an array implementation, and a chain-implemented list.

There is also the vector (synchronous) class, which, in addition to the synchronization method that includes access and modification vectors, is the same as ArrayList.

The last is the Stack class, it inherits from the Vector class, but generally only as a function of the stack to use, do not use the vector inside the function


5) Map

Map is a mapping, which is fundamentally different from the previous set and list.

Hash chart HashMap, chain hash chart linkedhashmap, tree diagram Treehashmap is a mapping of 3 implementations, from the name, with the above set of 3 implementations of the analysis, this is similar.

HASHMAP: High Efficiency
Likedhashmap: stored in order of addition, can be removed in order of addition
Treehashmap: Sort Sex

--------------------------------------------------------------------------------------------------------------- ------------------------------------


Collections class and Arrays class:

Collections Class (Note not collection): Provides a number of static methods to manage collections, linear tables (most of which are to manipulate linear tables, such as for linear table copying, sorting, etc., see API)

Arrays class: Provides a variety of static methods for sorting, locating, comparing, and populating elements of an array.

--------------------------------------------------------------------------------------------------------------- -------------------------------------


General types of Use:

refers to using generics in the Java collection to specify the type of element to add:

hashmap<k,v> map = new hashmap<k,v> () where K,v is a two class type, indicating that only objects of the K,v type can be populated here

In addition, only objects can be added to the collection, and the basic data types are automatically transformed into corresponding wrapper classes.

A collection framework is a uniform standard architecture that is defined for representing and manipulating collections. Any set frame contains three chunks of content: external interfaces, interface implementations, and algorithms for set operations.

Java Collection Framework :

1. What is a framework: a collection of class libraries

2. Collection framework: A unified architecture for representing and manipulating the interfaces and classes that implement a collection

3. Collection: Container for storing data

A collection framework consists of two parts: a part is an interface, and a part is a class

4. Why interfaces occur: Because many of the class functions in the collection framework are similar, "use interfaces to standardize classes"

Main structure diagram:

Note: In the "collection Framework", the interface Map and Collection have no affinity in the hierarchy, they are distinct.

Do not simply think that the collection class opportunity is these, the JDK collection class has many of these are just what we often use.
Collection, List, Set, queue, and map are all interfaces (Interface), not specific class implementations.

A List[public interface List<e>extends Collection<e>]:

A An ordered collection interface that allows precise control of the insertion position of each element in the list. The user can access the element based on the integer index of the element (where it is located in the list) and search for the elements in the list.

B Unlike set, a list usually allows repeating elements. More formally, the list usually allows elements E1 and element E2 to meet E1.equals (E2). And if the list itself allows null elements, they usually allow multiple null elements. Inevitably, someone wants to suppress a duplicate list by throwing a run-time exception when the user tries to insert a repeating element

C The List interface adds some additional conventions to the iterator, add, remove, equals, and Hashcode methods to standardize the conventions specified in the Collection interface. For convenience, the declaration of other inheritance methods is also included here

D The list interface provides 4 ways to locate (index) a list element. The list (like a Java array) is based on 0. Note that these operations may be performed in a time proportional to the index values of some implementations, such as the LinkedList class. Therefore, if the caller does not know the implementation, then iterating over the list element is usually better than iterating through the list with an index

E. In addition to the iterator () method, which has the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface. Listiterator has a number of add () methods that allow you to add, delete, set elements, and traverse forward or backward.

The list provides the following methods:

The list interface implements a number of classes:

Abstractlist, Abstractsequentiallist, ArrayList, AttributeList, Copyonwritearraylist, LinkedList, RoleList, Roleunresolvedlist, Stack, Vector in general, the main use is ArrayList, and LinkedList, the other class is not to say useless

ArrayList

ArrayList allows all elements to include NULL. ArrayList not synchronized

Understanding One: ArrayList uses a built-in array to store elements, the starting capacity of this array is 10. When the array needs to grow, the new capacity is obtained as follows: the new capacity = (old capacity *)/2+1, which means that each capacity will probably increase by 50%. This means that if you have a ArrayList object with a large number of elements, then eventually there will be a lot of wasted space, and this waste is caused by the way ArrayList works itself. If there is not enough space to hold the new element, the array will have to be reassigned so that new elements can be added.

Redistribution of the array will result in a dramatic decrease in performance. If we know how many elements a ArrayList will have, we can construct a method to specify the capacity. We can also remove wasted space after the ArrayList is allocated through the TrimToSize method.

Understanding two: ArrayList is implemented with an array, it is not a real linked list, at the time of initialization it sets an initial capacity of the array, when the space is not enough, it will rebuild a larger size of the array, and then copy the previous elements in

Whether it's one or two, no matter how he stores the elements. The only thing you can confirm is that he uses built-in arrays

LinkedList

The list interface is implemented as a link listing. Implements all optional list operations, and allows all elements (including null). In addition to implementing the List interface,

The LinkedList class also provides a uniform naming method for the get, remove, and insert elements at the beginning and end of the list. These operations allow the link list to be used as a stack, queue, or double-ended queue (deque). This class implements the queue interface to provide FIFO queue operations for Add, poll, and so on. Other stacks and double-ended queue operations make it easy to re-cast according to the standard list operation. Although they may run slightly faster than the equivalent list operation, they are included here primarily for ease of consideration.

The Java Collection framework has to say

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.