Black Horse Programmer _java Collection Overview

Source: Internet
Author: User
Tags addall comparable set set

-------Android Training, Java training, look forward to communicating with you! ----------

I. Set-up System

Object-oriented language is the embodiment of things in the form of objects, so in order to facilitate the operation of multiple objects, the object is stored, the collection is the most common way to store objects.
Arrays and collections are similar to containers, but the array length is fixed and the data types are fixed, and the collection classes are mutable.

is a diagram of the collection class in Java.

Is the inheritance system that the collection class keeps extracting upward. Top Layer for collection interface

Two common sub-class interfaces implemented
List and set

List: Can hold repeating elements, element access is ordered.
Set: Can not hold duplicate elements, element access is unordered.
The list is subdivided into arraylist,linkedlist and vectors, etc.
Set is subdivided into hashset,treeset and so on.
The specific partition is based on its storage method, i.e. data structure.

Two. Common methods for collection interfaces


Take ArrayList as an example:

ArrayList al=new ArrayList ();

(1) Adding elements

Al.add ("Java");//add element, parameter is generic object, in order to receive any type of object, in addition, the collection holds the address of the object, not the object itself.
A1.addall (); Adds all of the specified collection. Parameter is a collection
Al.size ();//Set length.

(2) Deleting an element
Al.remove ("Java");
Al.clean () emptying the collection

(3) The judging element.
Al.contains ("Java"); returns the Boolean type
Al.isempty ();

(4) Take the intersection
Retainall (); The parameter is a collection that retains the intersection portion of the specified collection.

(5) Get elements

The acquisition of elements in a collection is done primarily through iterators.

The iterator () collection of this static method can get a subclass object to an iterator iterator interface. The subclass has several methods for removing elements from the collection. A static method is actually a set of static internal classes, because to directly access the elements of the contents of the collection so defined within the collection, the iterator interface is simply a common extraction of the inner class of the collection, so that all the elements of the collection of rules of operation of the uniform, The static method iterator () is also defined inside the collection to get the object of the inner class. By polymorphism, the iterator reference to its parent class interface points to the subclass inner class object.

How to use:

(a)

for (Iterator iter = Iterator (); Iter.hasnext ();)
{
System.out.println (Iter.next ());
}

(b)

Iterator iter = L.iterator ();
while (Iter.hasnext ())
{
System.out.println (Iter.next ());
}

Considerations for using Iterators

Iterators are common in the Collcection interface and replace the enumeration (enumeration) in the vector class.

The next method of the iterator is to take the element down automatically, to avoid nosuchelementexception.

The next method of the iterator returns a value type of object, so remember the type conversion.

Three. The list interface is its child class.

ArrayList; The underlying data structure is the array structure, and the query modification speed is quickly based on the index, but the additions and deletions are slow, because one position changes the other position to move sequentially.
LinkedList; The underlying data structure is a linked list structure; Adding and deleting is fast, disconnecting and rebuilding the connection, the query is slow, because it needs to be accessed from the element object from the beginning, not by the index.
Vector bottom is the array structure and ArrayList consistent, is the old version exists is replaced, the thread is synchronous, ArrayList is not synchronized, multi-threading need to manually lock. Synchronization can reduce efficiency. At the same time, vector default array length is 15,arraylist default array length of 10 to save resources.

Elements in the list collection are ordered, elements can be duplicated, and the collection system elements are indexed. Indexed so you can operate on the index, with unique methods for indexed elements. Of course, because of the existence of indexes the list collection can also be traversed to get all the elements, not limited to iterators.

It is important to note that the Listiterator iterator differs from the iterator iterator, which is a subclass of the latter, which contains the latter's acquisition function but has its own unique function. For example, a iterator iterator cannot perform concurrent operations on an element, that is, when the element is removed and the element is modified at the same time, a concurrency exception is thrown when the iterator is in conflict with the method of the collection itself to operate on an element. The sub-class interface Listiterator encapsulates the corresponding modification method to avoid this kind of security.

Common methods:

(1) Increase
Add (index,elements)
AddAll (index,collection)
(2) by deleting
Remove (Index)
(3) Change
Set (index,element)
(4) Check
Get (Index)
Sublist (From,to)
Listiterator ();
IndexOf (Element)
LastIndexOf (Element)

LinkedList:

The unique method is related to its data structure, because it is a linked list structure, so its end-to-end elements operate more.
AddFirst (Element); add first
GetFirst (); first acquisition
AddLast (Element), trailing bit added
GetLast (); tail-bit acquisition.
Removefirst (); get first element delete element at the same time
Removelast (); Gets the tail element while deleting the element//throws an exception when the element is empty.
Pollfirst (); 1.6 version of the new feature, the same as the Removefirst method, but does not throw an exception when the element is empty, the return value is null
Polllast ();
Peaklast (); Replace GetLast
Peakfirst ();

Vector:

A point to be aware of; enumeration method. Enumeration is a unique way of extracting vectors
Enumerations are actually the same as iterations, but they are superseded because the names and methods of the enumerations are too long.
Vector v=new vector ();
Enumeration en=v.elements ();//usage is the same as an iterator.
while (En.hasmoreelements ()) {
SOP (En.nextelement ());
}

