Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Justin Dodson
4,237 PointsJava ArrayList changes list values to most recently added value
Hey guys,
I am working on the Soccer League app and am having some list trouble here. I am trying to build a list of Team objects that I can use to print out the available teams to the organizer so they know what teams are available to add players to. However, right now when I create a new team through the loop it changes the team info for all teams to the last added team.
public class Team { private static String mTeamName; private static String mCoach;
public Team(String teamName, String coach) {
mTeamName = teamName;
mCoach = coach;
}
public void setTeamName(String teamName) {
mTeamName = teamName;
}
public void setCoachName(String coachName) {
mCoach = coachName;
}
public String getTeamName() {
return mTeamName;
}
public String getCoachName() {
return mCoach;
}
public static String getTeam() {
String team = mCoach + " " + mTeamName;
return team;
}
}
public class Roster { private Map<Team, Player> mTeamRoster; private List<Team> mTeamList = new ArrayList<Team>();
public Roster() {
mTeamRoster = new HashMap<Team, Player>();
}
public void addTeam(Team newTeam) {
mTeamList.add(newTeam);
}
public List<Team> getTeam() {
List<Team> team = new ArrayList<>(mTeamList);
for (Team teams : team) {
System.out.println("Team: " + teams.getTeam()); // this is the .getTeam method for the Team class
}
return team;
}
public Map<Team, Player> getCompleteTeam() {
Map<Team, Player> map = new HashMap<Team, Player>();
return map;
}
}
private void addTeamsLoop() {
int choice = 0;
do {
System.out.println("Add team?\n" +
"1: yes\n" +
"2: no");
choice = in.nextInt();
Team newTeam = promptForNewTeam();
mRoster.addTeam(newTeam);
}while(choice != 2);
}
private Team promptForNewTeam() {
System.out.println("What is the team name?");
String teamName = in.nextLine();
teamName = in.nextLine();
System.out.println("What is the Coach's Name?");
String coachName = in.nextLine();
return new Team(teamName, coachName);
}
Justin Dodson
4,237 PointsJustin Dodson
4,237 PointsSorry for the formatting also, the editor wouldn't style the first lines of each code snippet. Basically, the first section is my Team class, the second is the Roster class, and the last one is the driver class that is running the code that is having issues.