【问题标题】:Java: How do I initialize an array with objects of a class at the time of object creation?Java:如何在创建对象时使用类的对象初始化数组?
【发布时间】:2020-09-01 01:45:07
【问题描述】:

我正在编写代码,我想返回冠军球队的排名板。

我想创建一个 ArrayList 包含类名 Team 的对象,这样我就可以返回所有团队的整个排名板。

我希望它在创建对象时完成,在这方面我有以下代码不起作用:

// the constructor
public Team(String name) {
        this.name = name;
        teams.add(this);
    }

public List<Team<T>> teams = new ArrayList<>();

我还尝试在添加球员的方法中初始化球队:

public boolean addMembers(T player) {
        if (members.contains(player)) {
            System.out.println("Player already in the list");
            return false;
        } else {
            members.add(player);
            teams.add(this);
            System.out.println(player.getName() + " has been picked for team " + this.name);
            returnClassament();
            return true;
        }
    }

【问题讨论】:

  • 请解释"is not working"。无论如何,您可能可以将团队列表作为构造函数参数传递,而不是使其成为 Team 类中的字段。
  • 等等,你有每个团队内部的团队列表吗?比如,一个团队是否由许多不同的团队组成?这背后的逻辑是什么?
  • @Amongalen 我可以创建不同类型的球队:篮球、足球等。在每支球队的内部,我添加了球队球员
  • @Pshemo 为了创建一种显示排名板的方法,我想创建一个团队数组。当我打印数组时它是空的,所以我认为某处是错误的。但是很高兴知道我们在创建对象时如何做到这一点
  • 拥有每个团队中所有团队的列表毫无意义。您应该创建一个课程Championship 或类似的东西,并让所有团队参与其中。你甚至自己说过“我想归还冠军队伍的排行榜”——不是队伍中的队伍,而是冠军队伍中的队伍。

标签: java arraylist conditional-statements


【解决方案1】:

如果我没有误解你,这种方法可能会有所帮助

     public Team(String name, List<Team> list) {
        this.name = name;
        if(list != null) list.add(this);
    }

【讨论】:

    【解决方案2】:
    import java.util.ArrayList;
    
    public class Team{
    //we create private variables here because only the constructor is accessing them
    private String name;
    private int score;
      
      //create a static ArrayList that holds type of class Team here so all objects refer to one and it is not copied over to each object (as per i've learned because static is confusing)
      public static ArrayList<Team> teams=new ArrayList<Team>(); 
    
      
      public Team(String name,int score){
        this.name=name;
        this.score=score;
        //tell the program that the instance variable has the same value as the parameter
        teams.add(this);
        //adding the object to the ArrayList
      }
    
    //This is not necessary; it just prints the values of each object in the ArrayList
    public void printTeamStats(){
      System.out.println(name+" "+score);
    }
        }
    

    【讨论】:

      【解决方案3】:

      冠军类的AddPlayer方法可用于向系统添加玩家

      Void addPlayer (String surname, Strong country, integer age, String position) {
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-26
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多