I’m running into a problem when trying to create an ArrayList in Java, but more specifically when trying to add() to it. I get syntax errors on the people.add(joe); line…
Error: misplaced construct: VariableDeclaratorId expected after this token.
at people.add(joe);
^
It’s my understanding that an ArrayList would be better than an array for my purposes, so my question is, is that the case and if not, where am I going wrong with my syntax?
This is my code…
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);
}
Why are these variables defined as static?
It looks like you are doing it in the Person class. Doing it in the class is OK(it can be done), but doesn’t make much sense if you are creating an ArrayList of Person objects.
The main point here is that this must be done within an actual method or constructor or something (an actual code block). Again, I am not entirely sure how useful an ArrayList of type Person would be inside of a Person class.