Three. Set interface and its subclasses

The function of the set set is consistent with the list collection, except that there is no action on the pin of the element in the unordered method. This disorder refers to the order in which they are stored.

HashSet:

The underlying data structure is a hash table. , the order in which they are stored is determined by their hash value.
When the element is stored, the first is to call the Hashcode method to return the hash value that is used to refer to the address value, compare the value of the hash with the existing element first, and then, if the value of the address is equal, to compare the value of the object content by calling the Equals method for comparison. The Add method adds a failure if it differs from the original address, and if the address value is not the same, it is stored directly and no longer calls the Equals method. Therefore, it is generally necessary to override the hashcode and Equals methods when storing objects, because the default method does not meet the requirements.
The same steps are also made when deleting and judging. Most of the methods that are called in the process are the element object's own method can be inherited from the object class can also be self or implement interface

TreeSet:

The underlying data structure is a two-fork tree structure that allows you to sort the elements in the set collection. The default is natural ordering, which makes the element itself a comparative feature. The first object element is added as the root, and then the object elements are compared with it, the large one is placed on the other side, and the element is added to the first comparison, and if it is necessary to determine the position with the second comparison, it is a comparison. The binary tree data structure optimizes the number of comparisons to improve performance. When there are too many elements, the binary tree system is too large to automatically take its compromise value as the first comparison value.
Also, because the result of the comparison is determined by the CompareTo method return value, you can force the Conpareto method to return only one value, so that it is arranged in the order in which it was deposited. Returns 0 only one element is saved. In this way, the collection can be stored in either positive or reverse order.

When the collection is storing elements, the comparable interface is called for the sort to be used for natural sorting. The Caompareto of a class is called a natural ordering method. Therefore, before storing the element object in order to have the comparable interface and overriding the custom CompareTo method, the primary condition is sorted first, and the secondary condition is judged when the primary condition is the same.

TreeSet the second sort, when the element itself is not comparable, or the required comparability is not the required rules, then you need to make the collection itself comparative. The comparator comparer is constructed by constructing a constructor to specify the ordering method.

TreeSet ts=new TreeSet (New Compare ());

Class Compare implements comparator{//constructor is encapsulated by implementing the Comparator interface, overriding the Compare method, and then passing the subclass constructor object as a parameter to the collection constructor.
Public in compare (Object o1,object O2) {
Student s1= (Student) O1;
Student s2= (Student) O2;
Return S1.getname (). CompareTo (S2.getname ());
}
}

Four. Map and its sub-categories

The collection stores key-value pairs, is a pair of pairs, and guarantees the uniqueness of the key.

Map Collection System
Hashtable; The underlying is a hash table data structure that cannot be stored in NULL as a key or key value, which is thread-synchronized. Low efficiency
HashMap; The underlying is a hash table data structure and allows NULL as a key or key value, which is not synchronized. High efficiency
TreeMap; The bottom layer is a two-fork tree data structure, which can be used to sort the keys in the map geometry with different threads.
and set very much like, in fact, the bottom of the set is the use of the map collection.


Map Commonality Method
Add to
Put (Key,value)//when there is the same key value key, the added value overrides the value of the original key, and returns the value of the overridden key, similar to the one that called the Remove method.
Putall (map<?extends key,?extends value> m)
Delete
Clear ()
Remove (Object key)//delete the key value at the same time
Judge
ContainsKey (Object key)
Containsvalue (object value)
IsEmpty ();
Get
Get (Object key)//returns NULL when the description does not exist
Size ()
VALUES ()//Gets all the values in the Map collection and returns a collection of collection<v>.
EntrySet ()
KeySet ()

There are two ways to take the map collection, there is no iterator in the map collection, the Map collection is converted to a set set and then removed by an iterator
1,keyset
Set<key> Keyset returns the set set of keys contained in this map, and the set collection has iterators, so you can take all the keys in an iterative manner and get the corresponding key values based on the Get method
2,entryset
Set<map.entry<k,v>> EntrySet (); Stores the mappings in the Map collection in the Set collection, The type is a map.entry mapping relationship type key-value pair, and then the relationship type object is fetched by an iterator map.entry<k,v> is an interface in which Getkey and GetValue methods take out the corresponding keys and key values. The principle is similar to an iterator, except that entry is an internal interface that defines a function by implementing an interface through a map collection subclass.

Five. Expansion

1, tool classes in the collection framework
Collections
• Find a collection
• Remove the maximum value from the collection, the minimum value
• Sort the list collection
• ......
Arrays
• Convert an array to a list collection
• Sorting an array
• Binary search of an array

2,

Enhanced for Loop
Package for iterators after version 1.5
For (data type variable name: traversed union or array) is used to iterate through the collection,
for (String s:al) {} is not the same as an iterator, the loop for the collection can only perform the fetch operation. Iterators can also perform actions on elements in the Remove collection, in addition to traversal. If you use the Listiterator iterator, you can also perform the action of the increase and deletion check.
For the traditional for advanced for, there is a limitation that there must be a traversed target. It is recommended that you use the classic for when iterating through the array, because the classic for can define the foot tag.

Black Horse Programmer _java Collection Overview

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.