Java se basics (Collection interface overview)

Source: Internet
Author: User

Java se basics (Collection interface overview)

The integration relationship of the Collection interface is shown in figure

1. Iterable APIs)
The iteratable Interface contains only one method and returns an iterator that iterates on a group of T-type elements:

public abstract Iterator
 
   iterator();
 

 

The method declaration of the Iterator interface is as follows:

 

Public interface Iterator
 
  
{Public abstract boolean hasNext (); // returns true public abstract next () if there are still elements that can be iterated; // returns the next element of the iteration}
 
2. Collection Interface
All common Collection implementation classes provide two constructor methods:
(1) Non-parameter constructor, used to create an empty collection;
(2) A constructor with single parameters of the Collection type is used to create a collection with the same elements as its parameters.
3. List Interface
(1) ordered collection (also called sequence). Users of this interface can precisely control the insert position of each element in the list.
(2) The list usually allows repeated elements. If the List itself allows null elements, they usually allow multiple null elements.
(3) The List interface provides a special Iterator ListIterator. In addition to allowing normal operations provided by the Iterator interface, it also allows element insertion and replacement and bidirectional access.
(4) partial List method
Public interface List
 
  
Extends Collection
  
   
{Iterator
   
    
Iterator (); // returns the iterator ListIterator that iterates over the elements in the list in the appropriate order
    
     
ListIterator (); // returns the list iterator for this list element (in the appropriate order ). ListIterator
     
      
ListIterator (int index); // returns the list iterator of the elements in the list (in the proper order), starting from the specified position in the List E set (int index, E element ); // Replace the element at the specified position in the list with the specified Element (optional) E get (int index); // return to the void add (int index, E element); // insert a specified element in the specified position of the List (optional) List
      
        SubList (int fromIndex, int toIndex) // return some views between fromIndex (included) and toIndex (excluded) specified in the list .}
      
     
    
   
  
 
4. About ListIterator Interface
(1) List iterator, which allows you to traverse the list in any direction, modify the list during iteration, and obtain the current position of the iterator in the list.
(2) ListIterator does not have the current element; its cursor position is always between the elements returned by calling previous () and those returned by calling next.
Element (0) Element (1) Element (2)... Element (n-1)
Cursor positions: ^
(3) The remove () and set (Object) methods are not defined based on the cursor position; they are defined based on the operation for the last element returned by calling next () or previous ().
(4) Some ListIterator Methods
Public interface ListIterator
  
   
Extends Iterator
   
    
{Boolean hasNext (); // returns trueboolean hasPrevious () if the list iterator contains multiple elements while traversing the list in a forward direction; // if the list is traversed in reverse direction, if the list iterator has multiple elements, true E next () is returned; // returns the next element E previous () in the list (); // return the previous element int nextIndex () in the list; // return the index int previusindex () of the elements returned for subsequent calls to next (); // return the index void add (E e) of the elements returned by subsequent calls to previous; // The new element is inserted before the implicit cursor: this element is directly inserted before the next element returned by next, or after the next element returned by previous, // subsequent calls to next are not affected, in addition, the new element void set (E) will be returned for subsequent calls to previous; // Replace the last element void remove () returned by next or previous with the specified element (); // remove the last element returned by next or previous from the list}
   
  
5. About the ArrayList class
(1) it can contain repeated elements, the value can be null, And the thread is not synchronized.
(2) Each ArrayList instance has a capacity. As elements are added to the ArrayList, the capacity automatically increases.
Before adding a large number of elements, the application can use the ensureCapacity operation to increase the capacity of the ArrayList instance. This can reduce the number of incremental redistribution.
(3) The thread synchronization of the ArrayList instance is generally done by synchronizing the objects encapsulated in the list;
If such an object does not exist, use the Collections. synchronizedList method to "Wrap" the list.
List list = Collections. synchronizedList (new ArrayList (...));
(4) ArrayList partial Method

 

 

Public void ensureCapacity (int minCapacity) {}// increase the capacity of this ArrayList instance to ensure that it can accommodate at least the number of elements specified by minCapacity. Public void add (int index, E element) {}// Insert the specified element into the specified position in this list public int indexOf (Object o) {} // returns the index of the specified element that appears for the first time in this list, or if this list does not contain elements, returns-1 protected void removeRange (int from, int) {} // remove all the elements in the list between fromIndex (included) and toIndex (excluded). public void trimToSize () {}// adjust the capacity of the ArrayList instance to the current size of the list. This operation is used to minimize the storage capacity of the ArrayList instance.
(5) For example:

 

Import java. util. arrayList; import java. util. iterator; import java. util. listIterator; public class MyArrayList {public static void main (String [] args) {ArrayList <Integer> arraylist = new ArrayList
  
   
(); // Create an ArrayList object. The default capacity is 10for (int I = 0; I <15; I ++) {// initialize the array list content arraylist. add (I);} Object [] arr = arraylist. toArray (); // get the arraylist content and store it in the array for (Object object: arr) {// traverse the array and output the System. out. print (int) object + "\ t");} System. out. println (); System. out. println (arraylist. size (); // query the number of arraylist elements at this time. System. out. println (arraylist. contains (15); // query whether an element arraylist is contained. add (5,-1); // Insert the element arraylist at the specified position. add (15); // Insert the System element at the end. out. println (arraylist. contains (15); // query whether an element arr = arraylist is contained. toArray (); // get the arraylist content and store it in the array for (Object object: arr) {// traverse the array and output the System. out. print (int) object + "\ t");} System. out. println (); arraylist. set (5, 1); // change the arraylist element at the specified position. remove (16); // remove the arraylist element from the specified position. remove (15); arraylist. remove (arraylist. lastIndexOf (1); Iterator
   
    
Iterator = arraylist. iterator (); // iterator traverses while (iterator. hasNext () {System. out. print (iterator. next () + "\ t");} System. out. println (); arraylist. trimToSize (); // adjust the capacity of this ArrayList instance to the current size of the List ListIterator
    
     
Listiterator = arraylist. listIterator (); // use ListIterator to traverse the System element. out. println (listiterator. hasPrevious (); while (listiterator. hasNext () {System. out. print (listiterator. next () + "\ t");} System. out. println (); while (listiterator. hasPrevious () {System. out. print (listiterator. previous () + "\ t");} System. out. println (); listiterator. next (); // Replace the listiterator element. next (); listiterator. set (-1); while (listiterator. hasPrevious () // the pointer returns to the listiterator header. previous (); while (listiterator. hasNext () // traverse System. out. print (listiterator. next () + "\ t"); System. out. println ();}}
    
   
  
6. Sort list class
(1) it can contain repeated elements, the value can be null, And the thread is not synchronized.
(2) In addition to implementing the List interface, the revoke List class also provides a unified naming method for get, remove, and insert elements at the beginning and end of the List.
These operations allow the link list to be used as a stack, queue, or dual-end queue
(3) The iterator returned by the iterator and listIterator methods of this type fails quickly: After the iterator is created, if the list is modified from the structure,
The iterator will throw ConcurrentModificationException unless it is modified in any way at any time through the remove or add method of the iterator.
(4) partial list method

 

 

Public void addFirst (E e) {}// Insert the specified element to the beginning of the list. Public void addLast (E e) {}// Add the specified element to the end of this list public E getFirst () {}// return the first public E getLast () {}// return the last public E removeFirst () element of this list () {}// remove and return the first public E removeLast () {}// remove and return the last public ListIterator in this list
  
   
ListIterator (int index) {}// returns the list Iterator of the elements in this list. The public Iterator starts from the specified position in the list.
   
    
DescendingIterator () {}// returns the iterator that iterates in reverse order on the elements of this double-end queue. The elements are returned in the order from the last to the first.
   
  
(5) For example:

 

Import java. util. Iterator; import java. util. shortlist; public class my‑list {public static void main (String [] args) {shortlist
  
   
Counter list = new counter list
   
    
(); // Create a link list object for (int I = 0; I <15; I ++) {// initialize the linked list. add (I);} Iterator iterator = Consumer list. iterator (); // gets the iterator and traverses the link list while (iterator. hasNext () {System. out. print (iterator. next () + "\ t");} System. out. println (); returns list. addFirst (15); // Add the System element at the beginning. out. println (listing list. removeLast (); // Delete the iterator = shortlist element at the end. iterator (); // gets the iterator and traverses the link list while (iterator. hasNext () {System. out. print (iterator. next () + "\ t");} System. out. println (); Iterator descendingiterator = shortlist. descendingIterator (); // obtain the reverse iterator while (descendingiterator. hasNext () System. out. print (descendingiterator. next () + "\ t"); System. out. println ();}}
   
  
7. Set Interface
(1) does not contain duplicate elements. It can contain up to one null element.
(2) interface declaration (Part ):

 

Public interface Set
  
   
Extends Collection
   
    
{Iterator
    
     
Iterator (); // return the int size () iterator for iteration on the elements in this set; // return the number of elements in the set}
    
   
  
8. HashSet class
(1) does not contain repeated elements, a null value is allowed, and threads are not synchronized.
(2) This type is supported by HashMap instances, and the iteration sequence is not guaranteed to remain unchanged.
(3) Some Methods
Public boolean add (E e) {}// if this set does not contain the specified element, add the specified Element public Iterator.
  
   
Iterator () {}// returns the public boolean remove (Object o) {}// iterator that iterates on the elements in this set. If the specified element exists in this set, it is removed.
  

 

(4) For example:

 
Import java. util. HashSet; import java. util. Iterator; public class MyHashSet {public static void main (String [] args) {HashSet
  
   
Hashset = new HashSet
   
    
(); // Create a hash collection class object for (int I = 0; I <15; I ++) // Add the hashset element. add (I); hashset. add (null); Iterator iterator = hashset. iterator (); // get iterator, traverse hashsetwhile (iterator. hasNext () System. out. print (iterator. next () + "\ t"); System. out. println (); System. out. println (hashset. size (); // returns the number of elements in the set. System. out. println (hashset. contains (10); // test the System set. out. println (hashset. add (10); // add the repeating element System. out. println (hashset. add (15); // add the non-repeating element System. out. println (hashset. remove (0); // remove the existing element System. out. println (hashset. remove (0); // remove the Nonexistent element iterator = hashset. iterator (); // get iterator, traverse hashsetwhile (iterator. hasNext () System. out. print (iterator. next () + "\ t"); System. out. println (); System. out. println (hashset. isEmpty (); hashset. clear (); // clear the set System. out. println (hashset. isEmpty ());}}
   
  
9. SortedSet Interface
(1) The element cannot be null.
(2) elements are sorted in the natural order, or based on the Comparator provided when an ordered set is created. The set iterator traverses the set in ascending order of elements.
(3) All elements inserted into an ordered set must implement the Comparable interface, and all these elements must be Comparable to each other.
(4) All sorted set implementation classes should provide four constructor methods:
1) The parameter-free constructor creates an empty sorted set and sorts the elements in the natural order.
2) constructor with a Comparator type parameter. It creates an empty sorted set and sorts it according to the specified Comparator.
3) The constructor with a Collection type parameter creates a new ordered set, whose element is the same as the parameter and is sorted in the natural order of the elements.
4) A constructor with a SortedSet type parameter creates a new ordered set. Its elements and sorting methods are the same as the input ordered set.
(5) Some Methods
Comparator
  Comparator (); // returns the comparator for sorting the elements in this set; if this set uses the natural sequence of its elements, it returns nullE first (); // returns the current first (lowest) element E last () in this set; // returns the current last (highest) element SortedSet in this set
  
   
SubSet (E from, E to); // return some views of this set, whose elements are from (included) to (excluded) SortedSet
   
    
HeadSet (E toElement); // returns some views of this set, and its elements are strictly less than toElementSortedSet
    
     
TailSet (E fromElement); // return some views of this set. The element is greater than or equal to fromElement.
    
   
  
10. TreeSet class
(1) does not contain repeated elements, does not allow null, and threads are not synchronized
(2) sort the elements in the natural order of the elements, or sort the elements based on the Comparator provided when the set is created. The elements must be comparable depending on the construction method used.
(3) This implementation provides guaranteed log (n) time overhead for basic operations (add, remove, and contains ).
(4) Some Methods
Public class TreeSet
  
   
Extends AbstractSet
   
    
Implements NavigableSet
    
     
, Cloneable, Serializable {public TreeSet () {}// construct a new empty set. The set is sorted by the natural order of its elements.
     Comparator) {}// construct a new empty TreeSet, which sorts public TreeSet (Collection
     C) {}// construct a new TreeSet containing the specified collection element. It sorts the elements in the natural order. public TreeSet (SortedSet
     
      
S) {}// construct a new TreeSetE ceiling (E e) with the same ing relationship and same sorting as the specified Ordered set) {} // returns the smallest element> = e in this set; if such element does not exist, returns nullE floor (E) {} // returns the maximum element of <= e in this set. If such element does not exist, nullE higher (E) is returned) {}// return the smallest element of> e in this set; if such element does not exist, return nullE lower (E) {}// return in this set
      
       
Comparator () {}// returns the comparator for sorting the elements in this set. If this set uses the natural sequence of its elements, the nullIterator is returned.
       
         Iterator () {}// the Iterator that returns the elements in this set in ascending order.
        
          DescendingIterator () {}// return the iterator that iterates in descending order on this set element}
        
       
      
     
    
   
  
(5) For example:

 

/* Example 1 */import java. util. iterator; import java. util. random; import java. util. treeSet; public class MyTreeSet {public static void main (String [] args) {TreeSet
  
   
Treeset = new TreeSet
   
    
(); // Create the tree set object Random r = new Random (); for (int I = 0; I <15; I ++) // Add the element treeset. add (r. nextInt (50); Iterator
    
     
Iterator = treeset. iterator (); // get iterator, forward traversing element while (iterator. hasNext () System. out. print (iterator. next () + "\ t"); System. out. println (); Iterator
     
      
Desciterator = treeset. descendingIterator (); // gets the iterator and reversely traverses the element while (desciterator. hasNext () System. out. print (desciterator. next () + "\ t"); System. out. println () ;}/ * Example 2 */public class Person {private int number = 0; private int age = 0; public Person (int number, int age) {this. number = number; this. age = age;} public int getAge () {return age;} public int getNumber () {return number;} @ Overridepublic String toString () {return "[" + this. number + "," + this. age + "]" ;}} import java. util. comparator; import java. util. iterator; import java. util. treeSet; import java. util. random; public class TreeSetCom implements Comparator
      
       
{Public static void main (String [] args) {TreeSet
       
         Treeset = new TreeSet
        
          (New TreeSetCom (); // create the tree set Random age = new Random (); Random num = new Random (); for (int I = 0; I <15; I ++) // Add the element treeset. add (new Person (num. nextInt (30), age. nextInt (20); Iterator
         
           Iterator = treeset. iterator (); // gets the iterator and traverses the element while (iterator. hasNext () System. out. print (iterator. next (). toString () + "--"); System. out. println () ;}@ Overridepublic int compare (Person arg0, Person arg1) {return arg0.getAge ()-arg1.getAge () ;}/ * @ Overridepublic int compare (Person arg0, Person arg1) {return arg0.getNumber ()-arg1.getNumber ();}*/}
         
        
       
      
     
    
   
  
11. Vector
(1) Allow repetition, allow null, thread synchronization
(2) array-based
(3) The Enumeration returned by the elements method of Vector is not a quick failure.
(4) If the increment of capacity is less than or equal to zero, the vector capacity will increase by a factor every time the capacity needs to be increased.
(5) Some Methods
Public class Vector
  
   
Extends actlist
   
    
Implements List
    
     
, RandomAccess, Cloneable, Serializable {public Vector () {}// construct an empty Vector so that the size of its internal data array is 10, its standard capacity increment is zero public Vector (int initialCapacity) {}// uses the specified initial capacity and capacity increment equal to zero to construct an empty Vector public Vector (int initialCapacity, int capacityIncrement) {}// use the specified initial capacity and capacity increment to construct an empty vector public void ensureCapacity (int minCapacity) {}// increase the capacity of this vector, to ensure that it can at least save the number of components specified by the minimum capacity parameter public void setSize (int newSize) {}// set the size of this vector. If the new size is greater than the current size, the corresponding number of null items will be added at the end of the vector; // if the new size is smaller than the current size, the public Enumeration of all items at and after the index newSize is discarded.
     
      
Elements () {}// returns the enumeration of components of this vector. The returned Enumeration object will generate all the items in this vector. The first item is the items at index 0, and then the items at Index 1... public void addElement (E obj) {}// Add the specified component to the end of the vector and increase its size by 1. If the vector size and capacity are large, the public E get (int index) {}// the element public E set (int index, E element) at the specified position in the return vector is increased) // Replace the element protected void removeRange (int from, int to) {} with the specified Element in the specified position in this vector. // remove its index from this List in from (including) all elements between and to (not included}
     
    
   
  
(6) For example:

 

Import java. util. enumeration; import java. util. vector; import java. util. iterator; import java. util. random; public class MyVector {public static void main (String [] args) {Vector
  
   
Vector = new Vector
   
    
(); // Create a parameter-Free vector object Random r = new Random (); // initialize the vector object for (int I = 0; I <9; I ++) vector. add (r. nextInt (30); Iterator
    
     
Iterator = vector. iterator (); // get iterator, traverse vector while (iterator. hasNext () System. out. print (iterator. next () + "\ t"); System. out. println (); Enumeration
     
      
Enumeration = vector. elements (); // obtains the enumeration of the vector component, traversing the vector while (enumeration. hasMoreElements () System. out. print (enumeration. nextElement () + "\ t"); System. out. println (); System. out. println (vector. size (); // The Operation System on vector capacity. out. println (vector. capacity (); vector. setSize (12); System. out. println (vector. size (); vector. trimToSize (); System. out. println (vector. capacity (); vector. addElement (null); vector. add (10, 9); vector. add (13); iterator = vector. iterator (); // get iterator, traverse vector while (iterator. hasNext () System. out. print (iterator. next () + "\ t"); System. out. println (); System. out. println (vector. capacity (); System. out. println (vector. size ());}}
     
    
   
  
12. Stack
(1) The Stack class indicates the Stack, extends the class Vector, and provides push and pop operations.
(2) Some Methods
Public class Stack
  
   
Extends Vector
   
    
{Public Stack () {}// create an empty Stack public E push (E item) {}// press the item to the top of the Stack public E pop () {}// remove the object at the top of the stack and return this object public E peek () {}// view the object at the top of the stack as the value of this function, but do not remove the public int search (Object o) {}// position of the Object from the stack to the top of the stack, which is based on 1; returned value-1 indicates that this object is not in the stack public boolean empty () {}// test whether the stack is empty}
   
  
(3) For example:

 

Import java. util. Stack; import java. util. Iterator; public class MyStack {public static void main (String [] args) {Stack
  
   
Stack = new Stack
   
    
(); // Create a stack for (int I = 0; I <11; I ++) // initialize the stack. add (I); Iterator iterator = stack. iterator (); // get iterator, traverse stack while (iterator. hasNext () System. out. print (iterator. next () + "\ t"); System. out. println (); System. out. println (stack. search (4); // The distance from the query element to the top of the stack is System. out. println (stack. search (15); System. out. println (stack. capacity (); System. out. println (stack. size (); System. out. println (stack. push (10); // push D popSystem. out. println (stack. push (11); iterator = stack. iterator (); // get iterator, traverse stack while (iterator. hasNext () System. out. print (iterator. next () + "\ t"); System. out. println (); System. out. println (stack. peek (); System. out. println (stack. pop (); iterator = stack. iterator (); // get iterator, traverse stack while (iterator. hasNext () System. out. print (iterator. next () + "\ t"); System. out. println (); while (! Stack. isEmpty () // stack System. out. print (stack. pop () + "\ t"); System. out. println ();}}
   
  

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.