Results 1 to 4 of 4
- 03-12-2010, 04:21 PM #1
Member
- Join Date
- Mar 2010
- Posts
- 2
- Rep Power
- 0
add object to ArrayList (object is from extends other class)
hi
i'm trying do develop a school
i created afew classes already:
school.class
person.class
student.class extends person
employee.class extends person
in the school class i want to create a method to add a student to the arraylist of persons and a method that only counts the objects wich are from the student class and another method wich is used to count the object from the employee class.
Can you give me some hints?Java Code:public class School { private ArrayList<Persons> persons = new ArrayList<Persons>(); public void addemployee (Employee employee){ if (employee !=null){ personen.add(employee); } // i think this doesn't work? } public int countEmployee{ //don't know how to count these }
- 03-13-2010, 03:54 AM #2
There are several ways to do what you want to do. Here are a few.
Create separate lists for employees and students. You can combine the lists on demand in a getPersons() method.
Add counters for employees and students. Update the counters in the addEmployee(), addStudent(), etc. methods.
Loop through the list to count students and employees on demand.
- 03-13-2010, 12:24 PM #3
Member
- Join Date
- Mar 2010
- Posts
- 2
- Rep Power
- 0
yes, i had come to that solution aswell but I realy want only just one list of persons (the object student is sligthly different from the object employee) so isn't it possible for java to recognice each object?
- 03-15-2010, 08:44 PM #4
If you have one list of Person, you can use the instanceof operator to determine which sub-type you are dealing with.
With two lists, you implement a method like this:
This approach allows for much more flexibility as your design grows. You should always create a new List and return it, rather than the instance object, as the caller can modify the list you return.Java Code:public List<Person> getPersons() { final List<Person> personList = new ArrayList<Person>(); personList.addAll(studentList); personList.AddAll(employeeList); return personList; }
Similar Threads
-
how to pass an arraylist from an object back to the parent object that it was created
By george_a in forum New To JavaReplies: 1Last Post: 03-04-2009, 06:14 PM -
Object ArrayList - increment solution needed badly!!
By rugbyGeek in forum New To JavaReplies: 4Last Post: 03-08-2008, 12:47 AM -
object instantiation and arrayList
By lockmac in forum New To JavaReplies: 5Last Post: 08-09-2007, 06:25 PM -
how to return an object from an arraylist
By elizabeth in forum New To JavaReplies: 1Last Post: 07-30-2007, 06:57 PM -
Creating object of Type Object class
By venkatv in forum New To JavaReplies: 3Last Post: 07-17-2007, 03:33 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks