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.
- 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) ;}