如何使用arraylist作为字段

时间:2017-08-08 20:55:27

标签: java arrays arraylist clone deep-copy

最深的元素:

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

收集于:

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

收集于:

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

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

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

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;
}

我可以改变什么来使这更有效或更优雅?

2 个答案:

答案 0 :(得分:0)

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

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;
}

如果没有使用stream和lambdas的循环索引,你可以使它更优雅:

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

答案 1 :(得分:0)

理想情况下,如果你想进行完美的深度克隆,你也应该克隆玩家,我们应该总是在每个类中编写克隆方法,然后调用克隆方法来克隆,无论如何你可以进入下面。

SELECT distinct emp_id, salary FROM TABLE_EMPLOYEE