import java.util.ArrayList;
import java.util.List;
public class Test {
List<String> list= new ArrayList<String>();
list.add("sdp");// This line isn't working
}

- 10,631
- 12
- 36
- 56

- 11
- 1
-
5Wrap it in a method/constructor/initialization block. – Nicholas K Mar 31 '19 at 14:03
2 Answers
The problem is you are in the class context, can can just declare and initialize variables here. To call a method on variables you need to do it in the constructor:
public class Test {
List<String> list = new ArrayList<String>();
public Test() {
list.add("sdp");
}
}
Or in a method:
public class Test {
List<String> list= new ArrayList<String>();
private void test() {
list.add("sdp");
}
}
Beside that use field variables only if necessary.
If you want to initialize a List
with elements you can use Arrays.asList()
:
List<String> list = Arrays.asList("sdp", "test");
If you have only one element use Collections.singletonList()
(this returns an immutable list, so you can not add any elements afterwards):
List<String> list = Collections.singletonList("sdp");

- 10,631
- 12
- 36
- 56
You can only have the variable declaration and initialization, method declaration (in case of Abstract class) and definition inside the class body (so you can't have expressions). If you want to initialize a variable, you can either do it inline or wrap the initialization logic inside an initialization block. Please look at the docs for various ways of initializing class attributes.
Below is one way of initializing class attributes.
import java.util.ArrayList;
import java.util.List;
public class Test {
List<String> list= new ArrayList<String>();
{
list.add("sdp"); //this will be executed when you create an instance of class `Test`.
}
}

- 117
- 1
- 3