Java Collections Framework Overview

Java collections

Java frame set includes two types of containers, one is a collection (Collection), a storage element in the set, the other is a view (the Map), stores key / value mapping. There are three types of seeds Collection interface, List, Set and Queue, and then the following are some of the abstract class, and finally the implementation class.

Interface: abstract data type represents a collection. For example Collection, List, Set, Queue, Map , these interfaces operate in a manner different set of objects.

Specific classes: specific implementation of a set of interfaces. Essentially, they are reusable data structure, for example: ArrayList, LinkedList, HashSet, HashMap .

Algorithms: Some useful computational objects that implement collection interfaces in the method of execution, such as: searching and sorting. Collections and Arrays provides an implementation of these algorithms.

Below is the Java Collections Framework "Java programming ideas" given by:

Marquee represents the interface; solid lines represent the specific type; with dotted outline arrow indicates a particular class implements an interface; the dotted line with solid arrow represents a class of objects indicated by the arrow may be generated;

 

 

Iterator (Iterator)

Iterator: iterator is an abstraction of "access to all the elements one by one," the operation. In fact, the integration of the relationship between the position of a set of objects, such as the direct successor .

When traversal sequence, the iterator always maintain a current element, and provides a mechanism to access the next element of the sequence , the first time "an element under Access" access operation will give the most original of the current element.

Thus, according to these descriptions, the iterator must have:

Boolean hasNext ()      // Check for remaining elements 
E GetNext ()           // Returns next element

1.Iterator Interface

Iterator interface is Java Util package provided in a iterator interface, the idea is by iterator method, each set can be returned to the customer and create an object that implements the Iterator interface, and the concept of the current position within the object store down.

It is defined as:

public  interface the Iterator <E> {
     Boolean the hasNext (); 
    E Next (); 
    void Remove ();   // removes the last element returned by the iterator 
}

For remove () operation should be noted that, after a call to remove (), this method can not be called again, unless another call next () method.

2.Iterable Interface

The Iterable interface returns an instance of the Iterator interface, the interface is provided to allow the container to have a different way to navigate, through inheritance Iterable interface Iterator can achieve a plurality of different classes, for example, the forward iteration, the iteration counter, random iteration and so on.

public interface Iterable<T> {
  Iterator<T> iterator();
}

3. reasons collections have achieved Iterable interface

The core interface methods 1.Iterator next () or hasNext () is dependent on the position of the current iteration of the iterator. If Collection Iterator interface directly implemented, inevitably lead to a data collection object contains the current iteration location (pointer). When the set is transferred between different methods, since the current iteration is not the preset position, the result next () method will become unpredictable. Unless a further interface to add Iterator reset () method, used to reset the position of the current iteration. But this instant, Collection only the existence of a current iteration position at the same time. The Iterable is not, each call returns an iterator from scratch count. Multiple iterators interfere with each other.

2. As mentioned above, so that the collection can be more flexible in an iterative manner.

4. enhanced for loop

When the compiler is used to see a reinforcement for loop Iterable object, it calls replaced with those of the loop iterator method for enhancing an Iterator to obtain the object, and then call its methods.

E.g:

public static <E> void print(Collection<E> collection){
    for(E item:collection){
        System.out.println(item);
    }
}

The compiler will be rewritten as:

public static <E> void print(Collection<E> collection){
    Iterator<E> it = collection.iterator();
    while (it.hasNext()){
        E item = it.next();
        System.out.println(item);
    }
}

Collection与Map

Collection abstract concept set, it stores a set of objects of the same type . The key interface (part) as follows:

public  interface Collection <E> the extends the Iterable <E> {
     int size ();               // returns the number of elements 
    Boolean isEmpty ();      // determine whether an empty 
    void Clear ();      // empty set of 
    Boolean the contains (E X);    / / is determined if a certain element 
    Boolean the Add (E X);     // add an element 
    Boolean remove (E X);    // remove an element of 
    the iterator <E> iterator ();    // returns an iterator 
    Object [] toArray ( );      // return a composed of these elements of the array of objects 
}

Map is one kind of container storing a set of entries , the entry form as a (key, value) of the composite object. The key interface (part) as follows:

public  interface the Map <K, V> {
     int size ();
     Boolean isEmpty ();
     void Clear ();
     Boolean containsKey (Object Key);    // determines if a certain key 
    Boolean containsValue (Object value);    // determines whether comprising an element 
    V GET (Object key);       // Get a key element corresponding to 
    V PUT (key K, V value);     // add a key-value pairs 
    V remove (Object key);     // key to remove a key corresponding to value 
    V replace (key K, V value);     // replace only when a key has a value corresponding to the value of the 
    Boolean replace (K key, oldValue V, V newValue);    // replaced with a new value, the old value corresponding to the absence of then add
}

Comparator与Comparable

1.Comparator Interface

Comparator interface is more can be achieved with interface to construct a comparator that defines the size of the instance of the class rules. Common method is to be provided to a ranking function sequence.

It is defined as:

public interface Comparator<T> {
    int compare(T o1, T o2);
    boolean equals(Object obj);
}

Notably, no objects have been achieved equals (Object obj) method, so that when the implement Comparator interface can be implemented only compare method does not implement the equals method.

