|
-
August 16th, 2011, 07:38 AM
#5
Re: ArrayList
 Originally Posted by part0
Thanks for the reply.
But is there a way to put the arraylist in the object class employee method?
As keang told you, I'd never put the List inside element class, unless there's no other option. Always try to make your program as much simple as possible. It'll be easy to understand and to correct.
So that whenever my main class calls the object class empolyee it will just auto add in to the arraylist.
I insist not to do that, but if that is what you need there are several options:
- Create List in main class and pass it as an argument to constructor in Employee Class, ie:
In main class
Code:
List<Employee> employees = new ArrayList<Employee>(); // Create List
//for each employee:
Employee emp1 = new Employee("firstName", "lastName", employees);
[....]
In Employee class:
Code:
//Constructor
public Employee(String firstName, String lastName, List<Employee> employees) {
this.firstName = firstName;
this.lastName = lastName;
employees.add(this);
}
- Make list static and public (or private with statics getter and setter).
In main class:
Code:
public class MainClass {
public static List<Employee> employees = new ArrayList<Employee>();
[...] // Create each your employee object
}
In Employee class:
Code:
//Constructor
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
MainClass.employees.add(this); // static access
}
In this case, you must be careful if there are several threads: The access should be synchronized.
As I dont whish to initialize like this...
// Create as many Employee objects as you need
Employee emp1 = new Employee ("lastName1", "firstName1");
Employee emp2 = new Employee ("lastName2", "firstName2");
[...]
As this will become hardcoded... you will never know how many empolyees needed to be initialize... assume that there are a lot of employees and the above method might not be a good choice to do it.
It doesn't matter. It was just an example. Nothing changes, but the way you create each Employee object: you can read them from a file or a database, or from whatever you want.
There is no need to know how many employees are for ArrayList. It'll increase its own size when needed: Don't worry about that.
Regards,
Albert.
Please, correct me. I'm just learning.... and sorry for my english :-)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|