1.JAVA Foundation--Arrays, sets 1

Source: Internet
Author: User
Tags comparable

1. Array declarations

int New int []{1,2,3}; int [] Score2 = {n/a}; int New int [3];

2. Collection

First, a logical diagram.

In Java, the collection container is divided into two categories: one is a single-valued collection, and the other is a map that stores key-value pairs.

  • Colleciton:collection is an interface that is used to represent any object or group of elements.
      • Collection interface Method (collection does not provide a GET method, to traverse collection must use iterator).
        1. Single element Add, delete operation: Boolean add (Object o); Boolean remove (Objcet O);
        2. Query operation: int size (), Boolean IsEmpty (), Boolean contains (Object o), Iterator Iterator ()//returns an iterator for accessing the elements of the collection;
        3. Group Operation: Boolean Containsall (Collection c); Boolean addall (Collection c); void clear (); void RemoveAll (Collection c); void Retainall (Collection C)//Removes the element not contained in set C from the collection, which is the intersection of the set C;
        4. Objcet array operation: object[] ToArray ()//Returns an array containing all the elements in the collection (must be an object, not a basic data type); object[] ToArray (object[] a)// Returns an array containing all the elements in the collection, where a represents an array that stores this collection element (if it is large enough), otherwise a new array with the same run-time type will be assigned;
    • Abstarctcollection Abstract class: This class is an abstract implementation class for the collection interface that provides the basic functionality of a concrete "collection framework" that provides implementations of methods other than iterator () and size (). However, the Abstarctcollection class will need to be re-implemented for the Add () method (the implementation of this method in Abstarctcollection is to throw the unsupportedoperationexception exception directly).
    • Iterator Interface: Collection returns a iterator (iterator) through the iterator () method. The interface iterates through each element of the collection individually and safely removes the appropriate element from the collection.
      • Note: "Security" here means (online explanation):Iterator is working in a separate thread, and has a mutex lock. Iterator is created after the creation of a single-chain index table pointing to the original object, when the original object number changes, the contents of the index table will not be synchronized changes, so when the index pointer moves back to find the object to iterate, so according to the Fail-fast principle (fault quick fix) Iterator will immediately throw the java.util.ConcurrentModificationException exception. So Iterator is not allowed to be changed by iterative objects while working. But you can delete the object using Iterator's own method, remove (), and the Iterator.remove () method maintains the consistency of the index while deleting the current iteration object. look at the following code:
         Public Static voidMain (string[] args) {Set<String> set =NewHashset<string>(); Set.add (A); Set.add ("B"); Set.add (C); Set.add ("D"); Iterator<String> iterator =Set.iterator (); /*it is normal to delete the following while loop.*/     while(Iterator.hasnext ()) {string string=(String) iterator.next (); if(String.endswith ("C") ) {iterator.remove (); }    }    /*the deletion in the for loop below will throw an exception*/    /*For (string string:set) {if (String.endswith ("C")) {Set.remove (string); }            }*/     for(String string:set) {System.out.println (string); }}
    • Listiterator interface: It integrates from the iterator interface to support adding or changing elements in the underlying collection, and also supports bidirectional access, which has no current position, and the cursor is between the values returned by the previous and next methods.
      • A few ways to Listiterator:
        • Object Previous (): Returns the previous object of the cursor, and moves the cursor one bit forward.
        • Object Next (): Returns an object after the cursor, and moves the cursor one bit behind. Because the cursor is between the two, successive calls to the next and previous methods return the same object.
        • void Add (Object O): Adds an element that is prepended to the current cursor, so after adding an element with ADD, the call to the previous () method returns the element that was just added, and the return value of the next method is not affected by the Add method.
        • void set (Object O): Sets the value of an element, which is the element returned after the previous call to the previous () or next () method. (Note: If the list structure has been modified since the last call, the IllegalStateException exception will be thrown.) )
           Public Static voidMain (string[] args) {List<String> list =NewArraylist<string>(); List.add (A); List.add ("B"); List.add (C); Listiterator<String> Listiterator =List.listiterator (); if(Listiterator.hasnext ()) {System.out.println (Listiterator.nextindex ());        System.out.println (Listiterator.next ());        System.out.println (Listiterator.nextindex ());        System.out.println (Listiterator.previous ());        System.out.println (Listiterator.nextindex ()); System.out.println ("----------------------");        System.out.println (Listiterator.next ()); Listiterator.set ("M");        System.out.println (Listiterator.previous ()); Listiterator.add (N);    System.out.println (Listiterator.previous ()); }}//the output is:0a1a0----------------------Amn
    • Abstractlist and Abstractsequentiallist Abstract classes: All are abstract implementation classes of the list that override the Equals () and Hashcode () methods to ensure that equal collections return the same hash code. In addition, Abstractlist and abstractsequentiallist implement the rest of the list methods, including the implementation of the iterator method.
    • Randomaccess interface: This is a feature interface that, when a collection implementation class implements the interface, indicates that the collection implementation class supports effective random access. Both the ArrayList and the vector classes implement the interface.
        • Note: JDK recommended for the list collection as much as possible to implement the Randomaccess interface, if the collection implements the interface, then when traversing the collection, try to use the for (int i = 0; i < size; i++) to traverse instead of using the iterator iterator. Conversely, if list is a sequence list, it is best to iterate with iterators. The JDK is very clear, in the list, especially huge size list of the traversal algorithm, to try to determine whether it belongs to randomaccess (such as ArrayList) or sequence List (such as LinkedList), Because the randomaccess list is suitable for the traversal algorithm, used in the sequence list on the difference is very large, the common practice is:
           if  (list instanceof   randomaccess) { for  ( int  m = 0; M < List.size (); M++}}  else  {Iterator iter  = List.iterator ();  while   (Iter.hasnext ()) {
          }}
    • Comparable interface and comparator interface: Two comparison interfaces in the collection framework.
      • The Java class that implements the comparable interface needs to implement the CompareTo (object o) method, which compares the order of the current object to the object o, returns a negative number if it precedes the object o, and returns 0 if the two objects are in the same position (note: 0 only represents the same location, element is not necessarily the same), if after O, a positive value is returned.
      • If a class is unable or inconvenient to implement the comparable interface, and to provide its own sort, the comparator interface can be implemented by itself, thus defining a comparator with compare (Object O1, Object2) and Equalse ( Object o) Two methods, the first method is used to compare O1 and O2 two object order, if O1 in front of the O2, then return a negative value, if the equality is returned 0 (note: 0 is the same position, the element is not necessarily the same), if the O1 is behind O2, a positive value is returned. The second Equalse method is used to compare whether an object o is equal to the comparer .
    • SortedSet Interface: A special collection interface that keeps an orderly ordering of elements (from low to high). Note: Here the order, not refers to the element entry sequence, but refers to the element after joining the class set, will be based on the comparable interface implementation of the CompareTo method or the comparator interface Comapre method to compare, according to the return result of the elements ordered arrangement. Specifically, the following code is visible:
       public  static  void   main (string[] args) {Set  <String> ts = new  treeset<string> ();    Ts.add ( "C" );    Ts.add ( "z" );    Ts.add ( "a" );    Ts.add ( "B" );    Ts.add ( "3" );  for   (String string:ts) {System.out.pri    Ntln (string); }}  //  output:  3abcz  

      Because elements need to be ordered, elements added to SortedSet must implement the comparable interface, otherwise the SortedSet interface implementation class must be constructed to provide an implementation of the comparator interface. For example, the only implementation class TreeSet for the SortedSet interface, which provides a construction method that contains the comparator interface:

       Public Super E> Comparator) {    this (new treemap<e,object>(Comparator));} 

      This interface provides access to a collection of views (subsets) and methods at both ends.

        • Comparator Comparator (): Returns the comparer when the element is sorted, or null if compared using the CompareTo method of the comparable interface

        • Object First (): returns one (lowest) element in an ordered collection.

        • Object last (): Returns the final (highest) element in an ordered collection.

        • SortedSet subset (Object fromelement, Object EndElement): Returns the Fromelement view (subset) of elements from endElement (including) to SortedSet (not included)

        • SortedSet HeadSet (Object toelement): Returns a view (subset) that includes all elements in the collection that are less than toelement.

        • SortedSet Tailset (Object fromelement): Returns a view (subset) that includes all elements in the collection that are greater than or equal to fromelement.
    • Abstractset Abstract class: This class overrides the Equals and Hashcode methods.
  • Map interface: The map interface is used to maintain a key/value pair that describes a key-to-value mapping that is never duplicated.
      • Map interface methods:
      1. Add Delete operation: Object put (object key, Object value)//If key already exists, overwrite old value and return old value, add and Return Null;object Remove (object key) if not present; void Putall (Map t); void clear ();(Note: Both the key and the value of the map can be null)
         Public Static void Main (string[] args) {    Mapnew hashmap<string, string>();    Map1.put ("A", "a");    MapNew hashmap<string, map>();    Map.put ("0", MAP1);    Map.put ("1", map);     = Map.get ("1");     = = map);    System.out.println (Neemap.get ("0"));

        Returns the result: True and {a=a}
        Description:map can add itself as a key or value to itself .

      2. Query operation: Object get (Object key)//If not found, returns Null;boolean ContainsKey (object key); Boolean Containsvalue (object value); int Size (); Boolean isEmpty ();
      3. View operation: Set KeySet ()//Returns the view set of all keys; Collection values ()//Returns the view set of all value; Set EntrySet ()//Returns the view set of the Map.entry object;Note: Developers can remove elements from all returned view sets, and Key/value in the corresponding source will be deleted, but elements cannot be added to the view set)
         Public Static voidMain (string[] args) {Map<string, string> map =NewHashmap<string, string>(); Map.put ("A", "1"); Map.put ("B", "2"); Map.put ("C", "3"); Set<entry<string, string>> set =Map.entryset (); Iterator<entry<string, string>> iterator =Set.iterator ();  while(Iterator.hasnext ()) {Entry<string, string> entry =Iterator.next (); if(Entry.getkey (). Equals ("B") ) {iterator.remove (); }    }     for(Entry<string, string>Entry:set) {System.out.println ("The key before the change is:" + entry.getkey () + "value:" +Entry.getvalue ()); Entry.setvalue (Entry.getvalue ()+ "~~"); System.out.println ("After the modified key is:" + entry.getkey () + "value:" +Entry.getvalue ()); }}//the output is:Before the modifier key is: C value is: 3after the modified key is: C value is:3~~the pre-modification key is: A value is:1after the modified key is: A value is:1~~
    • Map.entry interface: Map's EntrySet () method returns a collection of objects that implement the Map.entry interface, through which you can obtain a key or value for each entry (the only way to get it) and change the value. When an entry is returned through an iterator, unless it is the SetValue () method of the iterator's own remove () method or the entry returned by the iterator, the remainder of the modification to the source map will cause this set of entries to become invalid and the resulting entry behavior undefined.
    • SortedMap interface: The SortedMap interface is a special interface integrated from map, which is used to maintain the order of the keys. As with Sorterset, it is only comparing the key of the map.
    • Abstractmap abstract class: Similar to Abstractset, abstractlist, covers the Equals and Hashcode methods.
    • Weakhashmap class: weakhashmap is a special implementation of map that uses weakreference (weak references) to hold hash table keywords. In this way, when the mapped key is no longer referenced outside of the Weakhashmap, the garbage collector reclaims it, but it incorporates a weak reference to the object into a queue. The run of Weakhashmap will periodically check the queue to find the newly arrived weak application. When a weak reference arrives at the queue, it means that the keyword is no longer used by anyone, and it has been collected. Then Weakhashmap deletes the associated mappings.
      • (1) weakhashmap (): Build an empty weak hash map like
      • (2) Weakhashmap (Map T): Build a weak hash map image, and add all mappings in images T
      • (3) weakhashmap (int initialcapacity): Constructs an empty weak hash map with a specific capacity like
      • (4) weakhashmap (int Initialcapacity, float loadfactor): Constructs an empty weakly hash map like
    • with a specific capacity and load factor
    • Identityhashmap class: Identityhashmap is also a special implementation of map. In this class, the hash code for the keyword should not be computed by the hashcode () method, but should be computed by the System.identityhashcode method (even if the Hashcode method has been redefined). This is the method that Object.hashcode uses to calculate the hash code based on the memory address of the object. In addition, in order to compare individual objects, identityhashmap uses = = instead of the Equals method. In other words, different keyword objects, even if their contents are the same, are considered different objects. The Identityhashmap class can be used to implement object topology Transformations (Topology-preserving object graph transformations), such as implementing serialization or deep copies of objects, which requires a node table when converting "Keeps track of references to objects that have already been processed. Even if objects happen to be equal, the node table should not be considered equal. Another application is to maintain the proxy object. For example, the debugging tool wants to maintain a proxy object for each object during program debugging.
      Identityhashmap class is not the general meaning of the map implementation, its implementation intentionally violates the map interface requirements by the Equals method to compare objects of the Convention. This class only uses situations where it is rarely necessary to emphasize equivalence semantics.
      (1) Identityhashmap (): Constructs an empty all-in-one hash map image, the default expected maximum size is 21
      "Expected maximum size is the maximum number of key/value mappings expected by the image"
      (2) Identityhashmap (map m): Build an All-in-one hash map image and add all the mappings in the images m
      (3) identityhashmap (int expectedmaxsize): Constructs an empty hash map image with the desired maximum size. When you place a key/value mapping that exceeds the expected maximum size, the internal data structure grows and can sometimes be time-consuming.

1.JAVA Foundation--Arrays, sets 1

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.