Java 7 collection type 1th article-Java collection __java

Source: Internet
Author: User
Tags addall instance method int size iterable
Reprint please indicate the source: http://blog.csdn.net/mazhimazh/article/details/17730517
1, on the set of the two-side questions


Let's take a look at a few questions:

1. Create an immutable set:

      public static void Main (string[] args) {
		set<string> Set = new hashset<string> ();
		Set.add ("Java");
		Set.add ("JEE");
		Set.add ("Spring");
		Set.add ("Hibernate");
		Set = Collections.unmodifiableset (set);
		Set.add ("Ajax"); Not allowed.
	}
As you can see, creating an immutable set is primarily a call to the collections Unmodifiableset () method, while the collections class implements the encapsulation of a generic collection through an ornamental pattern.

2, remove the duplicate elements in the list collection, and keep the original order

public static void Main (String args[]) {
        list<string> list=new ArrayList ();
        List.add ("A");
        List.add ("B");
        List.add ("C");
        List.add ("A");
        The list allows elements to repeat for
        (int i=0;i<list.size (); i++) 
               System.out.print ("" +list.get (i));/a B C a
        // Removes duplicate elements and retains the order of the original elements
        list list2=new testd (). function (list);
        for (int i=0;i<list2.size (); i++) 
               System.out.print ("" +list2.get (i));/A B C 
        
} public
<e> List <e> function (list<e> list) {return
         new arraylist<e> (New linkedhashset<e> (list));
}

The code above removes duplicate elements by passing the original list into a linkedhashset. In this case, the Linkedhashset can keep the original order of the elements. If this order is not needed, then the linkedhashset can be replaced with HashSet.


2, set frame class diagram and set contrast


In fact, the two topics are not difficult, just do not understand the collection of deeper. Here is a rough look at the collection. The inherited classes of the collection are shown below.




such as the set can be summed up into three categories, namely list, set and map. At the same time, there are some auxiliary tool classes, such as collections, arrays and other convenient collection operation, the comparison of each set as shown below.




In fact, for the operation of the collection, there is no external

Increase: Adds an element to a collection, inserts all elements from a collection into the current collection delete: Deletes the specified element, deletes all element modifications in the collection: Modifies a specified element lookup: Check the size of the current collection, find the common elements in two sets, and so on Other: Converts an element in a collection to an array representation, determining whether a collection is empty, and so on
3, Iterable, iterator, collection interface


As can be seen from the Java Collection Framework diagram, all classes inherit the Iterable interface directly or indirectly, the source code is as follows:

Package Java.lang;
Import Java.util.Iterator;

