java – ! list. Isempty() and list Size () > 0, same conditions?

I see such code

if (!substanceList.isEmpty() && (substanceList.size() > 0))
{
  substanceText = createAmountText(substanceList);
}

And you can reconstruct it like this

if (!substanceList.isEmpty())
{
  substanceText = createAmountText(substanceList);
}

I want to explain the above code and wonder if the second method may cause some errors

Solution

If you have any questions, please read the Javadoc:

Collection. isEmpty():

Collection. size():

Therefore, it is assumed that the set is implemented correctly:

collection.isEmpty() <=> collection.size() == 0

Or, conversely:

!collection.isEmpty() <=> collection.size() != 0

Since the number of elements should only be positive, this means:

!collection.isEmpty() <=> collection.size() > 0

So yes, the two forms are equivalent

Warning: in fact, if your collection is not modified from another thread at the same time, they are only equivalent

This:

!substanceList.isEmpty() && (substanceList.size() > 0)

Equivalent to the logic I mentioned above:

!substanceList.isEmpty() && !substanceList.isEmpty()

You can only simplify this

!substanceList.isEmpty()

If you can guarantee that its value is in substancelist Isempty() does not change between evaluations

In fact, you are unlikely to need to care about the differences between these situations, at least at this point in the code You may need to be concerned about the list of changes in another thread, but if it becomes empty before (or at the same time) createmounttext is executed But this is not introduced by refactoring

TL; Dr: did almost the same thing with if (! Substancelist. Isempty()) {and read it more clearly

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>