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).

Tristan Cunningham
  • 909
  • 2
  • 10
  • 24

2 Answers2

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;
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    "Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18) – isnot2bad Nov 09 '13 at 23:55
  • @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. – Hovercraft Full Of Eels Nov 09 '13 at 23:56
  • 1
    @TristanCunningham While it's a [better practice to use a List](http://stackoverflow.com/questions/17459553/why-do-some-people-use-the-list-base-class-to-instantiate-a-new-arraylist), you can switch `List` with `ArrayList`. – Steve P. Nov 09 '13 at 23:58
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
}
duffymo
  • 305,152
  • 44
  • 369
  • 561