Alan2
Alan2

Reputation: 24572

new ArrayList<Integer>(); giving a syntax error in Java

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?

Upvotes: 1

Views: 5962

Answers (2)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

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));

Upvotes: 1

NPE
NPE

Reputation: 500693

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]);
    }
  }
}

Upvotes: 4

Related Questions