Having trouble with ArrayList

Hey guys,
I’v got an interface named Entity.
In a separate class I am trying to make an array list of “Entity”, here is my code for it.

 Player player1 = new Player();
	public static ArrayList<Entity> entities = new ArrayList <Entity>();
	entities.add( player1);

on line 3 I keep getting an error that on the period that says “misplaced construct” and another error on line 3 where it says player1 that reads “variable decorator id expected after this token”

I’m pretty stuck here and any help would be greatly appreciated (:

All statements must be in a method body. (A statement is pretty much anything besides a declaration or an allocation, so long as the allocation is part of a declaration.)
I’m guessing these 3 lines (or at least line 3, a statement) are(is) not.

EDIT:


class demo {
   ArrayList<Object> list = new ArrayList<Object>(); //this is fine here
   list.add(null); //<-- Misplaced construct! Needs to be in a an initialization block (static or not) or a method of some type
}

Statements can also exist in a static initializer block. However, for that to work in the OP’s case, player1 would have to be static, too. The following compiles.

import java.util.ArrayList;

public class StaticTest
{
	static Player player1 = new Player();
	public static ArrayList<Entity> entities = new ArrayList <Entity>();

	static {
		entities.add(player1);
	}
}

class Player extends Entity
{}

class Entity
{}

But most likely, yes, the right answer is probably to wrap the .add() in a method or constructor.

Yes, they can also be in a static init block or even an instance init block (fancy), as stated off to the side in the code snippet, but generally and for simplicity they exist in methods.

Don’t forget, you can do the following:


entities.add(new Player());

It must be said that you should not be creating static methods or static init blocks to solve a problem - especially one as silly as this. They should be used when intended.

You should never be using static unless you know exactly what you’re doing.

To test small snippets of code you can stick it inside the objects main method but preferably you should do it inside the objects constructor or call the objects methods from the main method where you instantiate your object.

class Game {

  Player player = new Player();
  List<Entity> entities = new ArrayList<Entity>();

  public Game() {
     entities.add(player);
     System.out.println("The Game");
  }

  public static void main(String[] args) {
    new Game();
  }
}