2.Comparable Interface

Comparable can be seen as sort interface, any class that implements the Comparable interface supports sorting, which is called a "natural order." For example, a list of the class implements Comparable interface, you can use the Collections.sort (list) to sort the list.

It is defined as:

public interface Comparable<T>{
    int comparaTo(T o);
}

It is worth noting that the need to ensure that the results ComparaTo method and the equals method consistent, otherwise there will be some problems (when ordered sets or sorted map will be used with the natural ordering performance will exceed expectations, it is strange), and therefore recommended weight write the equals method .

After sum up, it can be seen as the Comparable interface "internal comparator" comparable class implements an interface, you can call direct sequencing method; Comparator interface and can be seen as "external comparator" when the class designers did not consider the class when sorting, the class may be bound Comparator interface, in order to achieve the sort.

One example:

import java.util.*;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        ArrayList<Person> list = new ArrayList<>();
        list.add(new Person("Ming",171));
        list.add(new Person("Hong", 165));
        list.add(new Person("Xi",165));
        list.add(new Person("Long",181));
        System.out.println(list);
        Collections.sort(list);            // Use natural ordering 
        System.out.println (List); 
        the Collections.sort (List, new new PersonComparator ());   // use an external sort comparator 
        System.out.println (List); 
    } 

    Private  static  class the Person the implements the Comparable < the Person> { 
        String name; 
        int Tall; 

        the Person (String name, int Tall) {
             the this .name = name;
             the this .tall = Tall; 
        } 

        public String toString () {
             return name + "-" +Tall; 
        } 

        @Override 
        public  int the compareTo (the Person Person) {     // for natural ordering interface sorted by name 
            return name.compareTo (PERSON.NAME); 
        } 

        Boolean equals (the Person Person) {    // override equals the rule 
            IF ( the this .name.equals (PERSON.NAME)) {
                 return  to true ; 
            } 
            return  to false ; 
        } 
    } 

    static  class PersonComparator the implements comparator <the Person> {   // achieve more interface, sorted according to the height 
        @Override
        public int compare(Person p1, Person p2) {
            return p1.tall - p2.tall;
        }
    }
}
//结果
[Ming-171, Hong-165, Xi-165, Long-181]
[Hong-165, Long-181, Ming-171, Xi-165]
[Hong-165, Xi-165, Ming-171, Long-181]

Collections

Collections collection operation to contain only static methods for the collection or return, comprising a set of multi-state operation of the algorithm. Some of the key API follows (parameters are shown):

public  class the Collections the extends Object {
     Boolean the addAll ();   // for the given set of elements added to the 
    Queue <T> asLifoQueue ();    // After Deque becomes advanced out Queue 
    int binarySearch ();           // binary search an object 
    xxx the checkedXxx ();      // return a dynamic view of the specified type xxx safety of 
    void copy ();    // the copy list to another list element so 
    Boolean disjiont ();    // determines whether the two sets intersect 
    xxx emptyxxx ();      // returns an empty set xxx 
    void fill ();       // filled with a given set of objects 
    int Frequency ();     //Returns a collection of elements equal to the specified number of objects 
    int indexOfSubList ();     // returns the starting position of the target list in the source list 
    int lastindexOfSubList ();     // Returns the end position of the target list in the source list 
    T max (); 
    T min (); 
    void reverse ();     // inverted set 
    void Rotate ();       // a specified distance set rotation 
    void shuffle ();     // scrambling set 
    void Sort ();        // ordered set 
    void the swap () ;       // exchange specified two elements 
    xxx synchronizedxxx ();         // return thread safe xxx 
    xxx unmodifiablexxx ();   // returns unmodifiable view xxx 
}

Arrays

Arrays include various methods for manipulating arrays and asList () method of the API is as follows (parameters are shown):

public  class Arrays, the extends Object { 
    List <T> asList (A T ...)      // given a list object creates 
    int binarySearch ();       // binary search certain value 
    int Compare ();     // lexicographically comparing two value 
    int compareUnsigned ();   // lexicographically compare two values, two values are considered unsigned 
    XXX copyOf ();        // element specifies the length of the array copies 
    XXX copyOfRange ();     // the appointed start position and length of array elements to copy 
    int mismatch the ();      // Find the first two arrays index mismatch 
    void parallelPrefix ();       // applied in parallel to all elements of a certain operation of the subarray 
    voidparallelSetAll ();     // use the generator function is provided in parallel to the sub-array of all the elements 
    void parallelSort ();    // parallel sorting 
    void Sort ();     // Sort 
    Spliterator <T> Spliterator ();    // Returns covering the specified array splitter 
    stream <T> stream ();    // return flow of the specified elements constituting the array 
    String toString ();
     Boolean the equals ();   // determines whether the two elements are equal 
    void Fill ();       // with the specified filling the array elements 
    int the hashCode ();
     Boolean deepEquals ();   // where deepxxx applied to nested arrays 
    int deepHashCode (); 
    String deepToString (); 
}

Subsequent to the implementation classes of the framework and the corresponding set of data structures.

Guess you like

Origin www.cnblogs.com/lht-record/p/11455578.html