Java ArrayList如何添加类

标签 java arrays arraylist

<分区>

我在尝试用 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)
   }
}

关于Java ArrayList如何添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11111339/

相关文章:

arrays - 如何在 Swift 中按属性值对自定义对象数组进行排序

java - 通过正则表达式从字符串中删除前导换行符?

java - 如何在同一个矩形上进行两次触摸

arrays - 根据另一个数组的排序顺序对多个数组进行排序

javascript - js/reactjs - 如何将数据从 json 重建为数组?

java - 将对象数组转换为 ArrayList 时出现问题

java - 如何通过按键盘上的 DELETE 删除 JTable 中的行

java - Hikari 驱动程序不支持获取/设置连接的网络超时。 (com.mysql.jdbc.JDBC4Connection.getNetworkTimeout()I)

java - 如何在 Java 中创建具有重复模式的 String ArrayList

Java - Vector 与 ArrayList 性能 - 测试