Dark Horse programmer--java Learning Note eight (collection)

Source: Internet
Author: User

1, Java's initial version provides a very small set of classes for the most commonly used data structures: Vector, Stack, Hashtable, Bitset, and enumeration interfaces, starting with the JAVA1.2 release of a set of fully functional data structures.
The origin of the collection class:
Objects are used to encapsulate unique data, and objects need to be stored if the number of objects is indeterminate.
is stored using the collection container.
Set Features:
1, a container for storing objects.
2, the length of the collection is variable.
3, the base data type value cannot be stored in the collection.
4, interface and implementation are separated from each other.
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.
2, in the Java class, the basic interface in the collection class is the collection interface, which inherits the Itearble interface.
Common Methods of collection:
1, Add.
Boolean Add (Object obj):
Boolean AddAll (Collection coll):
2, delete.
Boolean remove (Object obj):
Boolean RemoveAll (Collection coll);
void Clear ();
3, Judge:
Boolean contains (Object obj):
Boolean Containsall (Colllection coll);
Boolean IsEmpty (): Determines whether there are elements in the collection.
4, Get:
int size ():
Iterator Iterator (): The way to remove an element: an iterator.
The object must depend on the specific container, because each container has a different data structure.
So the iterator object is internally implemented in the container.
For a container user, a specific implementation is not important, as long as the object is obtained through the container to the iterator of the implementation,
That is the iterator method.
The iterator interface is the common interface for extracting elements from all collection containers.
is actually grasping the doll in the game machine the clip!
5, others:
Boolean Retainall (Collection coll);
Object[] ToArray (): Sets the collection to an array.

