gpt4 book ai didi

java - Set元素添加到List,然后乱七八糟

转载 作者:行者123 更新时间:2023-11-29 06:06:26 24 4
gpt4 key购买 nike

所以基本上我有类 League 的构造函数:

import java.util.*;

public class League {

private String name;
private List<Team> teamList;

public League(String name) {
List<String> teamNames = new LinkedList<String>(Company.teamList);
Collections.shuffle(teamNames);
teamNames.subList(0, 5);

for(int i = 0; i < teamNames.size(); i++){
teamList.add(new Team(teamNames.get(i)));
}
}
}

Company 类碰巧有一个名为teamListSet。当我调用 System.out.println(teamNames.get(i)) 时,它向我显示了内容,很明显集合的元素在那里,但是当我尝试创建一个新的 Team 对象基于字符串列表的元素,它给了我一个NullPointerException我不知道这是为什么?帮忙?

这是 Team 类的代码,以备不时之需:

import java.util.HashMap;
import java.util.Map;


public class Team {

protected Map<Integer, Player> teamPlayerMap;
private String teamName;

public Team(String name) {
teamPlayerMap = new HashMap<Integer, Player>();
teamName = name;
}

public String getTeamName() {
return teamName;
}


}

最佳答案

我觉得问题出在这里:

private List<Team> teamList;

public League(String name) {
// etc...

for(int i = 0; i < teamNames.size(); i++) {
teamList.add(new Team(teamNames.get(i))); // This will throw!
}
}

您需要创建一个实现List<Team> 的类的实例并将其分配给 teamList .你还没有这样做,所以它会抛出一个 NullPointerException当你调用teamList.add(...) .

解决办法是这样写:

private List<Team> teamList = new ArrayList<Team>();

关于java - Set元素添加到List,然后乱七八糟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8392726/

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