• Post Reply Bookmark Topic Watch Topic
  • New Topic

Add object to array  RSS feed

 
Heb Heather Gagnon
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I need to add an employee object that my program has created and put it in a array list. I am not using a file because I'm so new to this. My employee object is first name, last name, and a generated id. I am trying to add a new employee object to an array like this:

public static Employee addEmployees(String first,String last) //this method is in my employee class
{
Employee employee = new Employee(firstName,lastName);
employee.setFirstName(firstName);
employee.setLastName(lastName);
employee.getId();
employeefile.addEntry(employee); //add employee object to array list


return employee;

}

I have a separate class to set up array
public class EmployeeFile
{
public ArrayList<Employee> employees; //instance variable


public EmployeeFile() //constructor no arguments
{
employees = new ArrayList<>();
}

void addEntry(Employee employee) //method to add employee to array
{
this.employees.add(employee);
}


public ArrayList<Employee> getEmployeesList() //method to get employee from array
{
return employees;
}



}
I don't know if I am doing this properly. I have been trying to figure out how to println it to test, but I can't seem to do that or know which class to put this function in. I know about for loops and such, just don't know how to implement it or where. Any help is appreciated.
 
Daryl Cofer
Greenhorn
Posts: 19
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In order to test your code with println, you're going to have to create a Main class and inside it put a main() method.
The class and method signature should look like this:



That should get you on the right track to debugging your code and making sure it works as intended.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Daryl Cofer wrote: . . . The class and method signature should look like this:
. . .
That should get you on the right track to debugging your code and making sure it works as intended.
Good advice, but I would prefer this slightly longer format so as to get the main method even shorter than in Winston's excellent FAQ.Once you have that working with 1 employee, you should find it easy to add a second
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!