JAVA Collection class-a rare Summary

Source: Internet
Author: User
Tags sorts

JAVA Collection class-a rare Summary

 

 

The following documents are summarized in your learning and hope to help you. If you want to reprint it, thank you.

1. StringBuffer thread security, StringBuilder thread security efficiency is slightly higher
Set: objects in a Set are not arranged in any specific way, and data is operated by index value. duplicate elements are not allowed.
List: objects in a sequence are stored in a linear manner and operated on data by index value. Repeated elements can exist.
Ing (Map): each item of the ing is a "name-value" pair. The names cannot be repeated, and the values can be repeated. A name corresponds to a unique value.

Display the specified collection type: no packing process is performed.
Collection Resulte = dao. retrieveByClause (TaskVO. class, SQL );
Specify the size of the returned array when converting to an array.
Return result. toArray (new TaskVO [result. size ()]);
Arrays cannot be forcibly transformed:
String [] s = (String []) list. toArray (); -- Error
String [] s = (String []) list. toArray (new String [list. size ()]); -- correct

The iterator obtains all objects in the set one by one in order and is the standard mechanism for accessing each element in the set.
Create iterator: The Iterator () method of the Collection interface returns an iterator
Iterator it = test. iterator (); // convert the test set object into an Iterator
Common method of iterator:
HasNext () // determine whether the iterator contains the next element
Next () // return the next element of the iteration
Remove () // Delete the elements returned by the iterator

The Iterator interface is shown below: public interface Iterator {
Boolean hasNext ();
Object next ();
Void remove (); // Optional
}
It can be considered that the iterator points to the position between two elements.
When you call the remove () method, you must call the next () method once.
The remove () method is actually used to delete the last returned element.

List common methods:
Void add (int index, Object element): add an Object element to the position index.
Boolean addAll (int index, Collection collection): Add all elements in the collection of the container after the index position
Object get (int index): retrieves the element at the position where the subscript is index.
Int indexOf (Object element): searches for the location where the Object element first appears in the List.
Int lastIndexOf (Object element): searches for the last position of an Object element in the List.
Object remove (int index): deletes the element at the index position.
ListIterator listIterator (int startIndex): returns a ListIterator downloader, starting from startIndex.
List subList (int fromIndex, int toIndex): returns a subList, where elements are stored as an element before fromIndex to toIndex.

 

ArrayList: we can regard it as an array that can automatically increase the capacity.
Returns an array using the toArray () of ArrayList.
Arrays. asList () returns a list.
Iterator provides a common way to access elements in a set.


View Mode:
One is to measure the time of iteration elements:
Another measurement uses the toArray call to create an array:
The final result is as follows:
Using toArray to call the array iteration elements created is about 30% to 60% faster than using iterator.
However, the time overhead of using the toArray method to create an array is included. The use of iterator is actually faster than 10% to 20%, so we try not to create an intermediate array. Instead, use the iteration method.

ArrayList automatic Scaling
Implementation Mechanism: ArrayList. ensureCapacity (int minCapacity)
First, obtain the length of the current elementData attribute oldCapacity.
Then, you can determine whether or not to scale up by determining the oldCapacity and minCapacity parameters. If minCapacity is greater
OldCapacity, then we will resize the current List object.
The scale-up policy is: The one with a larger value between (oldCapacity * 3)/2 + 1 and minCapacity. Then copy data using Arrays
To transfer the previously stored data to the new array object.
If minCapacity is not greater than oldCapacity, resizing is not performed.

Shortlist
A two-way cyclic list is implemented.
Use consumer list to implement stack, queue, and double-ended queue ).
It has methods such as addFirst (), addLast (), getFirst (), getLast (), removeFirst (), and removeLast.

Use Queue list to implement Queues:
A Queue is a linear table where all inserts can only be performed at one end of the table, and all deletions are performed at the other end of the table.
The end that can be inserted in the table is called the Rear, and the end that can be deleted is called the Front ).
Queue operations are performed based on the FIFO principle.
Physical storage of queues can be sequential or chained.

Use consumer list to implement Stack:
Stack is also a special linear table, which is a kind of structure of LIFO.
Stack is a linear table that only inserts and deletes operations at the end of a table. The end of a table is called the top table and the header is called the bottom table ).
Stack physical storage can be sequential or chained.

Comparison between ArrayList and rule list:
The ArrayList uses arrays at the underlying layer, while the sorted list is completed by a general double-linked list. Each object in the list has two references besides the data itself, it refers to the first element and the last element respectively.
If we often add elements at the beginning of the List or insert or delete elements in the List, we should use the sort List. Otherwise, using ArrayList will be faster.
 

