gpt4 book ai didi

java - 如何使用 arraylist 作为字段有效地深度克隆对象数组

转载 作者:太空宇宙 更新时间:2023-11-04 11:14:52 24 4
gpt4 key购买 nike

最深元素:

class Player {
//fields contain:
int value;
}

收集于:

class Team {
//fields contain:
ArrayList<Player> players;
}

收集于:

class Splitter {
//fields contain:
Teams[] teams;
}

Splitter 的函数中,我必须克隆 teams。我基本上必须通过克隆每个 Team 对象来克隆数组 teams,每个对象都包含一个我必须克隆的 ArrayList players。我不想想要克隆 Player 对象本身。

到目前为止我的解决方案看起来像这样:

private Team[] deepClone(Team[] teams) {
Team[] new_teams = new Team[teams.length];
for (int i = 0; i < teams.length; i++) {
new_teams[i] = new Team();
for (Player player : teams[i].getPlayers())
new_teams[i].getPlayers().add(player);
}
return new_teams;
}

我可以做哪些改变来使其更高效或更优雅?

最佳答案

您当前的解决方案相当于以下更简单的形式:

private Team[] deepClone(Team[] teams) {
Team[] new_teams = new Team[teams.length];
for (int i = 0; i < teams.length; i++) {
new_teams[i] = new Team();
new_teams[i].getPlayers().addAll(teams[i].getPlayers());
}
return new_teams;
}

您可以使用流和 lambda 使其更加优雅,而无需循环索引:

private Team[] deepClone(Team[] teams) {
return Stream.of(teams).map(team -> {
Team newTeam = new Team();
return newTeam.getPlayers().addAll(team.getPlayers());
}).toArray(Team[]::new);
}

关于java - 如何使用 arraylist 作为字段有效地深度克隆对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45577876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com