我在尝试用 Java 创建 ArrayList
时遇到了问题,但更具体地说,是在尝试向其添加 add()
时遇到了问题。我在 people.add(joe);
行遇到语法错误...
Error: misplaced construct: VariableDeclaratorId expected after this token.
at people.add(joe);
^
据我了解,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);
}
static String name;
static double age;
static double height;
static double weight;
为什么这些变量被定义为static?
看起来你是在 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)
}
}