1

enter image description here

As you can see I have a StaffMember class and trying to make a list of StaffMember objects, but when I go to get them out of the list I get errors. What could be causing this (Or java lists are different from other languages).

2 Answers 2

10

Since you're not using a generic List variable, the compiler has no way of knowing what type of objects the List contains, and so you'll have to cast the object returned by the get(...) method to the type you believe it to be.

A better solution is to declare your list variable to be a generic List<StaffMember>.

public class StaffList {    
    private List<StaffMember> list;
Sign up to request clarification or add additional context in comments.

3 Comments

"Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18)
@TristanCunningham: You can still use a List variable and assign it an ArrayList object since the ArrayList class implements the List interface, and in fact this is the preferred way to do it.
@TristanCunningham While it's a better practice to use a List, you can switch List<StaffMember> with ArrayList<StaffMember>.
1

I think your life will be better if you do it this way:

public class Staff {
    private List<StaffMember> roster;

    public Staff() {
        this.roster = new ArrayList<StaffMember>();
    }

    // add the rest
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.