Hello All,

I'm currently having an issue trying to retrieve elements that have been saved within my arraylist.

I currently have two classes, Project and Staff.

In the Project class, i have declared an ArrayList of type staff, as seen below:

public static ArrayList<Staff> staff = new ArrayList<Staff>();

In the Staff.java file, i have this:

private static String name;
private static String staffID;

public Staff(String name, String staffID) {
    this.name = name;
    this.staffID = staffID;
}

and then a really simple getter method that grabs the staff name (still in Staff.Java):

public static String getName(String name) { 
    return name; 
}

In Project.java (the one with the arraylist), i add a new staff member via the code:

staff.add(new Staff("Bob", "11"));
staff.add(new Staff("Harry", "2"));

which stores it successfully into the arraylist.

I then convert the arraylist to an array of objects via:

Object[] array = staff.toArray();

And...this is where i am stuck. I cannot seem to output the individual elements of this object array. I simply get the same result (Harry) returned twice when i output using:

for( int i = 0; i < array.length; i++) {
    System.out.println(Staff.getName());
}

I should be getting Bob, Harry, yet i get Harry, Harry printed.

From what i understand, i am iterating through the object array and finding the correct number of elements. However, i cant seem to output the variable that is stored within each index.

Any help would be greatly appreciated :D

** I'm using JDK 1.6

Thanks,

First: the getName method is incorrectly defined as static. That's wrong - it doesn't apply to the whole class, but to each individual instance. Ditto the variables - they must not be static - each instance of Staff has its own name and ID.

for( int i = 0; i < array.length; i++) {
    System.out.println(array[i].getName());
}

Each element of the array is an instance of Staff, so you can call Staff's methods directly on the array elements.
You don't need to convert to an array - the for-each loop wprks well with your arraylist

for (Staff person : staff) {
   system.out.println(person.getName));
}

Thanks James for your reply,

I managed to add the 2nd code block into my original Project class, and found that

public static String getName(String name) { 
    return name; 
}

did not need the String name as a parameter.

Upon removal it now works :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.