【问题标题】:Can't print the content at a specific index in an ArrayList object无法打印 ArrayList 对象中特定索引处的内容
【发布时间】: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() 方法。

标签: java string arraylist


【解决方案1】:

您必须在 Team 类中覆盖 toString() 方法。否则会调用Object#toString()方法。

现在它正在打印ObjecttoString() 方法的默认实现,该方法的实现方式是提供对象哈希码的无符号十六进制表示。

public class Team {

@Ovveride
public String toString() {
    //build a string for team class to print and return here.
}


}

【讨论】:

    【解决方案2】:

    一个主要问题是您的程序结构不正确:团队不应包含ArrayList&lt;Team&gt;。该 ArrayList 应该驻留在另一个类中,例如 League 或 TeamList 类。您当前的代码可能会遇到 StackOverflowException。


    编辑
    你问:

    在您的建议中,TeamList / ArrayList 类应该是 Team 的子类吗?如果我保持现在的状态,您能否更具体地说明风险?

    不,它绝对不应该是一个子类。顺理成章地想一想:棒球联盟不是一种特殊类型的棒球队,是吗?不,因此您对子类的想法不满足子类的“is-a”规则。它应该是拥有自己的非静态方法和字段的自己的类。

    【讨论】:

    • 我对OOP不是很有经验,我最初在一个单独的班级中有团队列表,但后来改变了它,只是为了让所有与团队相关的元素都在团队中。在您的建议中,TeamList / ArrayList 类应该是 Team 的子类吗?如果我保持现在的状态,您能否更具体地说明风险?谢谢
    猜你喜欢
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2015-04-17
    • 2019-05-12
    • 2015-01-21
    • 2011-11-15
    相关资源
    最近更新 更多