如何将对象添加到对象的arraylist中

时间:2016-01-21 03:41:39

标签: java arraylist

目的是将团队添加到arraylist。每个团队都是一个具有String名称,String division,int wins和int loss的对象。

import java.util.ArrayList;
import java.util.Arrays;
public class Default 
{
     ArrayList<team> teams = new ArrayList<team>();
     team Mavericks = new team("Mavericks","Southwest",50,32);
     team Rockets = new team("Rockets","Southwest",56,26);
     team Grizzlies = new team("Memphis","Southwest",55,27);
     teams.add(team Mavericks);
     teams.add(team Rockets);
     teams.add(team Grizzlies);
}
class team
{
    String name, division;
    int win,loss;
    public team(String n,String d, int w, int l)
    {
        this.name = n;
        this.division = d;
        this.win = w;
        this.loss = l;
    }

}

3 个答案:

答案 0 :(得分:4)

 teams.add(team Mavericks);
 teams.add(team Rockets);
 teams.add(team Grizzlies);

应该是

 teams.add(Mavericks);//here Mavericks is an object
 teams.add(Rockets);
 teams.add(Grizzlies);

答案 1 :(得分:0)

您的代码存在多个问题:

  • class Default中的所有内容都应位于方法内。可能你想在main()中做到这一点。类似的东西:

    public class Default
    {
        public static void main(String[] args){
          ArrayList<team> teams = new ArrayList<team>();
          team Mavericks = new team("Mavericks","Southwest",50,32);
          team Rockets = new team("Rockets","Southwest",56,26);
          team Grizzlies = new team("Memphis","Southwest",55,27);
          teams.add(team Mavericks);
          teams.add(team Rockets);
          teams.add(team Grizzlies);
        }
    }
    
  • teams.add(team Mavericks);无法编译。您需要添加Arraylist,如:

    teams.add(Mavericks);
    teams.add(Rockets);
    teams.add(Grizzlies);
    
  • 根据java命名约定,team类应命名为Team。变量名称应为mavericksrocketsmemphis,而不是MavericksRocketsMemphis

答案 2 :(得分:0)

首先,你不能直接从类的主体调用函数。你应该把它放在构造函数中,例如

public class Default 
{
     ArrayList<team> teams = new ArrayList<team>();
     team Mavericks = new team("Mavericks","Southwest",50,32);
     team Rockets = new team("Rockets","Southwest",56,26);
     team Grizzlies = new team("Memphis","Southwest",55,27);
     public void Default()
     {
         teams.add(team Mavericks);
         teams.add(team Rockets);
         teams.add(team Grizzlies);
     }
}

此外,您应该将team从调用中删除到teams.add,以便它们成为:

teams.add(Mavericks);
teams.add(Rockets);
teams.add(Grizzlies);

我还要坚持使用大写字母和带小写字母的实例来启动类名的Java风格,例如: Maverick应该变为maverickteam应变为Team。对于标识符引用类和实例的其他人来说,这将更加明显。您可以在Code Conventions了解更多相关信息。