【问题标题】:Given that an Object is an Array of any type how do you test that it is empty in Java?鉴于 Object 是任何类型的 Array,如何在 Java 中测试它是否为空?
【发布时间】:2012-02-22 12:13:09
【问题描述】:

请帮我完成我的 isEmpty 方法:

public static boolean isEmpty(Object test){
    if (test==null){
        return true;
    }
    if (test.getClass().isArray()){
        //???
    }
    if (test instanceof String){
        String s=(String)test;
        return s=="";
    }
    if (test instanceof Collection){
        Collection c=(Collection)test;
        return c.size()==0;
    }
    return false;
}

如果我正在处理一个数组,如果它的长度为零,我会输入什么代码来确定它会返回 true?无论类型是 int[]、Object[],我都希望它能够工作。 (只是为了让你知道,我可以告诉你,如果你将 int[] 放入 Object[] 变量中,它会抛出异常。)

【问题讨论】:

    标签: java arrays types


    【解决方案1】:

    你可以使用java.reflect.Array中的辅助方法getLength(Object)

    public static boolean isEmpty(Object test){
        if (test==null){
            return true;
        }
        if (test.getClass().isArray()){
            return 0 == Array.getLength(test);
        }
        if (test instanceof String){
            String s=(String)test;
            return s.isEmpty(); // Change this!!
        }
        if (test instanceof Collection){
            Collection c=(Collection)test;
            return c.isEmpty();
        }
        return false;
    }
    

    注意不能用

    boolean empty = (someString == "");
    

    因为那不安全。要比较字符串,请使用String.equals(String),或者在这种情况下,只需检查长度是否为零。

    【讨论】:

      【解决方案2】:

      您可以使用java.lang.reflect.Array#getLength

      另请注意,您对 String 的测试不会像您预期的那样工作。

      【讨论】:

      • 详细说明,可以替换为:return s=="";返回 s.length() > 0;
      【解决方案3】:

      内置一些空值检查的第三个选项是 Apache 的 ArrayUtils

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-27
        • 1970-01-01
        • 2013-10-10
        • 1970-01-01
        • 2011-02-27
        • 2011-09-17
        相关资源
        最近更新 更多