In Java, I have the following method:
public String normalizeList(List<String> keys) { // ... }
I want to check that keys
:
null
itself; andsize() == 0
); andString
elements that are null
; andString
elements that are empty ("")This is a utility method that will go in a "commons"-style JAR (the class wil be something like DataUtils
). Here is what I have, but I believe its incorrect:
public String normalize(List<String> keys) { if(keys == null || keys.size() == 0 || keys.contains(null) || keys.contains("")) throw new IllegalArgumentException("Bad!"); // Rest of method... }
I believe the last 2 checks for keys.contains(null)
and keys.contains("")
are incorrect and will likely thrown runtime exceptions. I know I can just loop through the list inside the if
statement, and check for nulls/empties there, but I'm looking for a more elegant solution if it exists.
As other answers here have shown, in order to check if the list is empty you need to get the number of elements in the list ( myList. Count ) or use the LINQ method . Any() which will return true if there are any elements in the list.
isEmpty() method. A simple solution to check if a list is empty in Java is using the List's isEmpty() method. It returns true if the list contains no elements. To avoid NullPointerException , precede the isEmpty method call with a null check.
Example 2: Using the len() Function Then we used if statement to check if the length of the list is equals to zero or not. If the condition sets to be true then the string is empty. Otherwise the string is not empty.
v == null : o. equals(v) ). i.e. if o is null , it returns true only if one element is null in the ArrayList. If o is not null , it returns true only if at least one element equal to v.
keys.contains(null) || keys.contains("")
Doesn't throw any runtime exceptions and results true
if your list has either null (or) empty String.
This looks fine to me, the only exceptions you would get from keys.contains(null)
and keys.contains("")
would be if keys
itself was null
.
However since you check for that first you know that at this point keys
is not null
, so no runtime exceptions will occur.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With