I've been a professional developer for a lot of my career.. I'm a beginner at Java but not at Coding. The problem below is just a training exercise as such but I'd like to understand whats going on. I'm just trying to build a LIST of elements. Please excuse me that I choose it to be a list of English Football teams.. that's just a detail.
So I have defined my own class 'Team', and I'm building a List of TEAMs. I set the values of my three attributes (2 public, one private), print out some of the detail, add to the list...repeat 3 times... then print to the list
And my list is just the last item, added 4 tines. I've experimented with using different variable names for my Team in the Main class, and that fixes it... But I would expect my instance of team to have different values each time I add it.
OUTPUT :Team NextTeam = new Team(); List<Team> premL = new ArrayList<Team>(); NextTeam.CityName = "Preston"; NextTeam.ExtraName = "North End"; NextTeam.setColour("Blue"); System.out.println(NextTeam); premL.add(NextTeam); NextTeam.CityName = "Plymouth"; NextTeam.ExtraName = "Argyle"; NextTeam.setColour("Green and black"); premL.add(NextTeam); System.out.println(NextTeam.toString()); NextTeam.CityName = "Manchester"; NextTeam.ExtraName = "City"; NextTeam.setColour("Light Blue"); premL.add(NextTeam); System.out.println(NextTeam); NextTeam.CityName = "Gillingham"; NextTeam.ExtraName = ""; NextTeam.setColour("Blue"); premL.add(NextTeam); System.out.println(NextTeam); Team.printTeams(premL); } }
Team{CityName='Preston', ExtraName='North End'}
Team{CityName='Plymouth', ExtraName='Argyle'}
Team{CityName='Manchester', ExtraName='City'}
Team{CityName='Gillingham', ExtraName=''}
Gillingham
Gillingham
Gillingham
Gillingham
If I use a different 'variable' name for my Team, that does fix it, but that's not the point; I'm trying to understand what is going on
(Only changed code here, the 2nd team added using a different variable name
ExtraTeam.CityName = "Plymouth"; ExtraTeam.ExtraName = "Argyle"; ExtraTeam.setColour("Green and black"); premL.add(ExtraTeam); System.out.println(ExtraTeam.toString());
Then the output is;
Team{CityName='Preston', ExtraName='North End'}
Team{CityName='Plymouth', ExtraName='Argyle'}
Team{CityName='Manchester', ExtraName='City'}
Team{CityName='Gillingham', ExtraName=''}
Gillingham
Plymouth Argyle (note change)
Gillingham
Gillingham