Summary:
A set is an object that saves other objects.
The Collection interface defines some methods for all Collection classes except the Collection classes that implement ing.
The List set type describes an object that stores data by location and is ordered.
ArrayList is a common array for storing data in contiguous areas of memory.

Coding habits:
API-oriented programming to minimize the code change rate:
List Lst = new ArrayList ();
Avoid creating unnecessary objects as much as possible: vo should be created when the if statement is true
TaskReportVO reportvos = new TaskReportVO ();
If (I> 0 ){
LstAllVos. add (reportvos );}
Avoid traversing and deleting collections at the same time. Because this will change the size of the Set;
For (Iterator Iter = ComList. iterator (); iter. hasNext ();){
ComType com = iter. next ();
If (! Com. getName (). contains (abc )){
ComList. remove (com );}
}

Recommended:
For (Iterator Iter = ComList. iterator (); iter. hasNext ();){
ComType com = iter. next ();
If (! Com. getName (). contains (abc )){
Iter. remove (com );}

Estimate the size of objects held in the set. A large number of objects cannot be held, occupying the memory:
List Lst = new ArrayList ();
Adding an element in the lst without limit will inevitably cause the lst to occupy too much memory. Memory Overflow

Map interface:
The second type of interface tree of the set framework.
It provides key-value ing. Each stored object has a corresponding key, which determines the storage location of the object in Map.
Keywords should be unique, and each key can only map one value.
Common Methods:
Object put (Object key, Object value): used to store a key-value Pair in Map
Object remove (Object key): based on the key (key), remove the key-Value Pair and return the value
Void putAll (Map mapping): saves the elements in another Map to the current Map.
Void clear (): clears the elements in the current Map.
Object get (Object key): obtains the corresponding value based on the key.
Boolean containsKey (Object key): determines whether a key exists in the Map)
Boolean containsValue (Object value): determines whether a value exists in the Map)
Public Set keySet (): returns all keys and stores them using the Set container.
Public Collection values (): returns all values and stores them using collections.
Public Set entrySet (): returns an element Set that implements the Map. Entry interface.

HashMap:
Map is mainly used to store key-value pairs. Therefore, duplicate keys are not allowed, but repeated values are allowed.
HashMap is the most commonly used Map. It stores data based on the HashCode value of the key, and can directly obtain its value based on the key, with fast access speed.
HashMap allows a maximum of Null keys for one record and Null values for multiple records;
HashMap does not support thread synchronization. At any time, multiple threads can write HashMap at the same time, which may cause data inconsistency. If synchronization is required, you can use the synchronizedMap method of Collections to synchronize HashMap.

