Reputation: 10610
I tried to create a program with a linked list.
package com.delta.memory;
import java.util.ArrayList;
/**
* Lists
*/
public class Lists {
ArrayList<String> DaysOfTheWeek = new ArrayList<String>();
DaysOfTheWeek.add("Sunday");
DaysOfTheWeek.add("Tuesday");
DaysOfTheWeek.add("Wednesday");
DaysOfTheWeek.add("Thursday");
DaysOfTheWeek.add(1, "Monday");
}
But it gives the following compilation errors:
Error:(11, 22) error: <identifier> expected
Error:(11, 23) error: illegal start of type
And also a warning:
Cannot resolve symbol 'add'
Please help.
Upvotes: 0
Views: 5307
Reputation: 3287
You cannot execute code directly inside your class. It should be inside a method or in a static block:
import java.util.ArrayList;
/**
* Lists
*/
public class Lists {
private static List<String> daysOfTheWeek = new ArrayList<String>();
static {
daysOfTheWeek.add("Sunday");
daysOfTheWeek.add("Tuesday");
daysOfTheWeek.add("Wednesday");
daysOfTheWeek.add("Thursday");
}
}
In Java, static keywork indicates that the field or the method is directly to the Class and then shared accross all its instances. In other words, it is not managed by an object instance but by the defining class itself).
Using static, you can - as in you example - provide global initialization to any instance of a class. In your cas, your daysOfWeek list will be available to all your Lists instance.
Note 1: to statically fill the list I had to declare it static. Note 2: Instead of declaring the list as an arrayList, I declare it as a List - a more generic type and created it as an ArrayList.
BTW, you should find another name for your class, related to your business.
Upvotes: 1
Reputation: 393781
Your code should be inside a method.
public class Lists {
public static void main (String[] args)
{
ArrayList<String> DaysOfTheWeek = new ArrayList<String>();
DaysOfTheWeek.add("Sunday");
DaysOfTheWeek.add("Tuesday");
DaysOfTheWeek.add("Wednesday");
DaysOfTheWeek.add("Thursday");
DaysOfTheWeek.add(1, "Monday");
}
}
Upvotes: 3