Java programming ideology (9) -- Holding Objects (2)

Source: Internet
Author: User

Java programming ideology (9) -- Holding Objects (2)

11) Map

The author said that the ability to map objects to other objects is the best solution to programming problems.

Indeed, for example, to view the distribution of random numbers, if it is really a random number, then 10000 times to generate a random number of less than 20 times, each number should appear in a similar number.

Public class TestMap {public static void main (String [] args) {Map
 
  
Map = new HashMap
  
   
(); Random r = new Random (47); // The System is empty in map. out. println (map. get (1); for (int I = 0; I <10000; I ++) {int j = r. nextInt (10); Integer temp = map. get (j); map. put (j, temp = null? 1: temp + 1);} System. out. println (map) ;}// result: null // {0 = 994, 1 = 1033, 2 = 1010, 3 = 1014, 4 = 958, 5 = 1000, 6 = 1052, 7 = 980, 8 = 946, 9 = 1013}
  
 

Numbers are indeed randomly distributed, and Map is also useful.

Map also uses multiple dimensions.

Map
 
  >;
 


12) Queue

First-in-first-out, when buying a fund, because of the additional purchase in the later stage, but the previous fund has been full for one month, so no redemption is required. Then, after asking the customer service, I found that the first buy is redeemed first, then I shot my thigh. Isn't this the so-called queue design?


The Queue List implements the Queue interface.

By the way, Random is often used. I forgot to say why the author used 47 parameter passing. In fact, the parameter passing through Random is the input of a computing seed. The default value is the system time, 47. In his opinion, it has always been a "magic number ".

Public class TestQueue {public static void main (String [] args) {Queue
 
  
Q = new shortlist
  
   
(); Random r = new Random (47); for (int I = 0; I <10; I ++) {// insert an element to the end of the q. offer (r. nextInt (12);} // returns the System header. out. println (q. peek (); System. out. println (q );}}
  
 

1. PriorityQueue

Let's look at the example:

public class TestPriorityQueue {    public static void main(String[] args) {        String s = "What 's your favorite number ,1 or 2?";          List
 
   l = Arrays.asList(s.split(""));          PriorityQueue
  
    pq = new PriorityQueue
   
    (l);          while(pq.peek()!=null){              System.out.print(pq.remove()+" ");          }    }}result:[,  ,  ,  ,  , b,  , 1,  , i, e, n, h, ',  , a, o, 2, ?, y, t, t, o, u, u, m, r, e, r, f, ,, s, a, v, r, o, W, r]                                       ' , 1 2 ? W a a b e e f h i m n o o o r r r r s t t u u v y 
   
  
 

First-level, highest-level, and first-level pop-up. The smallest value in the priority queue has the highest priority. If the value is String, the highest priority is given by spaces.

Direct output is not sorted, which is different from what I expected.

To output the data in sequence, you must use the peek method to return the header of the queue. If it is null, null is returned. If it is removed, the data with a higher priority will be displayed.

 public static void main(String[] args) {        String s = "werwerwer";        List
 
   l = Arrays.asList(s.split(""));        PriorityQueue
  
    pq = new PriorityQueue
   
    (l);        while (pq.peek() != null) {            System.out.print(pq.remove() + " ");        }        pq = new PriorityQueue
    
     (l);        System.out.println(pq.peek());        pq.remove();        System.out.println(pq.peek());        pq.remove();        System.out.println(pq.peek());    }result: e e e r r r w w w ee
    
   
  
 

The result surprised me that the String contains spaces. After reading the string, return to solve the problem.


13) Foreach and iterator

Foreach traversal:

public class Box {    public static void main(String[] args) {        Collection
 
   c = new LinkedList
  
   ();        String s = "you are so great";        Collections.addAll(c,s.split(" "));        for(String string : c){            System.out.println(string);        }    }}
  
 

Previously, foreach was introduced by Java SE5 because the Iterable interface was also introduced. The Iterator method of Iterator is generated by the interface, and Iterable is used by Foreach to move in the sequence. Therefore, the classes that implement the Iterable interface can be used for Foreach statements.


All Known Subinterfaces: BeanContext, BeanContextServices, BlockingDeque
 
  , BlockingQueue
  
   , Collection
   
    , Deque
    
     , DirectoryStream
     
      , List
      
       , NavigableSet
       
        , Queue
        
         , Set
         
          , SortedSet
           
          
         
        
       
      
     
    
   
  
 

In fact, there are so many Iterable sub-interfaces, the next implementation of the Collection interface will naturally implement the Iterable interface, so it is also applicable.


Summary:

First look at the container classification diagram:


The dot line is an interface, the solid line is a specific class, the hollow arrow refers to the implementation interface, and the solid arrow refers to the object of the class that a class can generate the arrow points.


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + MaGiyv3X6b/release/b7do6y/release + CjwvcD4KPHA + release/release + TI3cG/oaO088G/y + a7 + release = "brush: java; "> public class Box {public static void main (String [] args) {long start = System. currentTimeMillis (); Random r = new Random (47); Random list L = new shortlist (); For (int I = 0; I <1000000; I ++) {l. add (r. nextInt (1000);} long end = System. currentTimeMillis (); System. out. println (end-start); ArrayList A = new ArrayList (); For (int I = 0; I <1000000; I ++) {. add (r. nextInt (1000);} long end2 = System. currentTimeMillis (); System. out. println (end2-end );}}
4. Map and HashMap are used for fast access. TreeMap keeps the key sorting, and the speed is not as fast as HashMap. LinkedHashMap keeps the element sorting, and also supports fast access through hash.


5. Set elements are not repeated. TreeSet, HashSet, and LinkedHashSet are similar to Map.



In the end, you will find that these containers can store objects in an infinite size and help you count them. How are these magical classes designed? This is the importance of learning the data structure well.




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.