有的時候還是需要自己手動轉換,可是每次都寫就會覺得很煩,今天終於研究了一個方法出來了,
終於可以可以省事了
/**
* 容器轉換成數據,支持泛型
* */
public static T[] collectionToArray(Collection 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 ;
}
/**
* 轉換類型
* */
private static T[] collectionToArray(Collection coll , Class<?> clazz){
Iterator 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 ;
}