JAVA basics-collections (1) and java Basics

Source: Internet
Author: User

JAVA basics-collections (1) and java Basics

As the basic knowledge of JAVA, the set was clearly understood, but the answer was unsatisfactory in the last interview! Repeat the sorting to help you understand and view the information at any time.

First, three important interfaces and features of the java. util package:List, Set (ensure that the elements in the Set are unique), and Map (maintain multiple key-value pairs to ensure that keys are unique ).

Shows the collection framework system:

Figure 1

  

  Differences and relationships between different set types are as follows:

 

Interface

Brief Introduction

Implementation

Operation Features

Member requirements

Set

Duplicate members are not allowed.

HashSet

Traverse members unordered externally

A member can be an Object of any Object subclass. If the equals method is overwritten, modify the hashCode method.

TreeSet

Attackers can traverse members in an external order. Additionally, SortedSet is implemented, and operations that require sequence such as subsets are supported.

The member must implement the caparable interface, or useComparator ConstructionTreeSet. The members are generally of the same type.

LinkedHashSet

The members are traversed by the insertion order of the members.

Similar to HashSet members

List

Provides Random Access to members based on indexes.

ArrayList

Provides quick access to index-based members, which provides better support for adding and deleting tail members.

Objects whose members can subclass any Object

Shortlist

It provides better support for adding and deleting members at any position in the list, but poor support for access to indexed members.

Objects whose members can subclass any Object

Map

Saves key-Value Pair members, performs key-searching, and sorts keys using the compareTo or compare methods.

HashMap

Can meet users' general needs for Map

The key member can be an Object of any Object subclass. If the equals method is overwritten, modify the hashCode method.

TreeMap

Supports sequential key traversal. We recommend that you use HashMap to add and delete members and generate TreeMap from HashMap. The SortedMap interface is added to support sub-Map and other operations that require sequential operations.

The key member must implement the caparable interface, or use Comparator to construct a TreeMap. Key members are generally of the same type.

LinkedHashMap

Reserve the insertion sequence of keys and use the equals method to check the equality of keys and values.

A member can be an Object of any Object subclass. If the equals method is overwritten, modify the hashCode method.

IdentityHashMap

Use = to check the equality of keys and values.

The members are strictly equal.

WeakHashMap

Its behavior depends on the garbage collection thread. It is rarely used for no absolute reason.

 

 

Figure 2

Detailed description of main set Interfaces


Collection Interface
Indicates any object or element group. This interface is used when you want to process a group of elements in a regular way as much as possible. Two interfaces derived from the Collection interface are List and Set

 

List Interface

The List in Java is an effective extension to the array. It is such a structure. If you do not use generics, it can accommodate any type of elements. If you use generics, it can only accommodate elements of the specified type of the generic type. Compared with arrays, the List capacity can be dynamically expanded.

The elements in the List can be repeated. The elements in the List are "ordered". The "ordered" here does not mean sorting, instead, we can specify the position of an element in the set.

Commonly used collection objects in List include ArrayList, Vector, and sorted List. The first two are stored Based on arrays, and the latter is stored Based on linked lists. The Vector is thread-safe, and the other two are not thread-safe.

List can include null, even if the generic type is used.

 

Sort list class
The listlist interface allows null elements. In addition, the values list provides additional get, remove, and insert methods at the beginning or end of the values list. These operations enable the queue list to be used as a stack, queue, or two-way queue (deque ).

ArrayList class
ArrayList implements an array of variable sizes. It allows all elements, including null. ArrayList is not synchronized.
Size, isEmpty, get, set method running time is constant. However, the overhead of the add method is the constant of the allocation. It takes O (n) to add n elements. The running time of other methods is linear.
Each ArrayList instance has a Capacity, that is, the size of the array used to store elements. This capacity can automatically increase with the addition of new elements, but the growth algorithm is not defined. When a large number of elements need to be inserted, you can call the ensureCapacity method before insertion to increase the ArrayList capacity to improve the insertion efficiency.
Like the synchronized list, ArrayList is also non-synchronous (unsynchronized ).

Vector
The Vector is very similar to the ArrayList, but the Vector is synchronized. Although the Iterator created by Vector is the same interface as the Iterator created by ArrayList, because Vector is synchronous, when an Iterator is created and in use, another thread changes the state of the Vector (for example, adding or deleting some elements). When calling the Iterator method, ConcurrentModificationException is thrown. Therefore, this exception must be caught.

Stack
Stack inherits from Vector to implement a post-import, first-out Stack. Stack provides five additional methods to make the Vector used as a Stack. The basic push and pop methods also include the elements of the peek method to get the top of the stack. The empty method tests whether the stack is empty. The search method checks the position of an element in the stack. The Stack is empty after being created.

Set Interface
The Set interface inherits the Collection interface and does not allow repeated items in the Set. Each specific Set implementation class depends on the equals () method of the added object to check uniqueness. The Set interface does not introduce new methods, so Set is a Collection, but its behavior is different.

