问题
I am trying to add a string to an ArrayList in Java, but I can't seem to get it to work.
Currently, I have the following code:
List food_names = new ArrayList();
food_names.add("pizza");
Why do I get these errors:
- Syntax error on token ""pizza"", delete this token
- Syntax error on token(s), misplaced construct(s)
回答1:
You have to use food_names.add("pizza")
in function, for example:
public void AddFood()
{
food_names.add("pizza");
}
Hope helps
回答2:
why don't you use List Generics List interface.
List<String> food_names = new ArrayList<String>();
food_names.add("pizza");
This shouldn't give any error.
回答3:
I suspect that those statements are at the top level of a class. The first one is OK there, but the second one can only be inside a code block; e.g. a method or constructor body. See @tomasBull's answer for an example of where you can do that.
The compiler is trying to parse food_names.add("pizza");
as a declaration, and is getting thoroughly confused.
回答4:
There is another solution
food_names.add(new String("pizza"));
回答5:
Class Example
{
//**Do not place it here.**
List food_names = new ArrayList();
food_names.add("pizza");
public static void main(String[] args)
{
//**You should place it here**
List food_names = new ArrayList();
food_names.add("pizza");
}
}
回答6:
I'm not sure you're initializing the ArrayList correctly. Try
ArrayList<String> food_names = new ArrayList<String>();
Also double check you've imported ArrayList. Or try removing the quotation marks around pizza. Disclaimer: I'm probably wrong but I'm laying in bed typing this from my phone, haha. Good luck.
来源:https://stackoverflow.com/questions/5055936/unable-to-add-a-string-to-an-arraylist-misplaced-constructs