java 集合添加数组,添加到对象在Java中一个固定的集合(数组)方法

I have made an inheritance hierarchy with one super-class called Employe and two subclasses called Lecturer and Assistant. In addition to this I made a class called Subject which has an array of employees.

What I want to do here is create a method for adding Employe objects into the array.

I made the same one that works for ArrayList, but it didn't seem to work for Arrays.

If it is possible, how can I create a method for doing the same thing with arrays?

public class Subject {

private String subjectcode;

private Employe[] employees;

public Subject(String subjectcode) {

this.subjectcode = subjectcode;

Employe[] employees = new Employe[5];

}

public void setSubjectcode(String code) {

this.subjectcode = code;

}

public String getSubjectcode() {

return this.subjectcode;

}

public boolean addStaff(Employe employe) {

if (employe instanceof Lecturer || employe instanceof Assistant) {

this.employees.add(employe);

return true;

} else {

return false;

}

}

}

解决方案

You need to use an ArrayList :

public class Subject

{

private String subjectcode;

private final List employees = new ArrayList();

public Subject(String subjectcode){

this.subjectcode = subjectcode;

}

public boolean addStaff(Employe employe){

return this.employees.add(employe);

}

Or if you still want to use an array :

public boolean addStaff(Employe employe){

List tempList = Arrays.asList(this.employees);

boolean added = tempList.add(employe);

this.employees = tempList.toArray(this.employees);

return added;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值