Java 7 source code analysis 7th

Source: Internet
Author: User



Let's take a look at several questions:

1,

      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 mainly calls the unmodifiableSet () method of Collections, while

Public static void main (String args []) {List <String> list = new ArrayList (); list. add ("A"); list. add ("B"); list. add ("C"); list. add ("A"); // The element in the List can be repeated for (int I = 0; I <list. size (); I ++) System. out. print ("" + list. get (I); // a B C A // remove duplicate elements and keep the original element order 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 javashashset <e> (list ));}




In fact, the above two questions are not difficult, but they do not have a deeper understanding of the set. Let's take a rough look at the set. The inheritance class of the set is as follows.


It can be divided into three different sets: List, Set, and Map. There are also some auxiliary tool classes, such as Collections and Arrays. The comparison of each Set is shown in.


// Implementing this interface allows an object to be the target of  the "foreach" statement.public interface Iterable<T> {    Iterator<T> iterator();}

An iterator is defined in the interface. You can use the enhanced for loop (foreach) to traverse the set. The source code of the Iterator class is as follows:

/** * Iterator takes the place of Enumeration. Iterators differ from enumerations in two ways: * *      <li> Iterators allow the caller to remove elements from the *           underlying collection during the iteration with well-defined *           semantics. *      <li> Method names have been improved. */public interface Iterator<E> {    boolean hasNext();    E next();    /**     * Removes from the underlying collection the last element returned     * by this iterator (optional operation).       */    void remove();}

Continue to check the Collection interface. The source code is as follows:

Public interface Collection <E> extends Iterable <E >{// int size (); boolean isEmpty (); boolean contains (Object o); boolean containsAll (Collection <?> C); // add the boolean add (E e); boolean addAll (Collection <? Extends E> c); // Delete boolean remove (Object o); boolean removeAll (Collection <?> C); boolean retainAll (Collection <?> C); void clear (); // convert the set Iterator <E> iterator (); Object [] toArray (); <T> T [] toArray (T [] a); // provides equals () and hashCode () boolean equals (Object o); int hashCode ();}
This interface defines various operations for a set. It defines general operations for a Common set. However, because of the high abstraction level, it is generally a specific set implementation class, for example, ArrayList and HashMap do not directly inherit this interface, but inherit some subclasses of this interface for implementation. Therefore, the specific implementation classes of each set directly or indirectly inherit this interface.

4. List-dependent interfaces and abstract classes:


After searching for the Collection framework, we can see that the specific List implementation class inherits the AbstractCollection abstract class and implements the List interface. What operations are defined in the List interface?

Public interface List <E> extends Collection <E> {// Query Operations int size (); boolean isEmpty (); boolean contains (Object o ); iterator <E> iterator (); Object [] toArray (); <T> T [] toArray (T [] a); // Modification Operations boolean add (E ); boolean remove (Object o); // Bulk Modification Operations boolean containsAll (Collection <?> C); boolean addAll (Collection <? Extends E> c); boolean addAll (int index, Collection <? Extends E> c); boolean removeAll (Collection <?> C); boolean retainAll (Collection <?> C); void clear (); // Comparison and hashing boolean equals (Object o); int hashCode (); // Positional Access Operations // Returns the element at the specified position in this list. E get (int index); E set (int index, E element); // modify the element void add (int index, E element) at the specified position ); E remove (int index); // Search Operations int indexOf (Object o); int lastIndexOf (Object o); // List Iterators ListIterator <E> listIterator (); listIterator <E> listIterator (int index); // View List <E> subList (int fromIndex, int toIndex );}

Some of the above methods have been defined in Collection, which can be omitted here, just for clarity. At the same time, this interface also defines some more specific methods, these methods are set for the List type set. In this way, the Map set can inherit only the Collection, instead of the methods in the List set. Therefore, if the List set is used only in practical applications, you can use the List interface, because many methods defined for the List can be seen in this refined interface. If you are not sure about the Collection type, or you need to interoperate the List set with the Map set, you need to use the Collection interface.

The List traversal operation defines a more refined iteration interface, which inherits the Iterator interface, as follows:

public interface ListIterator<E> extends Iterator<E> {    // Query Operations    boolean hasNext();    E next();    boolean hasPrevious();    E previous();    int nextIndex();    int previousIndex();    void remove();    void set(E e);    void add(E e);}

This interface adds a number of traversal search methods for List sets. Use ListIterator in the List interface, similar to using Iterator in AbstractCollection.

/*** This class provides a skeletal implementation of the <tt> Collection </tt> * interface, to minimize the effort required to implement this interface. <p> */public abstract class AbstractCollection <E> implements Collection <E> {// protected type, so that the subclass can successfully call protected AbstractCollection () {} public abstract Iterator <E> iterator (); // defines the abstract method of an iterator. public abstract int size (); public boolean isEmpt Y () {return size () = 0;} public boolean contains (Object o) {Iterator <E> it = iterator (); if (o = null) {while (it. hasNext () if (it. next () = null) return true;} else {while (it. hasNext () if (o. equals (it. next () return true;} return false;} public boolean remove (Object o) {Iterator <E> it = iterator (); if (o = null) {while (it. hasNext () {if (it. next () = null) {it. remove (); return true ;}} Else {while (it. hasNext () {if (o. equals (it. next () {it. remove (); return true ;}}return false;} public Object [] toArray () {// Estimate size of array; be prepared to see more or fewer elements Object [] r = new Object [size ()]; Iterator <E> it = iterator (); for (int I = 0; I <r. length; I ++) {if (! It. hasNext () // fewer elements than expected return Arrays. copyOf (r, I); r [I] = it. next ();} return it. hasNext ()? FinishToArray (r, it): r;} public <T> T [] toArray (T [] a) {// Estimate size of array; be prepared to see more or fewer elements int size = size (); T [] r =. length> = size? A: (T []) java. lang. reflect. array. newInstance (. getClass (). getComponentType (), size); Iterator <E> it = iterator (); for (int I = 0; I <r. length; I ++) {if (! It. hasNext () {// fewer elements than expected if (! = R) return Arrays. copyOf (r, I); r [I] = null; // null-terminate return r;} r [I] = (T) it. next ();} return it. hasNext ()? FinishToArray (r, it): r;} // defines the maximum stack size of the allocated array to prevent overflow of private static final int MAX_ARRAY_SIZE = Integer. MAX_VALUE-8;/*** Reallocates the array being used within toArray when the iterator * returned more elements than expected, and finishes filling it from * the iterator. */private static <T> T [] finishToArray (T [] r, Iterator <?> It) {int I = r. length; while (it. hasNext () {int cap = r. length; if (I = cap) {int newCap = cap + (cap> 1) + 1; // overflow-conscious code if (newCap-MAX_ARRAY_SIZE> 0) newCap = hugeCapacity (cap + 1); r = Arrays. copyOf (r, newCap);} r [I ++] = (T) it. next ();} // trim if overallocated return (I = r. length )? R: Arrays. copyOf (r, I);} private static int hugeCapacity (int minCapacity) {if (minCapacity <0) // overflow throw new OutOfMemoryError ("Required array size too large "); return (minCapacity> MAX_ARRAY_SIZE )? Integer. MAX_VALUE: MAX_ARRAY_SIZE;} // Modification Operations // omitted... // String conversion/*** Returns a string representation of this collection. the string * representation consists of a list of the collection's elements in the * order they are returned by its iterator, enclosed in square brackets * ("[]"). adjacent elements are separated by the characters * "," (comma and space ). */publ Ic String toString () {Iterator <E> it = iterator (); if (! It. hasNext () return "[]"; StringBuilder sb = new StringBuilder (); sb. append ('['); for (;) {E = it. next (); sb. append (e = this? "(This Collection)": e); if (! It. hasNext () return sb. append (']'). toString (); sb. append (','). append ('');}}}
From the preceding two methods, the contains () and remove () methods show that if the specific subclass inherits the two methods, you can add
ArrayList aList = new ArrayList (); aList. add ("a"); aList. add ("B"); aList. add ("d"); aList. add (null); // ArrayList allows null value System. out. println (aList. size (); // 4 Iterator it = aList. listIterator (); while (it. hasNext () {System. out. println (it. next (); // a B d null}
We can see that in the ArrayList set

5. Set dependent interfaces and abstract classes:


The Set interface inherits Collection and defines some methods for the Set. You can see that the method defined in the List interface is the same.

public interface Set<E> extends Collection<E> {    // Query Operations    int size();    boolean isEmpty();    boolean contains(Object o);    Iterator<E> iterator();    Object[] toArray();    <T> T[] toArray(T[] a);    // Modification Operations        boolean add(E e);    boolean remove(Object o);    // Bulk Operations    boolean containsAll(Collection<?> c);    boolean addAll(Collection<? extends E> c);    boolean retainAll(Collection<?> c);    boolean removeAll(Collection<?> c);    void clear();    // Comparison and hashing    boolean equals(Object o);    int hashCode();}
The methods defined in the above interface are the same, but the implementation is different. However, the benefit of defining interfaces for lists, sets, and other sets is that if an operation for a specific Set has a special operation, you can only define the operation in this interface, other collections are not affected.

6. interfaces and abstract classes on which Map depends:



























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.