1

I am trying to run the following code that I found marked as correct on StackOverflow:

Code on SO

List<Integer> intList = new ArrayList<Integer>();
for (int index = 0; index < ints.length; index++)
{
    intList.add(ints[index]);
}

When I run the code I get an error: Syntax error on token ";", { expected after this token on the line starting with List

Is there something I am missing?

1
  • 1
    Chances are that you are using a JDK version < 1.5 so you don't have support for generics. Either because syntax seems correct here. Did you also import package java.util.*? Commented Jun 16, 2012 at 17:50

2 Answers 2

4

You have probably placed this code block at the top level of your class. It has to go inside a function:

class Foo {
  public static void main(String[] args) {
    int[] ints = {1, 2, 3};
    List<Integer> intList = new ArrayList<Integer>();
    for (int index = 0; index < ints.length; index++)
    {
        intList.add(ints[index]);
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes this is correct. It works now. But how did you know this was the problem and why doesn't it work at the top level ?
@Gemma Java objects don't do anything on their own. The general principal is that the methods (and constructor, I guess) is where the action happens. Putting code at the top level is not allowed because it would never be called. Actually, this is probably true of all object oriented languages that aren't script based...
1

Try this

Have you added these below line inside a method, like this

public void go(){

List<Integer> intList = new ArrayList<Integer>();

for (int index = 0; index < ints.length; index++)
{
    intList.add(ints[index]);
}

}

Moreover,

if you want to add an Array into a List, do this way

List<Integer> intList = new ArrayList<Interger>(Arrays.asList(ints));

2 Comments

Why does it need to be inside a method?
for (int index = 0; index < ints.length; index++) { intList.add(ints[index]); } will need to be inside a method..either main method or any other, cause you can use only instance variable outside an method inside a class, not any loops etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.