To check null in a repeat statement

Asked 2 years ago, Updated 2 years ago, 132 views

Is there a good way to check if the list is null when going around for loop in Java?

if (someList != null) {
    for (Object object : someList) {
        // // do whatever
    }
}

//I 

if (someList == null) {
    return; // Or throw ex
}
for (Object object : someList) {
    // // do whatever
}

Both of these look so dirty. Isn't there a cleaner way?

for-loop java loops syntax

2022-09-21 18:01

1 Answers

for( Object o : safe( list ) ) {
   // // do whatever 
 }

public static List safe( List other ) {
    return other == null ? Collections.EMPTY_LIST : other;
}

You can do it this way.


2022-09-21 18:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.