Java Collection Cases

Source: Internet
Author: User

Reprinted please indicate the source: http://blog.csdn.net/droyon/article/details/22781533

The Collection interface represents a group of objects, which are also elements of the Collection. Some Collection interfaces allow repeated elements, while others do not. Some Collection interfaces are ordered, while others are disordered.

Duplicate: two objects are equal by equals. (Equals subclass objects can be rewritten)

Order: The order in which elements are stored is the same as that in which elements are retrieved.

The set interface stores unordered elements and does not contain repeated elements. Elements stored in the List interface are ordered and repeat is allowed.




<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHByZSBjbGFzcz0 = "brush: java;"> import java. util. collections; import java. util. comparator; import java. util. hashSet; import java. util. iterator; import java. util. linkedHashSet; import java. util. set; import java. util. treeSet; import java. util. concurrent. atomic. atomicInteger;/*** when a Set interface is implemented for a container to store objects, a fixed algorithm is used to calculate its storage index based on the hash code value of each object (obtained by calling the hashCode method, * store the object in the corresponding location of the hash list. If there are no other elements in this location, you only need to store them directly. If there are other elements in the position, * compares the new element with the [all] object in the position (calls equals) to check whether the object has been saved in the container, if the object does not exist, * stores the object. If the object already exists, use the [Existing] object directly. * @ Author wanghl ** [Set elements cannot be repeated] * [List elements can be repeated] ** [hasCode hash:] * If a container has 100 elements, when adding an element, You need to perform the equals Method 100 times to determine whether the element is repeated. If you need to execute equals every time you add an element, when there are many elements, the number of times the elements added to the set are compared is very large, which greatly reduces the efficiency. Therefore, java * adopts the hash table principle. The hash algorithm also becomes a hash algorithm, which directly specifies the data to an address based on a specific algorithm (we temporarily use the hasCode value as an index of the physical * address of the object storage, do not care about algorithm computing for the moment ). Then, when adding a new element, first check whether the location has been saved to the object through the hasCode index. If it does not exist, directly store * The new element in this location without calling the equals method. If an object already exists, the equals method is called for comparison. If the same method is used, the existing element is directly used. If different methods are used, the other addresses are hashed. In this way, the number of equals method calls is greatly reduced. * [Two objects are the same, so their hasCode must be the same, hasCode is the same, and the two objects are not necessarily the same] * [Objects saved to the Set, you may not call the equals method] */public class SetTest {public static void main (String args []) {/*** HashSet is one of the Set interface implementation classes, you can use the hash value to store it, so you can quickly find it. * [HashSet does not save the sequence of elements added to the container] */HashSet Set1 = new HashSet (); System. out. println ("------------------------ influence of hasCode and equals on the Set interface implementation class");/*** the output is: * p ---> 12Persion1 @ 01 * p ---> 12Persion1 @ 02 * Set count is: 1 * Persion1 object: 12Persion1 @ 01 * [verification:] set interface, if the hasCode and equals of the two elements are the same, the object exists and the existing object is used directly without overwriting ]. */Persion1 pa1 = new Persion1 (12); Persion1 pa2 = new Persion1 (12); System. out. println ("p --->" + pa1); System. out. println ("p --->" + pa2); set1.add (pa1); set1.add (pa2); System. out. println ("Set count is:" + set1.size (); for (Persion1 p: set1) {System. out. println ("Persion1 object:" + p);} System. out. println ("-------------------------------------"); // ---------------------------------------------/*** [Note:] Persion1 and Persio N2, which is only different from the equals method. * [Print:] * p ---> 12Persion2 @ 01 * p ---> 12Persion2 @ 02 * Set count is: 2 * Persion2 object: 12Persion2 @ 02 * Persion2 object: 12Persion2 @ 01 * [Note:] * the following two objects are stored in the index calculated by the same hasCode. Because equals is different, they can be stored. */HashSet Set2 = new HashSet (); Persion2 pb1 = new Persion2 (12); Persion2 PBS = new Persion2 (12); System. out. println ("p --->" + pb1); System. out. println ("p --->" + master); set2.add (pb1); set2.add (master); System. out. println ("Set count is:" + set2.size (); for (Persion2 p: set2) {System. out. println ("Persion2 object:" + p);} System. out. println ("-------------------------------------"); // ---------------------------------------------/*** output is unnecessary. * [Print:] * p ----> 44Persion1 @ 06 * p ----> 33Persion1 @ 05 * p ----> 22Persion1 @ 04 * p ----> 11Persion1 @ 03 * p ----> better * p ----> best * p ----> good */HashSet set3 = new HashSet (); persion1 pc1 = new Persion1 (11); Persion1 pc2 = new Persion1 (22); Persion1 pc3 = new Persion1 (33); Persion1 pc4 = new Persion1 (44 ); set3.add (pc1); set3.add (pc2); set3.add (pc3); set3.add (pc4); set3.add ("good"); set3.add ("better "); set3.add ("best"); Iterator Iterator = set3.iterator (); while (iterator. hasNext () {Object p = iterator. next (); System. out. println ("p ---->" + p + ", hasCode is:" + p. hashCode ();} System. out. println ("************************************* ********"); // -------------------------------------------/*** the hashset is stored Based on the hash code, and the sequence of elements added to the linked list is recorded. * Objects are stored through a linked list, which generally results in high insertion and deletion efficiency and low retrieval efficiency. */Define hashset into set = new LinkedHashSet ();/*** add sequence hashset record elements * print: * p ***> is: 55Persion1 @ 07, hasCode is: 0 * p ***> is: 66Persion1 @ 08, hasCode is: 0 * p ***> is: 77Persion1 @ 09, hasCode is: 0 * p ***> is: 88Persion1 @ 010, hasCode is: 0 * p ***> is: aaaa, hasCode is: 2986048 * p ***> is: bbbb, hasCode is: 3016832 * p ***> is: cccc, hasCode is: 3047616 */Persion1 pd1 = new Persion1 (55); Persion1 pd2 = new Persion1 (66); Persion1 pd3 = new Persion1 (77); Persion1 pd4 = new Persion1 (88); sorted set. add (pd1); sorted set. add (pd2); sorted set. add (pd3); sorted set. add (pd4); sorted set. add ("aaaa"); sorted set. add ("bbbb"); sorted set. add ("cccc"); for (Object p: sorted set) {System. out. println ("p ***> is:" + p + ", hasCode is:" + p. hashCode ();} System. out. println ("---------------------------------------");//----------------------------- --------------/*** If multiple objects of different types are added to the TreeSet, an exception is reported. * For a custom class, only one object can be stored, and the Implementation class does not need to implement the [Comparable interface ]. * However, if you want to store objects of multiple custom classes, * if you do not implement the Comparable interface, a java. lang. ClassCastException occurs. */Set treeSet = new TreeSet (); Persion1 pe1 = new Persion1 (12); treeSet. add (pe1);/* treeSet. add (new String ("hello"); */Iterator itor = treeSet. iterator (); while (itor. hasNext () {System. out. println ("TreeSet p is:" + itor. next ();} System. out. println ("-----------------------------------"); // combine/*** Set sorting ** Persion3 implements the sorting interface Comparable * p ***> is: 0Persion3 @ 07, hasCode is: 0 * p ***> is: 1Persion3 @ 01, hasCode is: 0 * p ***> is: 2Persion3 @ 03, hasCode is: 0 * p ***> is: 4Persion3 @ 06, hasCode is: 0 * p ***> is: 5Persion3 @ 04, hasCode is: 0 * p ***> is: 8Persion3 @ 02, hasCode is: 0 * p ***> is: 9Persion3 @ 05, hasCode is: 0 * sort by Age */Set SortSet = new TreeSet (); Persion3 pf1 = new Persion3 (1); Persion3 pf2 = new Persion3 (8); Persion3 pf3 = new Persion3 (2); Persion3 pf4 = new Persion3 (5 ); persion3 pf5 = new Persion3 (9); Persion3 pf6 = new Persion3 (4); Persion3 pf7 = new Persion3 (0); sortSet. add (pf1); sortSet. add (pf2); sortSet. add (pf3); sortSet. add (pf4); sortSet. add (pf5); sortSet. add (pf6); sortSet. add (pf7); for (Persion3 p: sortSet) {System. out. println ("p ***> is:" + p + ", hasCode is:" + p. hashCode ();} System. out. println ("-----------------------------------");/*** Set sorting: sort by [sorter] Comparetor * print: * p ***> is: 1Persion3 @ 01, hasCode is: 0 * p ***> is: 8Persion3 @ 02, hasCode is: 0 * p ***> is: 2Persion3 @ 03, hasCode is: 0 * p ***> is: 5Persion3 @ 04, hasCode is: 0 * p ***> is: 9Persion3 @ 05, hasCode is: 0 * p ***> is: 4Persion3 @ 06, hasCode is: 0 * p ***> is: 0Persion3 @ 07, hasCode is: 0 * sort by index */TreeSet SortSetByComparator = new TreeSet (New ComparetorByIndex (); sortSetByComparator. add (pf1); sortSetByComparator. add (pf2); sortSetByComparator. add (pf3); sortSetByComparator. add (pf4); sortSetByComparator. add (pf5); sortSetByComparator. add (pf6); sortSetByComparator. add (pf7); for (Persion3 p: sortSetByComparator) {System. out. println ("p ***> is:" + p + ", hasCode is:" + p. hashCode ();} System. out. println ("---------------------------------------") ;}} class Pe Rsion1 {public int mAge; private static AtomicInteger atIndex = new AtomicInteger (); // atomic type public int index; public Persion1 (int age) {mAge = age; index = atIndex. addAndGet (1) ;}@ Overridepublic int hashCode () {return 0 ;}@ Overridepublic String toString () {return mAge + "" + super. toString () + index ;}@ Overridepublic boolean equals (Object arg0) {if (arg0 instanceof Persion1) {Persion1 p = (Persion1) arg0; return mAge = P. mAge;} return super. equals (arg0) ;}} class Persion2 {public int mAge; private static AtomicInteger atIndex = new AtomicInteger (); // atomic type public int index; public Persion2 (int age) {mAge = age; index = atIndex. addAndGet (1) ;}@ Overridepublic int hashCode () {return 0 ;}@ Overridepublic String toString () {return mAge + "" + super. toString () + index ;}@ Overridepublic boolean equals (Object arg0) {if (arg0 instanceof P Ersion2) {Persion2 p = (Persion2) arg0; return mAge! = P. mAge;} return super. equals (arg0) ;}} class Persion3 implements Comparable {Public int mAge; private static AtomicInteger atIndex = new AtomicInteger (); // atomic type public int index; public Persion3 (int age) {mAge = age; index = atIndex. addAndGet (1) ;}@ Overridepublic int hashCode () {return 0 ;}@ Overridepublic String toString () {return mAge + "" + super. toString () + index ;}@ Overridepublic boolean equals (Object arg0) {if (arg0 instanceof Persion3) {Persion3 p = (Persion3) arg0; return mAge! = P. mAge;} return super. equals (arg0) ;}@ Overridepublic int compareTo (Persion3 p) {return mAge-p. mAge ;}} class ComparetorByAge implements Comparator {@ Overridepublic int compare (Persion3 p0, Persion3 p1) {return extends Mage-p1.mAge ;}} class ComparetorByIndex implements Comparator {@ Overridepublic int compare (Persion3 p0, Persion3 p1) {return partial index-p1.index ;}}

The Collection interface represents a group of objects, which are also elements of the Collection. Some Collection interfaces allow repeated elements, while others do not. Some Collection interfaces are ordered, while others are disordered.

Duplicate: two objects are equal by equals. (Equals subclass objects can be rewritten)

Order: The order in which elements are stored is the same as that in which elements are retrieved.

The set interface stores unordered elements and does not contain repeated elements. Elements stored in the List interface are ordered and repeat is allowed.

Import java. util. collections; import java. util. comparator; import java. util. hashSet; import java. util. iterator; import java. util. linkedHashSet; import java. util. set; import java. util. treeSet; import java. util. concurrent. atomic. atomicInteger;/*** when a Set interface is implemented for a container to store objects, a fixed algorithm is used to calculate its storage index based on the hash code value of each object (obtained by calling the hashCode method, * store the object in the corresponding location of the hash list. If there are no other elements in this location, you only need to store them directly. If there are other elements in the position, * compares the new element with the [all] object in the position (calls equals) to check whether the object has been saved in the container, if the object does not exist, * stores the object. If the object already exists, use the [Existing] object directly. * @ Author wanghl ** [Set elements cannot be repeated] * [List elements can be repeated] ** [hasCode hash:] * If a container has 100 elements, when adding an element, You need to perform the equals Method 100 times to determine whether the element is repeated. If you need to execute equals every time you add an element, when there are many elements, the number of times the elements added to the set are compared is very large, which greatly reduces the efficiency. Therefore, java * adopts the hash table principle. The hash algorithm also becomes a hash algorithm, which directly specifies the data to an address based on a specific algorithm (we temporarily use the hasCode value as an index of the physical * address of the object storage, do not care about algorithm computing for the moment ). Then, when adding a new element, first check whether the location has been saved to the object through the hasCode index. If it does not exist, directly store * The new element in this location without calling the equals method. If an object already exists, the equals method is called for comparison. If the same method is used, the existing element is directly used. If different methods are used, the other addresses are hashed. In this way, the number of equals method calls is greatly reduced. * [Two objects are the same, so their hasCode must be the same, hasCode is the same, and the two objects are not necessarily the same] * [Objects saved to the Set, you may not call the equals method] */public class SetTest {public static void main (String args []) {/*** HashSet is one of the Set interface implementation classes, you can use the hash value to store it, so you can quickly find it. * [HashSet does not save the sequence of elements added to the container] */HashSet
 
  
Set1 = new HashSet
  
   
(); System. out. println ("------------------------ influence of hasCode and equals on the Set interface implementation class");/*** the output is: * p ---> 12Persion1 @ 01 * p ---> 12Persion1 @ 02 * Set count is: 1 * Persion1 object: 12Persion1 @ 01 * [verification:] set interface, if the hasCode and equals of the two elements are the same, the object exists and the existing object is used directly without overwriting ]. */Persion1 pa1 = new Persion1 (12); Persion1 pa2 = new Persion1 (12); System. out. println ("p --->" + pa1); System. out. println ("p --->" + pa2); set1.add (pa1); set1.add (pa2); System. out. println ("Set count is:" + set1.size (); for (Persion1 p: set1) {System. out. println ("Persion1 object:" + p);} System. out. println ("-------------------------------------"); // ---------------------------------------------/*** [Note:] Persion1 and Persio N2, which is only different from the equals method. * [Print:] * p ---> 12Persion2 @ 01 * p ---> 12Persion2 @ 02 * Set count is: 2 * Persion2 object: 12Persion2 @ 02 * Persion2 object: 12Persion2 @ 01 * [Note:] * the following two objects are stored in the index calculated by the same hasCode. Because equals is different, they can be stored. */HashSet
   
    
Set2 = new HashSet
    
     
(); Persion2 pb1 = new Persion2 (12); Persion2 PBS = new Persion2 (12); System. out. println ("p --->" + pb1); System. out. println ("p --->" + master); set2.add (pb1); set2.add (master); System. out. println ("Set count is:" + set2.size (); for (Persion2 p: set2) {System. out. println ("Persion2 object:" + p);} System. out. println ("-------------------------------------"); // ---------------------------------------------/*** output is unnecessary. * [Print:] * p ----> 44Persion1 @ 06 * p ----> 33Persion1 @ 05 * p ----> 22Persion1 @ 04 * p ----> 11Persion1 @ 03 * p ----> better * p ----> best * p ----> good */HashSet set3 = new HashSet (); persion1 pc1 = new Persion1 (11); Persion1 pc2 = new Persion1 (22); Persion1 pc3 = new Persion1 (33); Persion1 pc4 = new Persion1 (44 ); set3.add (pc1); set3.add (pc2); set3.add (pc3); set3.add (pc4); set3.add ("good"); set3.add ("better "); set3.add ("best"); Iterator
     
      
Iterator = set3.iterator (); while (iterator. hasNext () {Object p = iterator. next (); System. out. println ("p ---->" + p + ", hasCode is:" + p. hashCode ();} System. out. println ("************************************* ********"); // -------------------------------------------/*** the hashset is stored Based on the hash code, and the sequence of elements added to the linked list is recorded. * Objects are stored through a linked list, which generally results in high insertion and deletion efficiency and low retrieval efficiency. */Define hashset into set = new LinkedHashSet ();/*** add sequence hashset record elements **/Persion1 pd1 = new Persion1 (55); Persion1 pd2 = new Persion1 (66 ); persion1 pd3 = new Persion1 (77); Persion1 pd4 = new Persion1 (88); sorted set. add (pd1); sorted set. add (pd2); sorted set. add (pd3); sorted set. add (pd4); sorted set. add ("aaaa"); sorted set. add ("bbbb"); sorted set. add ("cccc"); for (Object p: sorted set) {System. out. println ("p ***> Is: "+ p +", hasCode is: "+ p. hashCode ();} System. out. println ("-------------------------------------"); // ---------------------------------------------/*** an exception is reported when multiple objects of different types are added to the TreeSet. * For a custom class, only one object can be stored, and the Implementation class does not need to implement the [Comparable interface ]. * However, if you want to store objects of multiple custom classes, * if you do not implement the Comparable interface, a java. lang. ClassCastException occurs. */Set treeSet = new TreeSet (); Persion1 pe1 = new Persion1 (12); treeSet. add (pe1);/* treeSet. add (new String ("hello"); */Iterator itor = treeSet. iterator (); while (itor. hasNext () {System. out. println ("TreeSet p is:" + itor. next ();} System. out. println ("-------------------------------------"); // ---------------------------------------------/*** Set sorting ** Persion3 implements the sorting interface Comparable */Set
      
        SortSet = new TreeSet
       
         (); Persion3 pf1 = new Persion3 (1); Persion3 pf2 = new Persion3 (8); Persion3 pf3 = new Persion3 (2); Persion3 pf4 = new Persion3 (5 ); persion3 pf5 = new Persion3 (9); Persion3 pf6 = new Persion3 (4); Persion3 pf7 = new Persion3 (0); sortSet. add (pf1); sortSet. add (pf2); sortSet. add (pf3); sortSet. add (pf4); sortSet. add (pf5); sortSet. add (pf6); sortSet. add (pf7); for (Persion3 p: sortSet) {System. out. println ("p ***> is:" + p + ", hasCode is:" + p. hashCode ();} System. out. println ("-------------------------------------");/*** Set sorting: Sort Comparetor by [sequencer] */TreeSet
        
          SortSetByComparator = new TreeSet
         
           (New ComparetorByIndex (); sortSetByComparator. add (pf1); sortSetByComparator. add (pf2); sortSetByComparator. add (pf3); sortSetByComparator. add (pf4); sortSetByComparator. add (pf5); sortSetByComparator. add (pf6); sortSetByComparator. add (pf7); for (Persion3 p: sortSetByComparator) {System. out. println ("p ***> is:" + p + ", hasCode is:" + p. hashCode ();} System. out. println ("---------------------------------------") ;}} class Pe Rsion1 {public int mAge; private static AtomicInteger atIndex = new AtomicInteger (); // atomic type public int index; public Persion1 (int age) {mAge = age; index = atIndex. addAndGet (1) ;}@ Overridepublic int hashCode () {return 0 ;}@ Overridepublic String toString () {return mAge + "" + super. toString () + index ;}@ Overridepublic boolean equals (Object arg0) {if (arg0 instanceof Persion1) {Persion1 p = (Persion1) arg0; return mAge = P. mAge;} return super. equals (arg0) ;}} class Persion2 {public int mAge; private static AtomicInteger atIndex = new AtomicInteger (); // atomic type public int index; public Persion2 (int age) {mAge = age; index = atIndex. addAndGet (1) ;}@ Overridepublic int hashCode () {return 0 ;}@ Overridepublic String toString () {return mAge + "" + super. toString () + index ;}@ Overridepublic boolean equals (Object arg0) {if (arg0 instanceof P Ersion2) {Persion2 p = (Persion2) arg0; return mAge! = P. mAge;} return super. equals (arg0) ;}} class Persion3 implements Comparable
          
            {Public int mAge; private static AtomicInteger atIndex = new AtomicInteger (); // atomic type public int index; public Persion3 (int age) {mAge = age; index = atIndex. addAndGet (1) ;}@ Overridepublic int hashCode () {return 0 ;}@ Overridepublic String toString () {return mAge + "" + super. toString () + index ;}@ Overridepublic boolean equals (Object arg0) {if (arg0 instanceof Persion3) {Persion3 p = (Persion3) arg0; return mAge! = P. mAge;} return super. equals (arg0) ;}@ Overridepublic int compareTo (Persion3 p) {return mAge-p. mAge ;}} class ComparetorByAge implements Comparator
           
             {@ Overridepublic int compare (Persion3 p0, Persion3 p1) {return extends Mage-p1.mAge ;}} class ComparetorByIndex implements Comparator
            
              {@ Overridepublic int compare (Persion3 p0, Persion3 p1) {return partial index-p1.index ;}}
            
           
          
         
        
       
      
     
    
   
  
 

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.