Java ArrayList如何添加类

Jar*_*rod 2 java arrays arraylist

我在尝试创建ArrayListJava 时遇到了问题,但更具体地说是在尝试add()使用它时.我在线上遇到语法错误people.add(joe); ......

Error: misplaced construct: VariableDeclaratorId expected after this token.
    at people.add(joe);
                  ^
Run Code Online (Sandbox Code Playgroud)

我的理解是,ArrayList为了我的目的,一个数组会比一个数组更好,所以我的问题是,是这样的情况,如果没有,我的语法错在哪里?

这是我的代码......

import java.util.ArrayList;

public class Person {
    static String name;
    static double age;
    static double height;
    static double weight;

    Person(String name, double age, double height, double weight){
        Person.name = name;
        Person.age = age;
        Person.height = height;
        Person.weight = weight;
    }

    Person joe = new Person("Joe", 30, 70, 180);
    ArrayList<Person> people = new ArrayList<Person>();
    people.add(joe);
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*gis 5

static String name;      
static double age;
static double height;
static double weight;
Run Code Online (Sandbox Code Playgroud)

为什么这些变量定义为静态

看起来你是在Person类中做的.在类中执行它是可以的(可以完成),但是如果要创建Person对象的ArrayList则没有多大意义.

这里的要点是必须在实际的方法或构造函数或其他东西(实际的代码块)中完成.同样,我不完全确定Person类型的ArrayList在Person类中是多么有用.

import java.util.ArrayList;

public class Person 
{                   // Don't use static here unless you want all of your Person 
                    // objects to have the same data
   String name;
   double age;
   double height;
   double weight;

   public Person(String name, double age, double height, double weight)
   {
      this.name = name;       // Must refer to instance variables that have
      this.age = age;         // the same name as constructor parameters
      this.height = height;    // with the "this" keyword. Can't use 
      this.weight = weight;    // Classname.variable with non-static variables
   }

}

public AnotherClass 
{
   public void someMethod()
   {
      Person joe = new Person("Joe", 30, 70, 180);
      ArrayList<Person> people = new ArrayList<Person>();
      people.add(joe);
      Person steve = new Person("Steve", 28, 70, 170);
      people.add(steve);            // Now Steve and Joe are two separate objects 
                                    // that have their own instance variables
                                    // (non-static)
   }
}
Run Code Online (Sandbox Code Playgroud)