java判断长度为0,java检测集合是否为空或长度是否为0

java检测集合是否为空或长度是否为0

当读数据库的数据后,返回的数据可能为空或长度等于0,而我们要取第一个,或其他的数据,如果这个数据为空时就会报错,写了一个工具类方便调用:

package com.yx.utils;

import org.junit.Test;

import java.lang.reflect.Array;

import java.util.Collection;

import java.util.List;

import java.util.Map;

import java.util.Set;

public class ObjectIfNullUtils {

/**

* 判断对象是否为空

*

* @param obj

* @return

*/

public static Boolean ifNull(Object obj) {

return obj == null ? true : false;

}

@Test

public void test(){

}

/**

* 判断对象长度是否为空(对象不能为null)

*

* @param type

* @param obj

* @return

*/

public static Boolean ifLengthZero(String type, Object obj) {

int length = 0;

switch (type) {

case "Collection":

if(!(obj instanceof Collection)){

throw new RuntimeException("这个不是一个Collection集合");

}

length = ((Collection) obj).size();

break;

case "Map":

if(!(obj instanceof Map)){

throw new RuntimeException("这个不是一个Map集合");

}

length = ((Map) obj).size();

break;

case "String":

if(!(obj instanceof String)){

throw new RuntimeException("这个不是一个String对象");

}

length = ((String) obj).length();

break;

}

return length == 0 ? true : false;

}

/**

* 判断对象是否为空或者长度等于0

*

* @param type

* @param obj

* @return

*/

private static Boolean ifObjectLengthZeroAndNull(String type, Object obj) {

if (ifNull(obj)) {

return true;

}

if (ifLengthZero(type, obj)) {

return true;

}

return false;

}

/**

* 判断List集合是否为空或长度是否等于0

*

* @param list

* @return

*/

public static Boolean ifListLengthZeroAndNull(List list) {

return ifObjectLengthZeroAndNull("Collection", list);

}

/**

* 判断Set集合是否为空或长度是否等于0

*

* @param set

* @return

*/

public static Boolean ifSetLengthZeroAndNull(Set set) {

return ifObjectLengthZeroAndNull("Collection", set);

}

/**

* 判断Map集合是否为空或长度是否等于0

*

* @param map

* @return

*/

public static Boolean ifMapLengthZeroAndNull(Map map) {

return ifObjectLengthZeroAndNull("Map", map);

}

/**

* 判断String集合是否为空或长度是否等于0

*

* @param str

* @return

*/

public static Boolean ifStringLengthZeroAndNull(String str) {

return ifObjectLengthZeroAndNull("String", str);

}

/**

* 判断Array集合是否为空或长度是否等于0

*

* @param obj

* @return

*/

public static Boolean ifArrayLengthZeroAndNull(Object obj) {

if (ifNull(obj)) {

return true;

}

if (obj.getClass().isArray()) {

int length = Array.getLength(obj);

if (length == 0) {

return true;

}else {

return false;

}

}else{

throw new RuntimeException("这个不是一个数组");

}

}

/**

* 返回一个指定的集合数(超出范围会抛异常)

* @param list

* @param num

* @param * @return

*/

public static T getListNumDate(Listlist, Integer num){

if(!ifListLengthZeroAndNull(list)) {

return list.get(num);

}

return null;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值