/**
 * Implementing this interface allows the target of
 * "foreach" statement.
 * * Public
interface Iterable<t> {
    iterator<t> iterator ();//Returns an iterator that iterates over an element of a group of T types

The Iterable interface is under the Java.lang package, which defines an instance method for obtaining iterator.

The source code for the iterator class is as follows:

Public interface Iterator<e> {
    boolean hasnext ();  Contains the next element
    E next ();           Gets the next element of the collection,
    void Remove ();      Removes the current element from the collection
}

The iterator pattern is the standard access method used to traverse collection classes. It can abstract the access logic from different types of collection classes, thereby avoiding exposing the internal structure of the collection to the client. For example, if you are not using iterator, the way to traverse an array is to use an index:

for (int i=0; i< collection size; i++) {
	//Omit operation code
}

You must use a while loop when accessing a list (LinkedList):

while ((E=e.next ())!=null) { 
	//omit operation code

The above two methods of traversal must know in advance the internal storage structure of the collection, access code and the collection itself is tightly coupled, can not separate access logic from the collection class, each set corresponds to a traversal method, client code can not be reused. And if you later need to replace ArrayList with LinkedList, the original client code must be overridden. To solve these problems, the iterator pattern always iterates through the collection with the same logic:

for (Iterator it = C.iterater (); It.hasnext ();) { 
	// ... 

The ingenious thing about the design is that the client itself does not maintain "pointers" to traverse the collection, all internal states (such as the current element position and whether there is the next element) are maintained by iterator, and this iterator is generated by the collection class through the factory method, so it knows how to traverse the entire collection. It is worth reminding that this factory approach is the iterator () method we mentioned earlier, because all classes inherit the Iterable interface, so his implementation class must implement the iterator () method.

If you want to access the collection later, you can indirectly traverse the entire collection by controlling iterator, sending it forward, backward, and taking the current element command.

Examples are as follows:

public class Testset {public
	static void Main (String args[]) {
		//hashset<string> ct = new hashset<> ( );
		Set<string> ct=new hashset<> ();
		List<string> ct=new arraylist<> ();
		List<string> ct=new linkedlist<> ();
		
		Ct.add ("abc");
		Ct.add ("def");
		
		for (iterator<string> Myitr = Ct.iterator (); Myitr.hasnext ();) {
			System.out.println ());

		Iterator<string> iter = Ct.iterator ();
		while (Iter.hasnext ()) {
			System.out.println (Iter.next ());
		}

		for (String str:ct) {
			System.out.println (str);}}}
Using 3 methods to traverse the collection, the output results are consistent, as follows:

Abc
Def
Abc
Def
Abc
Def

The iterator specific types returned by each collection class may be different, the array may return Arrayiterator,set may return Setiterator,tree may return treeiterator, but they all implement the iterator interface, so , the client doesn't care what kind of iterator it is, it just needs to get the iterator interface, which is the benefit of the object-oriented.

See the iterator specific implementation address of each collection as follows:

Transmission Door 1, http://blog.csdn.net/mazhimazh/article/details/17759579

Transmission Door 2, http://blog.csdn.net/mazhimazh/article/details/17835467

Continue to look at the collection interface, the source code is as follows:

public
    Interface Collection<e> extends Iterable<e> {//lookup operation int size ();
    
    Iterator<e> iterator ();
    Judge Boolean IsEmpty ();
    Boolean contains (Object O);
    
    Boolean containsall (collection<?> c);
    Add boolean Add (e e);
    
    Boolean AddAll (collection< extends e> c);
    Delete Operation Boolean remove (Object O); Boolean RemoveAll (collection<?> c);//Removes all of this Collection ' s elements that are also contained in the SPECI
    Fied collection (optional operation). Boolean retainall (collection<?> c);//retains only the elements in this Collection that are contained in the Specifi
    Ed collection (optional operation).
    
    void Clear ();
    Set conversion object[] ToArray ();
    
    <T> t[] ToArray (t[] a);
    Provides Equals () and Hashcode () Boolean equals (Object O);
int hashcode (); }

The collection interface defines some basic operations for the collection, so any specific collection implementation class has these methods. However, because of the higher level of abstraction, so generally a specific set implementation class, such as ArrayList, HashMap, and so will not directly inherit this interface, but inherit the interface of some subclasses to implement. Therefore, the concrete implementation class of each set inherits this interface directly or indirectly.

There is one important way to explain:

    Boolean Add (e e);
    Boolean AddAll (collection< extends e> c);

    Boolean remove (Object o);
    Boolean RemoveAll (collection<?> c);
Take the Add (E E) method to illustrate that this method will add a new element to the collection. Method returns a Boolean, but the return value does not indicate whether the addition was successful or not. Carefully read Doc can see that collection stipulates that if a collection refuses to add this element, it must throw an exception for whatever reason. This return value represents the meaning of the Add () method after the execution of the contents of the collection has changed (that is, the element has no quantity, position, etc.), which is implemented by the specific class. That is, if the method fails, the exception is always thrown; the return value simply indicates that the content of the collection has changed since the method was executed.

It is found that many of the incoming parameters are collection<?> types, which facilitates the mutual operation of the specific implementation classes of each set. As an example:

                Linkedlist<string> list=new linkedlist<> ();
		
		List.add ("XY");
		List.add ("mn");
		
		Collection<string> ct=new hashset<string> ();
		Ct.add ("abc");
		Ct.add ("def");
		Ct.addall (list);
		
		Iterator<string> iter=ct.iterator ();
		while (Iter.hasnext ()) {
			System.out.println (Iter.next ());
		}
Adding elements from the LinkedList collection to HashSet requires only the AddAll () method to be invoked. The final result output is as follows:
Mn
Abc
Def
Xy






Reference documents:

1, Java source Analysis iterable http://wenku.baidu.com/view/d7a1788283d049649b6658b2.html

2. API documentation





Related Article

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.