Java Container class Interface: Iterator,collection,map

Source: Internet
Author: User
Tags iterable set set

Iterator

Iterator, called an iterator, is an object whose work is to traverse and select the objects in the sequence, and you can do some of the following:

    • Using the method iterator () requires the container to return a iterator,iterator that returns the first element of the sequence;
    • Use Next () to get the next element in the sequence;
    • Use Hasnext () to check if there are elements in the sequence;
    • Use Remove () to delete the element that was recently returned by the iterator;

Iterator can only move forward, Listiterator is a more powerful subclass of iterator, it can only be used for access to a variety of list classes, listiterator to move in two directions, It can produce the index of the previous and subsequent elements in the list that the current iterator points to, and you can replace the last element that it accesses by using the set () method.

Iterator is an interface in the JDK, and in JDK8 its sub-interfaces contain

Listiterator <e>,

Primitiveiterator <t,t_cons>,

primitiveiterator.ofdouble , 

Primitiveiterator.ofint , 

Primitiveiterator.oflong , 

Xmleventreader

Iterator is defined as follows:

Public interface Iterator<e> {

Boolean hasnext (); Returns true if there are elements that can iterate

E next (); Returns the next element of an iteration

void Remove (); Removes the last element returned by an iterator from the collection that the iterator points to

}

Iterator usage Examples:

Importjava.util.ArrayList;ImportJava.util.Iterator; Public classIteratortest { Public Static voidPlay (iterator<string>it) {         while(It.hasnext ()) {System.out.println (It.next ()); }    }         Public Static voidMain (string[] args) {ArrayList<String> SS =NewArraylist<string>();  for(inti = 0; I < 7; i++) {Ss.add ("I:" +i);    } Play (Ss.iterator ()); }}

Listiterator allows you to traverse the list in any direction, modify the list during iteration, and get the position of the iterator in the list. The listiterator has no current element, and its cursor position is always located between the element returned by the call to previous and the element returned by the call next.

The Listiterator is implemented as follows:

Public interface Listiterator<e> extends iterator<e> {

Boolean hasnext (); Returns true if the iterator has multiple elements while it is traversing the list

E next (); Returns the next element in the list, which can be reused with the iteration list

Boolean hasprevious (); Returns true if the iterator has more than one element when traversing the list backwards

E Previous (); Returns the previous element in the list

int Nextindex (); Returns the index returned for subsequent calls to next

int Previousindex (); Returns the index returned to the previous call

void Remove (); Removes the last element returned by next or previous from the list

void Set (e e); Replaces the last element returned by next or previous with the specified element

void Add (e e); Inserts the specified element into the list

}

Listiterator Usage Examples:

Importjava.util.LinkedList;ImportJava.util.ListIterator; Public classListiteratortest { Public Static voidPlay (listiterator<string>it) {         while(It.hasnext ()) {System.out.print (It.next () )+ "" + it.nextindex () + "|"); } it.set ("xxxxxxx"); It.add ("Yyyyyyy");        System.out.println (); System.out.println (it.previous ()+ " " +It.next ());  while(It.hasprevious ()) {System.out.print (it.previous () )+ "" + it.previousindex () + "|"); }    }         Public Static voidMain (string[] args) {LinkedList<String> ls =NewLinkedlist<string>();  for(inti = 0; I < 5; i++) {Ls.add ("Aaaaaaa");    } Play (Ls.listiterator ()); }}
Collection

Collection is a generic root interface that describes all of the sequence containers, which can be used to create code that is generic and can be written by interfaces rather than by specific implementations, and if the method is written to accept a collection, the method accepts any class that implements the collection.

The collection interface inherits from Iterable, and in JDK8 its sub-interfaces contain

Beancontext , 

beancontextservices , 

Blockingdeque <e>,

Blockingqueue <e>,

Deque <e>,

List <e>,

Navigableset <e>,

Queue <e>,

Set <e>,

SortedSet <e>,

Transferqueue <E>

Collection is defined as follows

Public interface Collection<e> extends iterable<e> {

int size (); Returns the number of elements in a collection

Boolean isEmpty (); Returns true if collection does not contain elements

Boolean contains (Object O); Returns True if collection contains the specified element

Iterator<e> Iterator (); Returns an iterator for this collection

Object[] ToArray (); Returns an array of all the elements of this collection

<T> t[] ToArray (t[] a); Returns an array of all the elements of this collection

Boolean Add (e e); Make sure that this collection contains the specified element

Boolean remove (Object O); Removes the specified element from this collection

Boolean containsall (collection<?> c); True if the element containing the specified collection is returned

Boolean AddAll (collection<? extends e> c); To an element in the specified collectio

Boolean RemoveAll (collection<?> c); Removes the element of the specified collection

Boolean retainall (collection<?> c); Keep only the elements in the specified collection

void Clear (); Remove all elements from the collection

Boolean equals (Object O); Compares and specifies whether the object is equal

int hashcode (); Returns the hash value for this collection

}

Class Abstractcollection provides the most basic implementation of the collection interface, minimizing the effort to implement the collection interface. If you need to implement a new non-modifiable collection, you only need to extend the abstractcollection to provide the implementation of the iterator () and size () methods ( The iterator returned by the iterator method must implement Hasnext and next, and if you want to implement a modifiable collection, you must override the Add method, and the iterator returned by the iterator method must also implement the Remove method.

Collection specific implementations can be seen in later list,set,queue.

Map

Map:map<k, V> provides the interface for key-value mappings in Java, and K represents the type of key maintained by this mapping, and V represents the type of this mapping value. A map cannot contain duplicate keys, and each key can be mapped to at most one value. Map provides a collection of three collection views, key sets, value collections, and key-value mapping relationships.

Map<k, the v> sub-interface contains

Bindings , 

Concurrentmap <k,v>,

Concurrentnavigablemap <k,v>,

Logicalmessagecontext , 

Messagecontext , 

Navigablemap <k,v>,

Soapmessagecontext , 

SortedMap <K,V>

Map<k, v> is defined as follows, Map<k, v> contains a nested interface representing the key-value pairs of the mappings

Public interface Map<k,v> {

int size (); returns the number of key-value mapping relationships in this map

Boolean isEmpty (); returns true if this mapping does not contain a key-value mapping relationship

Boolean ContainsKey (Object key); returns true if this map contains a mapping relationship for the specified key

Boolean Containsvalue (Object value); returns true if this mapping maps one or more keys to the specified value

V get (Object key); returns the value mapped by the specified key, or null if the mapping does not contain a mapping relationship for the key

V Put (K key, v value); associates the specified value with the specified key in this map

V Remove (Object key); If there is a mapping relationship for a key, it is removed from this mapping

void Putall (map<? extends K,? extends v> m); Copy all mappings from the specified map to this map

void Clear (); Remove all mapping relationships from this map

Set<k> KeySet (); returns a Set view of the keys contained in this map

Collection<v> values (); returns a Collection view of the values contained in this map

Set<map.entry<k, v>> entryset (); returns a Set view of the mappings contained in this map

Interface Entry<k,v> {

K GetKey ();

V GetValue ();

V SetValue (v value);

Boolean equals (Object O);

int hashcode ();

}

Boolean equals (Object O); compares whether the specified object is equal to this mapping

int hashcode (); returns the hash code value for this mapping

}

Map<k, examples of use of v>

ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map;ImportJava.util.Set; Public classMaptest { Public Static voidMain (string[] args) {Map<string, string> map =NewHashmap<string, string>(); Map.put ("A", "AA"); Map.put ("B", "BB"); Map.put ("C", "CC"); Set Set=Map.entryset (); Iterator it=Set.iterator ();  while(It.hasnext ()) {Map.entry<string, string> me = (map.entry<string, string>) It.next (); System.out.println (Me.getkey ()+ " " +Me.getvalue ()); }    }}

Java Container class Interface: Iterator,collection,map

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.