0

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.

2
  • 2
    You cannot just stick random code in a class. Code must go in a block. Also, please stick to Java naming conventions - variables are in camelCase. Commented Oct 11, 2014 at 18:09
  • Your code should be inside a method. Commented Oct 11, 2014 at 18:44

2 Answers 2

3

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");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

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.