设置添加到List的元素,然后混乱

时间:2011-12-05 22:20:37

标签: java list collections set

所以基本上我有类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碰巧有Set名为teamList。 当我调用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;
    }


}

3 个答案:

答案 0 :(得分:3)

我认为问题在于:

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>();

答案 1 :(得分:0)

您必须初始化teamList:

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

答案 2 :(得分:0)

问题是因为你没有创建teamList的实例我认为。