I'm getting an error in my Java code but I can't see whats wrong with it. Help?

前端 未结 5 1714
轻奢々
轻奢々 2021-01-23 14:20

The error i\'m getting is in the fillPayroll() method in the while loop where it says payroll.add(employee). The error says I can\'t invoke add() on an array type Person but th

相关标签:
5条回答
  • 2021-01-23 14:28

    payroll is an array. You are invoking method on an array. This is not possible.

    0 讨论(0)
  • 2021-01-23 14:29

    Instead of using an array use an ArrayList. You'll be much happier.

    Arrays cannot be resized once created. All the boilerplate for managing that is done by ArrayList. Using arrays with subclasses in elements has other issues too (around covariance). Probably the only line you need to change is:

    private final List<Person> payroll = new ArrayList<Person>();
    

    Lists have an add() method. Arrays don't.

    0 讨论(0)
  • 2021-01-23 14:44

    If Class B extends A:

    A a=new B();

    but not:

    B b=new A();

    0 讨论(0)
  • 2021-01-23 14:45

    Since payroll is an array it would need to be

    payroll[index].add(employee);
    
    0 讨论(0)
  • 2021-01-23 14:50

    If for whatever reason you can't use collections. you want to turn:

    payroll.add(employee);
    

    in to:

    this.add(employee);
    
    0 讨论(0)
提交回复
热议问题