【发布时间】:2014-01-05 17:55:25
【问题描述】:
我有以下团队类:
import java.util.ArrayList;
import java.util.Random;
public class Team {
private String name;
private int noOfTeams;
public ArrayList<Team> teamList;
//no-arg constructor, creates the array list of default teams
Team(){
this.teamList = new ArrayList<Team>();
teamList.add(new Team("Brondby IF"));
teamList.add(new Team("AaB"));
teamList.add(new Team("Viborg FF"));
teamList.add(new Team("Esbjerg"));
teamList.add(new Team("FC Copenhagen"));
teamList.add(new Team("Randers FC"));
teamList.add(new Team("FC Midtjylland"));
teamList.add(new Team("FC Nordsjaelland"));
teamList.add(new Team("Odense BK"));
teamList.add(new Team("AGF Aarhus"));
teamList.add(new Team("FC Vestsjaelland"));
teamList.add(new Team("Sonderjyske"));
}
//constructor using name
Team(String name){
this.name =name;
}
//get name of team
public String getName(){
return name;
}
//get the size of the arrayList
public int getSize(){
return teamList.size();
}
//get an element at a specific index i
public Team getIndex(int i){
return teamList.get(i);
}
和一个客户端(测试)类,我尝试使用上面定义的getIndex() 方法在ArrayList 中的第二个位置(例如)打印元素:
public class TestTeam {
public static void main(String[] args){
Team teamList = new Team();
System.out.print(teamList.getIndex(2));
}
}
以上内容为我提供了职位:Team@45a1472d。我尝试使用:
System.out.print((teamList.getIndex(2)).toString());
但结果相同。当我调试它时,teamList.getIndex(2) 的值似乎为空。我看不出我对 Team 类中的方法做错了什么,感谢任何提示/帮助。
【问题讨论】:
-
“上面给我的位置是:Team@45a1472d” 你需要重写从
Team类中的对象类继承的toString()方法。