if(listStr.size == 0){与if(listStr.isEmpty()){ [英] if(listStr.size == 0){ versus if(listStr.isEmpty()){

查看:110
本文介绍了if(listStr.size == 0){与if(listStr.isEmpty()){的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<String> listStr = new ArrayList<String>();

if(listStr.size == 0){

}

if(listStr.isEmpty()){

}

在我看来,使用 listStr.isEmpty()的好处之一是它不检查列表的大小然后将其与零进行比较,它只是检查列表是否为空。有没有其他优点,因为我经常看到 if(listStr.size == 0)而不是 if(listStr.isEmpty())在代码库中?是否有理由以这种方式检查我不知道?

In my view one of the benefits of using listStr.isEmpty() is that it doesn't check the size of the list and then compares it to zero, it just checks if the list is empty. Are there any other advantages as I often see if(listStr.size == 0) instead of if(listStr.isEmpty()) in codebases? Is there is a reason it's checked this way that I am not aware of?

推荐答案

这个问题可以给你答案。基本上,在某些列表的实现中,方法 isEmpty()检查大小是否为零(因此从性能的角度来看它们实际上是等价的)。但是,在其他类型的列表(例如链接列表)中,计算项目需要的时间多于检查它是否为空。

The answers to this question could give you the answer. Basically, in implementations of some lists the method isEmpty() checks if the size is zero (and therefore from the point of view of performance they are practically equivalent). In other types of lists (for example the linked lists), however, counting items require more time than to check if it is empty or not.

因此,它是总是方便使用方法 isEmpty()来检查列表是否为空。在所有类型的列表中提供这种方法的原因也与接口有关,因为 ArrayList Vector LinkedList 实现相同的 List 界面:此接口具有 isEmpty()方法;然后,每个特定类型的列表提供其 isEmpty()方法的实现。

For this reason it is always convenient to use the method isEmpty() to check if a list is empty. The reasons for which such a method is provided in all types of lists are also related to the interface, since ArrayList, Vector and LinkedList implement the same List interface: this interface has the isEmpty() method; then, each specific type of list provides its implementation of isEmpty() method.

这篇关于if(listStr.size == 0){与if(listStr.isEmpty()){的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