【发布时间】:2017-02-08 03:09:24
【问题描述】:
这是要点,基本上我有这个方法,除了一个我似乎无法获得的条件。条件是如果addGame() 使用相同的两个字符串被调用两次,它不会将Game 对象存储在games ArrayList 中,因为它将返回false。我已经尝试使用 ArrayList contains() 方法来修复它,但是我创建的 JUnit 测试每次都失败。这是该方法的代码:
public class Conference {
private ArrayList<Team> teams;
private ArrayList<Player> players;
private ArrayList<Game> games;
public Conference(){
teams = new ArrayList<Team>();
players = new ArrayList<Player>();
games = new ArrayList<Game>();
}
public boolean addGame(String team1, String team2) {
Game tempgame = new Game(team1, team2, 0, 0);
Team first = new Team(team1, 0, 0, 0);
Team second = new Team(team2, 0, 0, 0);
if(!tempgame.getFirst().equals(tempgame.getSecond())){
games.add(tempgame);
first.addGamesPlayed();
second.addGamesPlayed();
teams.add(first);
teams.add(second);
return true;
}
return false;
}
Game 类如下:
package conference;
import java.util.ArrayList;
public class Game {
private String firstTeam;
private String secondTeam;
private int firstTeamGoals;
private int secondTeamGoals;
private ArrayList<Team> team;
public Game(String first, String second, int goals1, int goals2){
this.firstTeam = first;
this.secondTeam = second;
this.firstTeamGoals = goals1;
this.secondTeamGoals = goals2;
team = new ArrayList<Team>();
}
public String getFirst(){
return new String(firstTeam);
}
public String getSecond(){
return new String(secondTeam);
}
public int getFirstTeamGoals(){
return this.firstTeamGoals;
}
public int addFirstTeamGoals(){
return firstTeamGoals++;
}
public int getSecondTeamGoals(){
return this.secondTeamGoals;
}
public int addSecondTeamGoals(){
return secondTeamGoals++;
}
public boolean hasMatchup(String t1, String t2){
if(this.firstTeam.equals(t1) && this.secondTeam.equals(t2)){
return true;
}
if(this.firstTeam.equals(t2) && this.secondTeam.equals(t1)){
return true;
}
return false;
}
}
还有Team 类:
package conference;
public class Team {
private String teamName;
private int goalsScored;
private int gamesPlayed;
private int gamesWon;
public Team(String name, int totalGoals, int games, int wins){
this.teamName = name;
this.goalsScored = totalGoals;
this.gamesPlayed = games;
this.gamesWon = wins;
}
public String getName(){
return new String(teamName);
}
public int getTotalGoals(){
return goalsScored;
}
public int addGoals(){
return goalsScored++;
}
public int addGamesPlayed(){
return this.gamesPlayed++;
}
public int getGamesPlayed(){
return gamesPlayed;
}
public int addGamesWon(){
return gamesWon++;
}
public int getGamesWon(){
return gamesWon;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (obj == this) {
return true;
} else {
if (!(obj instanceof Team)) {
return false;
} else {
Team temp = (Team) obj;
return this.teamName.equals(temp.getName());
}
}
}
}
【问题讨论】:
-
是不能永远存储相同的两个字符串还是不能连续存储相同的两个字符串?
-
永远无法存储相同的两个字符串
-
字符串存储在游戏对象中,这就是为什么我不能将两个相同的对象存储在 ArrayList 中
标签: java class arraylist duplicates