To check null in a repeat statement

Asked 1 years ago, Updated 1 years ago, 118 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.