To make it easier to implement collection, the Java class Library provides a class abstractcollection that abstracts the base method size and Itreator. The implementing person simply inherits the class.
3, the iterator, the iterator interface contains 3 methods,
public interface iterator<e>
{
E next ();
Boolean hasnext ();
void Remove ();
}
By repeatedly invoking the next method, you can access each element individually, not with an array index, and at the end throws a Nosuchelementexception exception. Therefore, you should first call the Hasnext () method to ensure that there are elements available for access. JAVA5 can be accessed later using for each.
The For Each loop can work with any object that implements the Itreable interface.
Public interface Itreable<e> {
Itreator <E> itreator ();
}
The next and Hasnext methods of the Itreator interface are the same as the Nexelement and hasMoreElements methods of the enumeration interface, but this is too cumbersome.
Removing an element, the Remove method of the Itreator interface removes the element that was returned when the next method was last called. It would be illegal to call remove before calling next, which would throw a illegalstateexception.
4, specific collections in Java
Arraylist an index sequence that can grow and shrink dynamically
LinkedList an ordered sequence that can efficiently insert and delete operations at any location
Arraydeque a double-ended queue implemented with a loop array
HashSet an unordered collection with no repeating elements
TreeSet an ordered set
Enumset a collection of values with enumerated types
LinkedList A collection that remembers the order in which elements are inserted
Proiorityqueue A collection that allows for efficient deletion of the smallest element
HASHMAP a data structure that stores key/value associations
TreeMap A mapping table for an orderly arrangement of key values
Enummap A mapping table with key values that are enumerated types
Linkedhashmap A mapping table that remembers the order in which key/value items are added
Weakhashmap A mapping table that can be reclaimed by the garbage collector when its value is useless
Identityhashmap A mapping table that compares key values with = = rather than equals
4, List interface
List is an ordered set, and all of the linked lists in Java are bidirectional.
Because the Linkedlist.add method adds an object to the end of the list, it is sometimes necessary to add the element to the middle, so this task is given to the iterator. Because only the naturally ordered collection uses iterators to add meaning (set has no natural order), so the normal itreator does not have an Add method. The collection class provides Listitreator, which contains the Add method, Previous () Hasprevious (). The Add method adds a new object before the iterator. When the iterator crosses the last element, the addition of the new element becomes the end of the table. The following ABC has four positions that can be inserted.
| ABC a| BC ab| C abc|, if you call next, then calling the Remove method will delete the element to the left of the iterator, and if it is previous, the element on the right will be removed. You cannot call remove two times. The Set method replaces the previous element that invokes next or previous with a new element.
The list iterator can even detect unsynchronized modifications, and the iterator discovers that his collection is modified by another iterator or by the collection itself (adding elements, deleting elements) and throws a concurrent modificationexception exception. Therefore, you should follow these rules: You can attach many iterators to the container as needed, but these iterators can only read the list, plus a single, skill-capable and writable iterator.
Although Linklist provides a get. But the traversal is inefficient.
If you need random access to the list, Arraylist,vector (synchronous security) is available.
Queue: Public interface Queue <e>{}JAVA 6 introduces a double-ended queue: public interface Deque<e> {}both Arraydeque and LinkedList implement the Deque interface.  priority queues: elements can be inserted in any order, but are always retrieved in sorted order. The priority queue queue uses an elegant and efficient data structure called a heap. The heap is a self-tuning two-fork tree that adds add and remove actions to the tree, allowing the smallest elements to be moved to the root without having to spend time sorting the elements. A typical instance of using priority is task scheduling.
5, set interface
Lists and arrays arrange the order of elements according to People's wishes, but to view an element, you need to traverse all the elements. There is a data structure that can quickly find the desired object, which is the hash table (hashTable). The hash table calculates an integer for each object, called a hash code. A hash code is a different hash code generated by the objects of different data fields. The hashcode you implement is compatible with equals. The hash list in Java is implemented with a list of linked lists, each of which is called a bucket, and sometimes the bucket is full, called a hash conflict, when the element content needs to be compared.
Set is a collection of elements that have no repeating elements.
1, determines whether the hash value of the two elements is the same.
If the same, determine whether the contents of the two objects are the same.
2, judging the same hash value, in fact, the object is judged by the method of Hashcode. The Equals method is used to determine the same content.
Be cautious when changing the elements in a collection, and if the hash code of the element changes, the position of the element in the data structure changes.
The TreeSet class is similar to a hash set, but it is an ordered set of elements that can be sorted in any order. Use red and black trees to find the complexity of log2n.
The way to judge the uniqueness of an element is to determine whether the return result of the comparison method is 0, which is 0, which is the same element and does not exist.
TreeSet how the elements are sorted one:
To make the element own the comparison function, the meta needs to implement the comparable interface. Overrides the CompareTo method.
If you do not sort by the natural order that is available in the object. If the object does not have a natural order. What to do?
You can use the TreeSet collection The second sort method two:
Let the collection itself have a comparison function, define a class to implement the comparator interface, overriding the Compare method.
Pass the class object as a parameter to the constructor of the TreeSet collection. It is the holder of the comparison method, which is called the function object, and the function object usually locates the anonymous inner class.
The Navigableset interface is implemented from Java6,treeset, and several methods are added to facilitate locating elements and echo traversal.
6, the mapping table, the mapping table is used to hold the key value pairs, if the key is provided, you can find the corresponding value.
The Java class provides two common implementations for the mapping library: HashMap and TreeMap
The hash table hashes the key, and the tree map sorts the elements in the order of the keys, and organizes them into search trees. A hash or comparison function can only be used for a key, and the value associated with the key cannot be hashed or compared. The key must be unique and cannot have a key that corresponds to two values.
Map has three views, namely, keyset, value set, key/value pair set.
Set<k> KeySet ()
Collection<k> VALUES ()
Set<map.entry<k,v>>entryset ()
7, collection framework, the collection class of Java form the framework of the collection class. It defines a large number of interfaces and abstract classes for the implementation of the collection.
Randomaccess does not have any method that can be used to detect whether a collection supports efficient random access. Both ArrayList and vectors support this interface.
8, view and wrapper, by using the view can get other objects that implement the collection interface and the mapping table interface, for example: Keyset, at first glance, as if this method creates a new
collection, and all the key values are filled in, and then the collection is returned. However, this is not the case. The keyset method returns a class object that implements the set interface, which operates on the original mapping table, a collection called a view. View technology has many very useful applications after the collection framework.
1, lightweight wrapper, Arrays.ailist () will return a list wrapper that wraps the normal Java array. is not a ArrayList, it is a view object with a get and set method that accesses the underlying array. There are also collections classes that contain many usage methods, and the parameters and return values of these methods are collections.
2, child scopes, you can set up a child scope view for many collections. For example. Collection.subrange (N1, N2). You can apply any action to a child range.
3, non-modifiable views, collections there are several methods for generating a non-modifiable view of the collection (Unmodifable views). These views add a run-time check to an existing collection and throw an exception if you find that you are trying to modify the collection. There are 6 of them:
Collections.unmodifiablecollection
. unmodfiablelist
. unmodfiableset
. unmodfiablesortset
. unmodfiablemap
. unmodfiablesortmap
4, synchronous view, if multiple threads access the collection, you must ensure that the collection is not accidentally destroyed. Example: Collections.synchornizedmap (MAP)
5, checking the view, JAVA5 adds a set of check views to provide debugging support for problems with generic types.
Arraylist<stirng > String = new Arraylist<> ()
ArrayList st = string;
Str.add (New Date ());
This error is not detected at run time. An exception is thrown only when a strong turn occurs.
Check the view to detect this problem.
Collection.checklist (String, String.class)
Note: The detected view is limited by the runtime checks that the virtual machine can run.
9, the tool class arrays the conversion between the collections array and the collection.
List<t> arrays.aslist (T ...) data into a collection
Object[] ToArray () Set Conversions to arrays
<T> t[] ToArray (t[] a) set to an array
 
Returns an array containing all the elements in this collection; The run-time type of the returned array is the same as the run-time type of the specified array. If the specified array can hold the collection, the array containing this collection element is returned. Otherwise, a new array with the run-time type of the specified array and this collection size is assigned.

If the specified array can hold collection, and there is space left (that is, the elements of the array are more than the elements of collection), then the elements in the array that are immediately trailing collection are set to NULL. (This method can be used to determine the length of the collection only if the caller knows that the collection does not contain any null elements.) )

If this collection makes some guarantees about the order of elements returned by its iterators, the method must return the elements in the same order.

 

Dark Horse programmer--java Learning Note eight (collection)

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.