I was looking through the code for an old Android application of mine, and I saw one thing I did to the effect of this:

我正在查看我的一个旧的Android应用程序的代码,我发现我做了一件事:

        boolean emptyArray = true;
        for (int i = 0; i < array.size(); i++)
        {
            if (array.get(i) != null)
            {
                    emptyArray = false;
                    break;
            }
        }
        if (emptyArray == true)
        {
            return true;
        }
        return false;

There has to be a more efficient way of doing this -- but what is it?

必须有一种更有效的方法来做到这一点——但它是什么呢?

emptyArray is defined as an ArrayList of Integers, which are inserted with a random number of null values (And later in the code, actual integer values).

emptyArray定义为一个整数的ArrayList,它插入了随机数的空值(在后面的代码中是实际的整数值)。

Thanks!

谢谢!

4 个解决方案

#1


6

There is no more efficient way. The only thing is you can do, is write it in more elegant way:

没有更有效的方法。你唯一能做的就是,用更优雅的方式写出来:

List<Something> l;

boolean nonNullElemExist= false;
for (Something s: l) {
  if (s != null) {
     nonNullElemExist = true;
     break;
  }
}

// use of nonNullElemExist;

Actually, it is possible that this is more efficient, since it uses Iterator and the Hotspot compiler has more info to optimize instead using size() and get().

实际上,这可能更有效,因为它使用迭代器,Hotspot编译器有更多的信息来优化,而不是使用size()和get()。

更多相关文章

  1. js实现把整数秒转化为"hh:mm:ss"的时间格式.
  2. 给定一个整数数组,找出两个下标,要求后面下标所指的数减去前面下标

随机推荐

  1. 创建 PSR-4 的 Php 包
  2. 看看PHP 多进程处理任务
  3. 一定要改掉 这5个PHP编程中的不良习惯!
  4. PHP安全问题汇总
  5. 详解PHP中被忽略的性能优化利器:生成器
  6. 教你使用PHP实现查找你想要的附近人
  7. 你可能要纠正这5个PHP编码小陋习!
  8. PHP处理时间和时区需注意以下三点!
  9. php+redis实现全页缓存系统
  10. 分享php秒杀功能实现的思路