Set can be roughly divided into two categories: unordered Set and sorted Set. unordered Set includes HashSet and sorted HashSet. Sorted Set mainly refers to TreeSet. HashSet and javashashset can contain null.

Hash table
A Hash table is a data structure used to find objects. The Hash table calculates an integer for each object, which is called a Hash Code ). A Hash table is an array of link lists. Each list is called a buckets (hash table element ). Index = HashCode % buckets (HashCode is the object hash code, and buckets is the total number of hash table elements ).
When you add an element, you may encounter a Hash table element that has been filled with the element. This is called Hash Collisions (Hash conflict ). In this case, you must determine whether the element already exists in the hash table.
If the hash code is reasonably randomly distributed and the number of hash table elements is large enough, the number of hash conflicts will be reduced. At the same time, you can set an initial number of hash table elements to better control the operation of the hashtable. The initial number of hash table elements is buckets = size * 150% + 1 (size is the expected number of elements ).
If the elements in the hash table are too full, rehashing must be performed ). Hash the number of elements in the hash table is multiplied, and the original object is re-imported into the new hash table element, while the original hash table element is deleted. Load factor determines when to re-hash the hash table. In Java programming language, the default value of the load factor is 0.75, and the default hash table element is 101.

HashSet class
In more cases, HashSet is preferred for storing repeated free sets. Considering the efficiency, the hashCode () method must be implemented for the objects added to the HashSet by appropriately allocating hash codes. Although most system classes cover the default Implementation of hashCode () and equals () in the Object, do not forget to overwrite hashCode () and equals () when creating your own classes to be added to the HashSet ().
TreeSet class
TreeSet is a Set that supports sorting. Its parent interface is SortedSet. Therefore, the TreeSet implementation is useful when you want to insert and extract elements in an ordered manner from the set.
Map Interface
The Map interface is not inherited from the Collection interface. The Map interface is used to maintain key/value pairs (key/value pairs ). This interface describes the ing from duplicate keys to values. Similar to Set, Map in Java also has two types: sorted and unordered, unordered tasks include HashMap, Hashtable, and LinkedHashMap, and sorted tasks include TreeMap.

 

HashMap class
HashMap is the best choice for inserting, deleting, and locating elements in a Map. HashMap is NOT thread-safe, and Hashtable is thread-safe. We can regard HashMap as a "simplified" version of Hashtable.

Regardless of HashMap or Hashtable, we can observe its constructor and find that it has two parameters: initialCapacity and loadFactor. By default, initialCapacity is 16 and loadFactor is 0.75. This is related to the number of elements that can be stored in the Hash table. When the number of elements exceeds initialCapacity * loadFactor, the rehash method is triggered to expand the hash table. If we need to insert too many elements into it, we need to adjust these two parameters as appropriate.

TreeMap class
However, if you want to traverse keys in the natural or custom order, it is better to use TreeMap, which is not thread-safe. The key classes required to be added using HashMap clearly define the implementation of hashCode () and equals. This TreeMap has no optimization options because the tree is always in the balance state.
LinkedHashMap class
LinkedHashMap extends HashMap and adds key/value pairs to the link hash image in the insertion order. Like LinkedHashSet, LinkedHashMap uses a dual-link list.
WeakHashMap class
WeakHashMap is a special implementation of Map. It uses WeakReference (weak reference) to store hash table keywords. In this way, when the ing key is no longer referenced outside WeakHashMap, the garbage collector recycles it, but it will include the weak references that reach this object into a queue. Running WeakHashMap regularly checks the queue to identify new weak applications. When a weak reference reaches the queue, it indicates that the keyword is no longer used by anyone and has been collected. Then WeakHashMap deletes the corresponding ing.
IdentityHashMap class
IdentityHashMap is also a special implementation of Map. In this class, the hash code of a keyword should not be calculated by the hashCode () method, but by the System. identityHashCode method (even if the hashCode method has been redefined ). This is the method used by Object. hashCode to calculate the hash code based on the Object's memory address. To compare objects, IdentityHashMap uses = instead of the equals method.
In other words, different keyword objects are considered as different objects even if their content is the same. The IdentityHashMap class can be used to convert the topology of an object (such as serializing or copying objects in depth, A "Node table" is required to track the references of objects that have been processed. Even if an object happens to be equal, the "Node table" should not be considered equal. Another application is the maintenance proxy object. For example, the debugging tool wants to maintain a proxy object for each object during program debugging.
"The IdentityHashMap class is not a Map implementation in general sense! Its implementation intentionally violates the Convention that the Map interface requires comparing objects through the equals method. This class is used only when equality semantics is rarely emphasized ."

References:

Http://jianshi-dlw.iteye.com/blog/1179834

Http://blog.csdn.net/zhangerqing/article/details/8122075

Http://www.cnblogs.com/wing011203/archive/2013/05/07/3066021.html

 

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.