Java List 复制

来源:互联网 发布:计算机监控软件 编辑:程序博客网 时间:2024/05/17 01:22

开发时, 很多时候我们需要实现 List 的复制, 如果使用For循环复制,  需要写好几行代码, 也不能复用 .

 

其实我们可以借助泛型写一个通用的方法, 以后都可使用这个方法实现List 的复制 .

 

Java代码  收藏代码
  1. /** 
  2.  * 复制集合 
  3.  * @param <E> 
  4.  * @param source 
  5.  * @param destinationClass 
  6.  * @return 
  7.  * @throws InstantiationException  
  8.  * @throws InvocationTargetException  
  9.  * @throws IllegalAccessException  
  10.  */  
  11. public static <E> List<E> copyTo(List<?> source, Class<E> destinationClass) throws IllegalAccessException, InvocationTargetException, InstantiationException{  
  12.     if (source.size()==0return Collections.emptyList();  
  13.     List<E> res = new ArrayList<E>(source.size());  
  14.     for (Object o : source) {  
  15.         E e = destinationClass.newInstance();  
  16.         BeanUtils.copyProperties(e, o);  
  17.         res.add(e);  
  18.     }  
  19.     return res;  
  20. }  
 
0 0