Java------Collection "in detail"

Source: Internet
Author: User
Tags collator comparable set set

Collection

First, the concept of a collection

Personal understanding: Saying simple points is similar, but far more powerful than arrays. Arrays can only be fixed-length, single-type, and the set is the expansion of the array above, enlarge. A collection can put multiple types of objects at the same time, which is what people say, and the number is variable.

Written Explanation: A collection is a simple object that contains more than one object, and the contained object is called an element. A collection can contain any number of objects, the quantity can vary, and there is no limit to the type of the object, which means that all objects in the collection can have the same type, or they can not

With. Set: Unlimited number, type unlimited; arrays: fixed length, single type.

II. Data storage Structure classification

The main thing is to look at the way storage, like arrays are stored sequentially, and the collection of storage is more abundant. There are: (1) sequential storage (2) chained storage (3) tree storage (4) hash store hash (5) map map Store

Three, set frame


(Implementation is the current use of more (using more of the six), the historical collection class is now not commonly used)

1. Features of each interface in the Set frame 1) Collection interface

is a set of objects that are allowed to be duplicated.

The collection interface is used to represent any object or group of elements. This interface is used when you want to handle a set of elements in the usual way possible.

It also uses the iterator interface, the iterator iterator , which is used primarily to enumerate the elements in the collection. (see example to understand, in Hangzhou electric A problem is easy to understand points.) Similar to scanner. Simple to understand: put all the elements in the collection in an iterator (a close-up container), and then iterate through all the contents of it)

Implementation class: LinkedList ArrayList

(As for the internal method, just look at the method in the implementation class)

Cases:

Import Java.util.arraylist;import java.util.collection;import Java.util.hashset;import Java.util.Iterator;import Cn.hncu.bean.person;public class Collectiondemo {public static void main (string[] args) {//collection col = new ArrayList ( ;//collection<object> col = new arraylist<object> ();//The order in which the elements are stored and added are consistent collection<object> col = new Hashset<object> ();//The order in which the elements are stored is determined by the internal hash algorithm according to the value of the element, and for object types such as the person object, each new address is different, so in each run the result, its order may be the change//increment Addcol.add (1); From jdk1.5 onwards, you can automatically pack Col.add (3), Col.add (2), Col.add (New person ("Jack")), Col.add ("Java"), Col.add (2);//Add duplicate elements, For list is possible, and for set is not added. Delete Remove removes the element itself//col.remove (3);//col.remove (2);//Change//col.remove (1); Col.add (4); Unreasonable, because the position changed object objs[] = Col.toarray (); Col.clear (); for (int i=0;i<objs.length;i++) {if (Objs[i].equals (1)) {OBJS [I]=4;} Col.add (Objs[i]);} Check (traverse)//Enhanced for Loop (foreach statement), can only read all, and there is no subscript concept//for (Object obj:col) {//system.out.println (obj);//}// Iterate through the collection with an iterator iterator iterator<object> it = Col.iterator (); while (it.hasnExt ()) {Object obj = It.next (), if (obj instanceof person) {System.out.println ("object:" +obj);} else if (obj instanceof Integer) {System.out.println ("int:" +obj);} Else{system.out.println ("Other:" +obj);}}}

2) Set interface

Inherit collection, unordered but not repeatable.

By definition, the set interface inherits the collection interface, and it does not allow duplicates to exist in the collection. All the original methods are readily available in collection and no new methods are introduced. The specific set implementation class relies on the Equals () method of the added object to check for equivalence.

Implementation class: HashSet TreeSet

3) List Interface

Inherit collection, orderly but allow repetition, and introduce positional subscripts.

The list interface inherits the collection interface to define an ordered set of allowed duplicates. This interface is not only able to process a part of the list, but also adds a location-oriented operation. Location-oriented operations include the ability to insert an element or collection, and also to get, drop, or change the functionality of an element. Search in List

The element can start at the head or tail of the list, and if an element is found, it will also report where the element resides. (note: Do not underestimate the location of the operation function of the addition, there is great usefulness, such as the need to the set of which (position) elements to operate, they are helpless)

Attention:

A) The Hashcode () method is not called automatically when a list (such as ArrayList) is used. Because in the list, repeating is repeated, do not need to judge, to ensure uniqueness.

b) The list has added the function of subscript index, so that the modification of the list can use the Set method to replace the elements of the specified position directly, do not need to be as complex as set (to convert the array to modify, and then to convert back). (Verify the point I said above)

c) collection with a iterator iterator, and list can be used with a listiterator listing iterator. The former can only be next (), which contains not only the next () method, but also the previous () method. Therefore, if you want to use the list to do similar to the book page, you can not only flip backwards, but also forward.

Implementation class: LinkedList ArrayList

4) Map Interface

the map interface is not an inheritance of the collection interface . Instead, start with your own interface hierarchy for maintaining key-value associations. By definition, this interface describes a key-to-value mapping that is never duplicated.

This interface method can be divided into three sets of operations: changing, querying, and providing an optional view.

The change operation allows you to add and remove key-value pairs from the map. Both the key and the value can be null. However, you cannot add a map as a key or value to itself.