HashMap implementation principle --- hash
The Hash algorithm provides a method to quickly access data. It uses an algorithm to establish the correspondence between the key value and the real value. A hash table is also called a hash table. The basic idea of the hash algorithm is to calculate the corresponding function value using the keyword of the node as the independent variable through a certain function relationship (hash function, use this value as the address of the node stored in the hash table.
When the elements in the hash table are too full, they must be hashed again to generate a new hash table. All elements are stored in the new hash table, the original hash will be deleted. In Java, the load factor is used to determine when to re-hash the hash. For example, if the load factor 0.75 is filled with a 75% position in the hash table, the hash is further hashed.
The higher the load factor (the closer it is to 1.0), the higher the memory usage efficiency, and the longer the element searching time. The lower the load factor (the closer it is to 0.0), the shorter the element search time, the more memory waste.

When do I need to rewrite equals?
When a class has its own unique concept of "logical equality" (different from the concept of Object Identity );
The Object class only provides a comparison of references. If the two references are not the same, false is returned, which cannot meet the needs of most Object comparisons. Therefore, override is required;
Use the = Operator to check whether the real parameter is a reference to the object"
Use the instanceof operator to check whether the real parameter is of the correct type.
Converts real parameters to the correct type;
For each "key" field in this class, check whether the field value in the real parameter matches the Domain value in the current object. For fields of neither float nor double type, you can use the = Operator for comparison. For fields of the object reference type, you can call the equals method of the referenced object recursively. For fields of the float and double types, convert them to values of the int or long type, and then use the = Operator to compare them;
After completing the equals method, you should ask yourself three questions: Is it symmetric, delivered, consistent? If the answer is no, find the reason for the failure of these features and then modify the code of the equals method.

Both equals () and hashCode () are overwritten.
It is particularly emphasized that these two methods should be overwritten when an object is used as a key value (or index;
After overwriting equals, two different instances may be logically equal, but according to the Object. the hashCode method generates different hash codes, which violates the rule that "equal objects must have equal hash codes ".
As a result, when you use one of them as the key to save it to hashMap, hasoTable, or hashSet, and then use "equal" to find another one as the key value to find them, you cannot find
HashCode values of different types
If this field is Boolean, compute (f? 0: 1)
If it is char, short, byte or int, calculate (int) f
For long type, calculate (int) (f ^ (f >>>> 32 ))
For float type, calculate Float. floatToIntBits (f)
For the double type, calculate Dobule. doubleToLongBits (f)
If the domain is referenced by an object, the hashCode is recursively called.
If this field is an array, each element is treated as a separate field, and a hash code is calculated for each important element,
Comparison:
The storage sequence of HashMap is irrelevant to the output sequence.
LinkedHashMap retains the order in which key-value pairs are stored.
TreeMap sorts the elements in the Map.
Because HashMap and LinkedHashMap store data faster and more efficient than directly using TreeMap.
After all elements are stored, we sort the elements in the whole Map. This can improve the efficiency of the entire program and shorten the execution time.
Note: In TreeMap, keys are sorted. If we want to use TreeMap for normal sorting, the objects stored in the Key must implement the Comparable interface.

Set:
Extended Collection Interface
Repeated elements are not allowed.
Added restrictions on the add (), equals (), and hashCode () methods.
HashSet and TreeSet are Set implementations.
Set-"hashSet implements hashSet
SortedSet-"TreeSet

Common HashSet methods:
Public boolean contains (Object o): returns true if set contains the specified element.
Public Iterator iterator () returns the Iterator of the elements in the set.
Public Object [] toArray (): returns the array public Object [] toArray (Object [] a) containing all elements in the set: returns an array containing all elements in the set, the runtime type of the returned array is the runtime type of the specified array.
Public boolean add (Object o): If the specified element does not exist in the set, add it to the set.
Public boolean remove (Object o): If a specified element exists in the set, it is deleted from the set.
Public boolean removeAll (Collection c): If the set contains the specified set, all elements of the specified set are deleted from the set.
Public boolean containsAll (Collection c): returns true if set contains all elements of the specified set. If the specified set is also a set, the method returns true only when it is a subset of the current set.

HashSet that implements the Set interface is implemented by HashMap.
We should define hashCode () and equals () for each object to be stored in the hash table ().
How can we prevent repeated elements?
"Key" is the object to be saved, and "value" is a constant. This ensures that the information we need to store
It is a "key ". The "key" cannot be repeated in Map, which ensures that all elements stored in the Set are not repeated.
How does a HashSet filter repeated elements?
Call the HashCode element to obtain the hash code -- "judge whether the hash code is equal. If it is not equal, enter
--- "Equal": determines whether equals () are equal. If not, hashcode is entered. If not, equals is not input.

TreeSet:
TreeSet is implemented by TreeMap.
TreeSet is an ordered set. The elements in the TreeSet are arranged in ascending order. By default, the elements in the TreeSet are arranged in natural order. This means that the Comparable interface must be implemented for the elements in the TreeSet.
When constructing a TreeSet object, we can pass the Comparator object that implements the Comparator interface.

Comparison of several sets:
The HashSet external traversal of Members unordered.
The member can be an Object of any Object subclass, but if the equals method is overwritten
Modify the hashCode method.
The members of the TreeSet are traversed in an orderly manner;
Added SortedSet and supported operations that require sequence, such as subsets.
The member must implement the Comparable interface, or use the Comparator to construct
TreeSet. The members are generally of the same type.
Hashset external traversal by member insertion order
Similar to HashSet members
HashSet is implemented based on the Hash algorithm, and its performance is generally better than TreeSet. We usually should use HashSet. We only use TreeSet when we need the sorting function.

The order in which HashSet elements are stored is irrelevant to the order in which they are added, while that in which HashSet elements are added. TreeSet sorts and stores the elements in our Set.

In general, the TreeSet implementation is useful when you want to extract elements in an ordered manner from a set. In order to proceed smoothly, the elements added to the TreeSet must be sorted. You also need to support the Comparable interface for class objects added to the TreeSet. Generally, it is faster to add elements to a HashSet and then convert the set to a TreeSet for sequential traversal.

Comparable and Comparator
The Comparable interface provides a natural sorting order.
You can implement
Comparator interface to define your own sorting function. You can pass the Comparator to Collections. sort or Arrays. sort.

Comparator Interface
If a class does not implement Comparable or does not like the default Comaparable behavior. Comparator interfaces can be implemented
Directly implement the compare interface of Comparator to complete the custom comparison class.
Example: Arrays. sort (results, new Comparator () Array sorting RepDataQueryExecutor
Example: Collections. sort (lst, new Comparator ()
 

 

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.