anonymous
anonymous

Reputation: 313

Cannot resolve symbol "add" while adding class object to an ArrayList

I am working on a class for an Address Book Application on Java called "AddressBook.java", which I have written the following code:

package com.company;
import java.util.ArrayList;

class AddressBook {
    ArrayList<AddressEntry> addressEntryList = new ArrayList<AddressEntry>();
    AddressEntry test = new AddressEntry("john", "doe", "yes", "no", "maybe", 1, "I guess", "ok");
    
    addressEntryList.add(test);
}

Since I was just testing the test object, I had to give random values for the variables from my AddressEntry class and it seemed to work well. However, when I ran it in IntelliJ, I received the error

Cannot resolve symbol 'add'

This made the adding method not working.

Upvotes: 0

Views: 9882

Answers (2)

abbujaansboy
abbujaansboy

Reputation: 99

You can only use your ArrayList object methods (for example .add, .remove etc) inside other methods, this can also be the main method (obviously)

Upvotes: 0

Cole Henrich
Cole Henrich

Reputation: 165

You need to put it inside the main method.

Like this:

package com.company;
import java.util.ArrayList;

class AddressBook {
    public static void main(String[] args){
        ArrayList<AddressEntry> addressEntryList = new ArrayList<AddressEntry>();
        AddressEntry test = new AddressEntry("john", "doe", "yes", "no", "maybe", 1, "I guess", "ok");
        addressEntryList.add(test);
    }
}

Java cannot resolve method calls if the method call does not call from any method.

Upvotes: 4

Related Questions