The Map.entry interface (entry is the inner class in the map interface, so it is written): The map's EntrySet () method returns an object set set that implements the Map.entry interface, where each object is a specific key-value pair in the underlying map.

This is still a picture to compare the image, easier to understand

Implementation class: TreeMap HashMap

2. Implementation Class 1) ArrayList class and LinkedList class

Which of the two types depends on the specific needs: if you want to support random access without inserting or removing elements at any point except the trailer, ArrayList provides an optional collection.

However, if you want to add and remove elements frequently from the middle of the list, and as long as the sequential access list element, then the LinkedList implementation is better.

A few common methods:

 boolean add(E e)
Adds the specified element to the tail of this list.
 void add(int index,E element)
Inserts the specified element into the specified position in this list.

 E get(int index)
Returns the element at the specified position in this list.
boolean isEmpty()
Returns true if there are no elements in this list
 E remove(int index)
Removes the element at the specified position in this list.
 int size()
Returns the number of elements in this list.
 E set(int index,E element)
Replaces the element at the specified position in this list with the specified element.

Note: In addition, LinkedList adds some methods for working with the elements on both sides of the list, which make it easy to use LinkedList as a stack, queue, or other endpoint-oriented data structure. itself can be linkedlist as a stack and queue, as for why can be divided into these two, pay attention to how you use

The method of the face.

 void
addfirst (e e)
            inserts the specified element at the beginning of this list.
 void addlast (e e)
            adds the specified element to the end of this list.
 e
getfirst ()
            Returns the first element of this list.
 e getlast ()
            returns the last element of this list.
 E removeFirst()
Removes and returns the first element of this list.
 E removeLast()
Removes and returns the last element of this list.

2) HashMap class and TreeMap class

Which of the two types depends on the specific needs: inserting, deleting, and locating elements in a map, HashMap is the best choice. But if you want to traverse the keys sequentially, then TreeMap is better.

The key class that is added with HashMap requires a clear definition of the hashcode () implementation (understanding: Map.keyset Returns the set set of keys, and the set set has a limit on the hashcode implementation, so the class that is the key is also subject to that restriction). With the TreeMap implementation, the elements added to the map must be sortable.

Note: Both HashMap and TreeMap implement the Cloneable interface.

3) HashSet class and TreeSet class

The "Set framework" supports two common implementations of the set interface: HashSet and TreeSet. In more cases, HashSet stores the collection of repeated liberties. With efficiency in mind, objects added to the hashset need to implement the Hashcode () method in a way that distributes the hash code appropriately. When you need to pump in an orderly manner from the collection

When you take an element, the TreeSet implementation is useful. To be able to proceed smoothly, the elements added to the TreeSet must be sortable.

Because this is relatively not a lot of use, in addition to look at the above two categories, specific to see the API will be.

Iv. sorting of sets 1, Method 1

The Java.lang.Comparable interface works when a class has a natural order. The object collection is assumed to be of the same type, which allows the collection to be sorted into natural order.

The int compareTo (T obj) method in this interface compares the current instance object with Object obj, returns a negative value if it precedes the object obj, returns 0 if the two objects are in the same position in the sort, or returns a positive value if it is behind the object obj.

The implementation points of this sort method are:

The object class that is placed into the container implements the comparable interface. The method that is implemented by CompareTo () determines the order in which objects are arranged.

2. Method 2

The Java.util.Comparator interface works when a class has a natural order. The object collection is assumed to be of the same type, which allows the collection to be sorted into natural order.

The Compare (T O1, To2) method in this interface: compares the two parameters used to sort. Returns a negative, 0, or positive integer based on the first parameter less than, equal to, or greater than the second parameter

The implementation points of this sort method are:

Let the container join the Comparer object at construction time.

Chinese sorting problem:

Comparison functions are not problematic for sorting characters in ASCII codes such as letters and numbers, but the Chinese sort is obviously incorrect. This is mainly in Java in the use of Chinese encoding GB2312 or GBK, char type conversion to int type of process has a relatively large deviation. This deviation is caused by the Compare method, so we can actually

Now comparator interface. In addition, the internationalization problem can be solved by collator class.

The Java.text.Collator class, which provides classes and interfaces for handling text, dates, numbers, and messages in a way unrelated to natural language.

3. Assembly Sequencing Applications

In JDK1.2, there are 14 classes that implement the comparable interface, and the natural sort specified in these classes is as follows:

1) Bigdecimal,biginteger,byte,double,float,integer,long,short sorted by number size

2) Character sorted by numeric size of Unicode values

3) Collationkey Sort by locale-sensitive string

4) Date chronological order

5) The File is sorted by the Unicode value of the fully qualified character of the system-specific path name

6) Objectstreamfield Sort by the Unicode value of the characters in the name

7) string sorted by character Unicode value in string

Note: If a class cannot or does not facilitate the implementation of the Java.lang.Comparable interface, you can provide your own sorting behavior using the method that implements the comparer comparator interface. Similarly, if the default comparable behavior does not meet the engineering needs, you can also provide your own comparator.









Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java------Collection "in detail"

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.