一些小工具方法,能将容器转换成指定的数组类型有使用泛型

如果大家有更好的方法,请回帖


 

/**
	 *一个小工具类
	 *@author Hf
	 *@mailto:huangfei8087@163.com
	 * 在编程的过程中很多时候都希望能将
	    容器直接转成成为指定的数据,比如
		List<Integer>ids = new ArrayList<Integer>();
		则每次都需要手动创建一个Integer数组,然后在赋值。 
		
		collectionToArray 这个方法就实现了这个功能,可直接转换成为Integer数组
	*/
public class Helper{
	/**
	 *判断去空的方法
	 *@author Hf
	 *@mailto:huangfei8087@163.com
	 *
	*/
	public static boolean isNull(Object value){
		if(value == null){
			return true ; 
		}
		if(value.getClass().isArray()){
			if(Array.getLength(value) == 0){
				return true ; 
			}
		}
		if(value instanceof Collection<?>){
			Collection<?> collection = (Collection<?>) value ;
			if(collection.isEmpty()){
				return true ;
			}
		}else if(value instanceof Map<?, ?>){
			Map<?, ?> map = (Map<?, ?>) value ;
			if(map.isEmpty()){
				return true ;
			}
		}else if(value instanceof String){
			String string = (String) value ;
			return isNull(string) ;
		}
		return false; 
	}
	
	
	/**
	 * 判断String类型是否为空 
	 *@author Hf
	 *@mailto:huangfei8087@163.com
	 * */
	public static boolean isNull(String value){
		if(value == null){
			return true ;
		}
		if("".equals(value.trim())){
			return true ;
		}
		return false ;
	}
	
	/**
	 *去掉数组中为NULL 的字段
	 *@author Hf
	 *@mailto:huangfei8087@163.com
	 * */
	public static <T> List<T> checkNull(T[] objs){
		if(isNull(objs)){
			return null;
		}
		List<T> objList = new ArrayList<T>(); 
		for(T obj : objs){
			if(!isNull(obj)){
				objList.add(obj) ;   
			}
		}
		if(isNull(objList)){
			return null;
		}
		return objList ;  
	}
	

	/**
	 *将容器转换成为数组
	 *@author Hf
	 *@mailto:huangfei8087@163.com
	 * */
	public static <T> T[] collectionToArray(Collection<T> coll){ 
		T[] ts = null ;
		try {
			if(coll == null || coll.isEmpty()){
				return ts;
			}
			
			ts = collectionToArray(coll , null ) ;
		} catch (Exception e) {
			try {
				ts = collectionToArray(coll , Object.class ) ; 
			} catch (Exception e2) { 
				e2.printStackTrace( ) ; 
			}
		}
		return ts ; 
	}
	
	/**
	 * 将容器转换成为指定数组
	 *@author Hf
	 *@mailto:huangfei8087@163.com
	 * */ 
	public static <T> T[] collectionToArray(Collection<T> coll , Class<?> clazz){
		Iterator<T> iterator = coll.iterator() ;
		T[] ts = null ;
		int x=0 ;
		while(iterator.hasNext()){
			T tempT = iterator.next() ; 
			if(x == 0){
				ts = (T[])Array.newInstance(clazz != null ? clazz : tempT.getClass() 
						, coll.size()) ;
			}
			ts[x++] = tempT ; 
		}
		return ts ;  
	}
	
}


 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值