加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

给定一个Object是任何类型的数组,如何测试它在Java中是空的?

发布时间:2020-12-14 17:43:31 所属栏目:Java 来源:网络整理
导读:请帮我填写我的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 Collect
请帮我填写我的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.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),或者在这种情况下,只需检查长度是否为零.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读