Back to Topic Index

Java help

By Gibble00 on 02/04/2010
Okay, I know some of yall can do Java programming.

I'm dealing with arrays of People (class) that have several properties such as age (int), gender (char), and salary (int) and I need an instance method that adds a new item of type Person to the array of existing Persons (called 'people') and I'm having trouble adding them to this array. This is the code I need to edit:

void addPerson (Person p){ // adds a person p to the end of the population instance variable

// You complete this method
}

I'm having trouble doing this I think, I don't actually know if this is what's not working for me because my program doesn't have any errors but it won't run.

I tried using ArrayList.add but that returns a void result and I need a result of type Person.



By Tnuac on 03/04/2010
Been a while since i did all that i'm afraid =s

By Maxrobinsun on 18/04/2010
I imagine that i'm probably too late to help but:
import java.util.*;
// Assume you have some people class already
ArrayList<People> names;
names = new ArrayList<People>();
Person p = new person(constructors here);
names.add(p);
...
Person[] result = new Person[names.size()];
names.toArray(result);

It would be something like that I believe.


However, if the array already exists then i'm afraid, you would have to find the nearest empty item in the array and add it there, or if the array is full, create a new one of size: Old + 1 and then copy it over and insert the new element. (Try Arrays.copyOf. EDIT: URL screws with tags: http://java.sun.com/javase/6/docs/api/java...28boolean\[],%20int%29, again not sure if it will work but looks like an option)

Or at least it should look something like that, it's been a while since I did Java



Back to Topic Index

Developed by Mojo.