像array.length这样的函数不包含NULL元素?

时间:2011-09-19 03:12:22

标签: java arrays null

TreeNode[] children = grid[row][col].getChildren();

我想要一个简单的函数,可以告诉我这个数组中有多少个对象? getChildren()将返回大小不超过4的对象,例如:

children[0] = null;
children[1] = TreeNode Object
children[2] = null;
children[3] = null;

6 个答案:

答案 0 :(得分:7)

你为什么不自己写呢:

public static <T> int getLength(T[] arr){
    int count = 0;
    for(T el : arr)
        if (el != null)
            ++count;
    return count;
}

答案 1 :(得分:1)

其他选择:

ArrayList l = new ArrayList(Arrays.asList(children));
l.removeAll(Collections.singleton(null)); 
l.size();

答案 2 :(得分:1)

使用谓词可能有些过分,但这是一个Guava解决方案:

int numNotNull = Iterables.size( Iterables.filter( Arrays.asList( children ),
                        Predicates.notNull() ));

答案 3 :(得分:0)

这应该有效。与为您编写的函数基本相同,而不是特定于TreeNode。

int initLength(Object[] myArray) {
  int count = 0;
  for (Object obj : myArray) {
    if ( obj != null ) count++;
  }
  return count;
}

我称它为initLength,因为这些项是init'd但是可以调用它。有些人会说你定义它时会初始化,无论内容是否为空。

答案 4 :(得分:0)

在Java 8中,您可以使用Math.toIntExactArrays.stream构建一个漂亮的单行代码:

Math.toIntExact(Arrays.stream(row).filter(s -> s != null).count())

答案 5 :(得分:0)

代码:

class suppress_exception(object):
    def __init__(self, exceptions_to_catch, minutes=30):
        self.exceptions_to_catch = exceptions_to_catch
        self.timedelta = datetime.timedelta(minutes=minutes)
        code = sys._getframe().f_back.f_code
        self.cache_key = 'suppress_exception_' + code.co_filename + str(sys._getframe().f_back.f_lineno)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        datetime_of_first_failure = cache.get(self.cache_key)
        now = datetime.datetime.now()
        if not type:
            cache.delete(self.cache_key)
            if datetime_of_first_failure:
                logging.info('Fine again. First failure was %s. Duration (first failure until ok): %s' % (
                    datetime_of_first_failure, now - datetime_of_first_failure))
            return
        if not issubclass(type, self.exceptions_to_catch):
            # Thils will raise an exception
            return
        if not datetime_of_first_failure:
            cache.set(self.cache_key, now)
            datetime_of_first_failure = now
        log_method = logging.warn
        if datetime_of_first_failure + self.timedelta > now:
            log_method = logging.info
        log_method('%s %s (datetime_of_first_failure=%s)' % (type.__name__, value, datetime_of_first_failure))
        return True