0

So I have the following array list:

ArrayList <Employee> employees = new ArrayList<>();

In my main method I create instances of them

public static void main(String[] args){
     Employee test = new Manager("john doe", 1000); //manager is subclass

} 

I have a method that checks that the employee object doesn't already exist, the equals method is defined in the subclasses

public void addEmployee(Employee newEmployee){
    for (int i  = 0; i < employees.size(); i++){
           if(newEmployee.equals(employees.get(i))){
               .........
           }
       }
 }

Theres more to it above, but you get the point. I need to reference the ArrayList, but if I instantiate the array list outside of the main method I can't add any variables to it, getting the error "non-static method cannot be referenced from static context" which makes sense, but I don't know how to use that method then since I can't declare it in the main method.

7
  • 1
    Declare it as a static variable. What's the issue? Commented Apr 3, 2015 at 23:28
  • How are these three segments of code even related? It's not clear what you're trying to do or what's preventing you. Commented Apr 3, 2015 at 23:31
  • declare the test variable as static? I do that and I get an error saying illegal start of expression Commented Apr 3, 2015 at 23:31
  • @David it's a watered down version of all my code. I have a main superclass of employee, a subclass of manager, and subclass of worker, then this main class that tests the methods and constructors and such. Commented Apr 3, 2015 at 23:33
  • 1
    seems like a Set would be a more suitable container than an ArrayList Commented Apr 3, 2015 at 23:34

1 Answer 1

2

Unless you want to create a class for managing employee's you'll want to make your method and collection static

static ArrayList <Employee> employees = new ArrayList<>();

public static void addEmployee(Employee newEmployee){
    for (int i  = 0; i < employees.size(); i++){
           if(newEmployee.equals(employees.get(i))){
               .........
           }
       }
 }

@muued has a point. There are other data structures in java then ArrayList. When in doubt I look at this:

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I wasn't aware that I could declare ArrayList as static like that and still allow it to have it's elements be modified and still function properly.
@BoristheSpider deserves the credit for that. He spotted it first.
I'm new to this place is there a way to give him the best answer?
He didn't post an answer but his comment can be upvoted.

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.