将对象添加到一个数组 [英] Adding objects to an array

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

问题描述

我一直在寻找如何添加元素的问题到一个数组<一个href=\"http://stackoverflow.com/questions/5061721/how-can-i-dynamically-add-items-to-a-java-array\">How我可以动态地将项目添加到Java数组?。

I have been looking at questions of how to add elements to an array How can I dynamically add items to a Java array?.

我不明白如何添加一个类类型,而不是像数据类型字符串的对象。我怎么做到这一点,当对象患者有不同的数据类型?我不能让我的头左右,是如何把一个病人对象的属性到一个数组。

I do not understand how to add objects of a class type, not a datatype like String. How am I supposed to do this, when the object patient has various datatypes? What I can't get my head around, is how to put the attributes of a Patient object into an array.

Class Patient{

    public Patient(String ptNo, String ptName, int procType) throws IOException
    {
        Patient.patientNo =  ptNo;
        Patient.patientName = ptName;
        Patient.procedureType = procType;
    }
}

另外一类:

public static void main(String[] args) throws IOException
    {
        Patient [] patients;
        Patient p = new Patient(null, null, 0);

        int i = 0;
        for (i = 0; i < 2; i++)
        {
        patients.add(p);
        }
    }

我明白我缺少明显的,只有来到这里,用尽其他资源后。

推荐答案

您需要使用索引来访问数组

You need to access an array using the indexes

patients[i] = p;

但你需要初始化以及之前。

but before that you need to initialize it as well.

Patient [] patients = new Patient[10]; // random init

既然你想他们是动态的,尽量使用ArrayList和不断增加的对象吧。

Since you want them to be dynamic, try to use an ArrayList and keep adding the objects to it.

List<Patient> patients = new ArrayList<>();
patients.add(p);

这篇关于将对象添加到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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