Set元素添加到List中,然后乱七八糟
所以基本上我有一个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类恰好有一个名为teamList的Set
。 当我调用 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;
}
}
So basically I have this constructor for the class 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)));
}
}
}
The class Company
happens to have a Set
called teamList
.
When I call on System.out.println(teamNames.get(i))
it shows me the content so obviously the elements of the set are there, however when I try to create a new Team
object based on the elements of the list of Strings, it gives me a NullPointerException
. I don't know why is that? Help?
Here is the code for the Team class in case you need it:
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为问题出在这里:
您需要创建一个实现
List
的类的实例,并将其分配给teamList
。您尚未执行此操作,因此当您调用teamList.add(...)
时,它将抛出NullPointerException
。解决方法是这样写:
I think the problem is here:
You need to create an instance of a class that implements
List<Team>
and assign it toteamList
. You haven't done this so it will throw aNullPointerException
when you callteamList.add(...)
.The fix is to write this instead:
您必须初始化 teamList:
You must initialize teamList:
我认为问题是因为你没有创建 teamList 的实例。
Problem is because you not create instance of teamList I think.