Code fragment-exception. If the return length is greater than 0, the return value is null.

Source: Internet
Author: User

Otherwise, null is returned.

    • Returns a container with a length of 0.CodeBefore using the container, you do not need to judge whether it is empty.

      • Code is more elegant
    • Avoid many nullpointexception events that do not appear normally.

      • Do not always remember to check whether the container is empty.
      • This avoids many forceclose attacks. Some error scenarios are hard to reproduce.

If an exception occurs, null is returned.

    • Public static list <string> getitems1 () {If (new random (). nextint (10)> 5) {// returns nullreturn NULL;} List <string> List = new arraylist <string> (); For (INT I = 0; I <5; I ++) {list. add ("Item1 +" + I);} return list ;}
    • List <string> List = getitems1 (); If (list! = NULL) {// annoying judgment. This judgment is required if it is useful in the future. For (string S: List) {system. Out. println (s );}}

After modification

    •  Public static list 
          
            getitems2 () {If (new random (). nextint (10)> 5) {// exception, return the return collections for the container whose length is 0. emptylist () ;}list 
           
             List = new arraylist 
            
              (); For (INT I = 0; I <5; I ++) {list. add ("item2-" + I);} return list ;}
            
           
          
    •  for (string S: getitems2 () {// more general, no need to use special judgment system. out. println (s) ;}

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.