其他
深拷贝最佳实践:考虑拷贝消耗的 CPU 和拷贝速度
(给ImportNew加星标,提高Java技能)
深拷贝(clone)是 Java 开发过程中经常遇到问题,有人用 IO 流、有人用 JSON 序列化、有人循环拷贝属性等等,网上文章都能实现功能。
<dependency>
<groupId>com.github.bruce-cloud</groupId>
<artifactId>fastclone</artifactId>
<version>1.0.RELEASE</version>
</dependency>
// 深克隆list
FastClone fastClone = new FastClone();
List<T> clone = fastClone.clone(src);
// 深克隆list
FastClone fastClone = new FastClone();
List<T> clone = fastClone.cloneShallow(src);
public static <T> List <T> deepCopy(List <T> src) {
try {
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteout);
out.writeObject(src);
ByteArrayInputStream bytein = new ByteArrayInputStream(byteout.toByteArray());
ObjectInputStream in = new ObjectInputStream(bytein);
@SuppressWarnings("unchecked")
List < T > dest = (List < T > ) in .readObject();
return dest;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
String jsonString = JSON.toJSONString(arrayList);
List < Symbol > configCoinSymbols = JSON.parseArray(jsonString, Symbol.class);
public static < T > List < T > deepCopy(List < T > src) {
FastClone fastClone = new FastClone();
try {
List < T > clone = fastClone.clone(src);
return clone;
} catch (Exception e) {
log.error("deepCopy 克隆失败", e);
throw new ExchangeException("deepCopy 克隆失败");
}
}
转自:鲫鱼哥,
链接:blog.csdn.net/zjy_love_java/article/details/119465427
- EOF -
看完本文有收获?请转发分享给更多人
关注「ImportNew」,提升Java技能
点赞和在看就是最大的支持❤️