Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 跳过空数组_Java_Arrays - Fatal编程技术网

Java 跳过空数组

Java 跳过空数组,java,arrays,Java,Arrays,我正在删除数组的一部分,当这个方法通过时,我得到一个空点异常。如何使其跳过带有null值的数组 public static int getTotal(Candidate[] list) { int total = 0; for(int i = 0; i < list.length; i++) { total = list[i].getVotes() + total; }

我正在删除数组的一部分,当这个方法通过时,我得到一个空点异常。如何使其跳过带有
null
值的数组

 public static int getTotal(Candidate[] list)   
    {  
        int total = 0;  
        for(int i = 0; i < list.length; i++) 
        {

        total = list[i].getVotes() + total;  
    }

        return total;  
    }  
publicstaticintgettotal(候选者[]列表)
{  
int-total=0;
for(int i=0;i
您可以像这样做:

total += list[i] != null ? list[i].getVotes() : 0;
在Java 8中,您的方法如下:

public static int getTotal(Candidate[] list) {
    return Stream.of(list)
                 .filter(s -> s != null)
                 .collect(Collectors.summingInt(Candidate::getVotes));
}
你可以这样做:

total += list[i] != null ? list[i].getVotes() : 0;
在Java 8中,您的方法如下:

public static int getTotal(Candidate[] list) {
    return Stream.of(list)
                 .filter(s -> s != null)
                 .collect(Collectors.summingInt(Candidate::getVotes));
}
publicstaticintgettotal(候选者[]列表)
{  
int-total=0;
for(int i=0;i
公共静态int getTotal(候选[]列表)
{  
int-total=0;
for(int i=0;i
只需使用空检查来保护它:

public static int getTotal(Candidate[] list)   
{
    int total = 0;  

    if (list != null)
    {
        for(int i = 0; i < list.length; i++) 
        {
            if (list[i] != null)
            {
                total = list[i].getVotes() + total;  
            }
        }
    }

    return total;  
}
publicstaticintgettotal(候选者[]列表)
{
int-total=0;
如果(列表!=null)
{
for(int i=0;i
只需使用空检查来保护它:

public static int getTotal(Candidate[] list)   
{
    int total = 0;  

    if (list != null)
    {
        for(int i = 0; i < list.length; i++) 
        {
            if (list[i] != null)
            {
                total = list[i].getVotes() + total;  
            }
        }
    }

    return total;  
}
publicstaticintgettotal(候选者[]列表)
{
int-total=0;
如果(列表!=null)
{
for(int i=0;i
if(list[i]!=null)
if(list[i]!=null)