添加到对象在Java中一个固定的集合(数组)方法 [英] Method for adding Objects into a fixed collection(Array) in Java

查看:903
本文介绍了添加到对象在Java中一个固定的集合(数组)方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与所谓的雇工一个超类和两个子类称为讲师和助理继承层次。除了这个我做了一个名为类主题有员工组成的数组。

我想在这里做的是创造增加雇工对象到数组的方法。结果
我做了对ArrayList的工作方式相同,但它似乎并没有为数组。

如果有可能,我怎么能创建使用数组做同样的事情的方法?

 公共类主题{    私人字符串主题code;
    私人雇工[]的员工;    公共科目(科目字符串code){
        this.subject code =主题code;
        雇工[] =员工新雇工[5];
    }    公共无效SETSUBJECT code(字符串code){
        this.subject code = code;
    }    公共字符串getSubject code(){
        返回this.subject code;
    }    公共布尔addStaff(雇工雇工){
        如果(雇工的instanceof讲师||雇工的instanceof助理){
            this.employees.add(雇工);
            返回true;
        }其他{
            返回false;
        }
    }
}


解决方案

您需要使用ArrayList

 公共类主题
{
    私人字符串主题code;
    私人最终名单<员工>员工=新的ArrayList<员工>();    公共科目(科目字符串code){
        this.subject code =主题code;
}公共布尔addStaff(雇工雇工){
        返回this.employees.add(雇工);
 }

或者,如果你仍然想使用数组:

 公共布尔addStaff(雇工雇工){
        清单<员工> tempList = Arrays.asList(this.employees);
    布尔补充= tempList.add(雇工);
    this.employees = tempList.toArray(this.employees);
    增加收益;
 }

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<Employee> employees = new ArrayList<Employee>();

    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<Employee> tempList = Arrays.asList(this.employees);
    boolean added = tempList.add(employe);
    this.employees = tempList.toArray(this.employees);
    return added;
 }

这篇关于添加到对象在Java中一个固定的集合(数组)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