varargs中的元素数量

时间:2018-05-01 05:13:17

标签: java arrays variadic-functions arity

我很困惑Java如何计算varargs的长度:

// Spinner.js

import React from 'react'
import {Icon, Spin} from 'antd';

const antIcon = () => <Icon type="loading" style={{ fontSize: 24 }} spin />;


export const FullSpinner = () => <Spin indicator={antIcon} />

这会打印一个0。

当我通过时:

static void hello(Integer... x){

    System.out.println(x.length);
}


public static void hi(){
    hello();
}

这会抛出Null指针异常。

static void hello(Integer... x){

    System.out.println(x.length);
}


public static void hi(){
    hello(null);
}

这打印44。

有人可以帮我理解吗?

4 个答案:

答案 0 :(得分:2)

如果您将非null整数数组传递给hello()方法,那么正如您所见,您可以毫无问题地访问该长度。因此,您应检查null输入并将其等同于长度为零的数组:

static void hello(Integer... x) {
    int length = x == null ? 0 : x.length;
    System.out.println(length);

    if (x == null) return;

    // otherwise do something
}

public static void hi() {
    hello(null);
}

请注意,值只是作为数组传递,并且您对hello()的以下版本存在同样的问题:

static void hello(Integer[] x) { }

在这种情况下,如果您还尝试读取null输入的长度,则会出现异常。

答案 1 :(得分:2)

写这个:

static void hello(Integer... x){

基本上是写这个的奇特方式:

static void hello(Integer[] x){

还有额外的好处,你可以用这种方式调用前者:

hello(Integer.valueOf(1), Integer.valueOf(2));

而不是

hello(new Integer[]{Integer.valueOf(1), Integer.valueOf(2)});

话虽如此,你仍然可以使用带有varargs的方法的第二种形式。

手头的第二个问题是数组,甚至是基元数组,在Java中被视为对象。所以,如果你写:

hello(null);

您使用hello null数组Integer的参数调用new Integer[]{null},而 walkAlarmManager.cancel()

第一个调用传递一个空数组,所以长度为0.同样,第三个调用传递一个长度为44的数组,然后你得到它作为结果。

答案 2 :(得分:0)

如果原因是每个数组的内容都有值,请记住数组的每个位置都是与其容器相同类型的变量,因此如果发送null,则数组为空如果它是null print null

static void hello(Integer... x){
  if(x!=null)
   System.out.println(x.length);
  else
    System.out.println('is null');
}

答案 3 :(得分:0)

声明

static void hello(Integer... x)

您可以通过正好传递一个Integer[](在方法中成为x)或传递零个或多个Integer来调用它(编译器将创建一个{其中{1}}成为方法中的Integer[]

的情况下
x

您是否试图传递hello(null) 类型null的值,或者您是否尝试传递Integer[]类型的null值,这是不明确的(两者都是合法的)。它默认为前者(Integer类型的null),因此方法内的Integer[]x,而不是单个null的数组元件。尝试访问null上的.length会导致异常。

如果您想传递一个null null,可以通过明确地将其转换为Integer来解决歧义:

Integer

或首先将其分配给hello((Integer)null); 类型的变量:

Integer

这些将打印长度为1。