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?

Community
  • 1
  • 1
Alan2
  • 23,493
  • 79
  • 256
  • 450
  • 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.*`? – Jack Jun 16 '12 at 17:50

2 Answers2

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]);
    }
  }
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 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 ? – Alan2 Jun 16 '12 at 18:00
  • 1
    @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... – KidTempo Jun 16 '12 at 21:26
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));
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • Why does it need to be inside a method? – Alan2 Jun 16 '12 at 18:06
  • 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. – Kumar Vivek Mitra Jun 16 '12 at 18:09