简体   繁体   English

如何在 Java 中声明动态对象数组?

[英]How to declare a dynamic object array in Java?

I want to ask a question about Java.我想问一个关于Java的问题。 I have a user-defined object class, student, which have 2 data members, name and id.我有一个用户定义的对象类,student,它有 2 个数据成员,name 和 id。 And in another class, I have to declare that object[], (eg student stu[?]; ).在另一堂课中,我必须声明那个对象[],(例如student stu[?]; )。 However, I don't know the size of the object array.但是,我不知道对象数组的大小。 Is it possible to declare an object array but don't know the size?是否可以声明一个对象数组但不知道大小? thank you.谢谢。

As you have probably figured out by now, regular arrays in Java are of fixed size (an array's size cannot be changed), so in order to add items dynamically to an array, you need a resizable array.正如您现在可能已经发现的那样,Java 中的常规数组的大小是固定的(数组的大小不能更改),因此为了向数组动态添加项目,您需要一个可调整大小的数组。 In Java, resizable arrays are implemented as the ArrayList class ( java.util.ArrayList ).在 Java 中,可调整大小的数组实现为 ArrayList 类 ( java.util.ArrayList )。 A simple example of its use:其使用的一个简单示例:

import java.util.ArrayList;

// Adds a student to the student array list.
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student());

The <Student> brackets (a feature called generics in Java) are optional; <Student>括号(Java 中称为泛型的特性)是可选的; however, you should use them.但是,您应该使用它们。 Basically they restrict the type of object that you can store in the array list, so you don't end up storing String objects in an array full of Integer objects.基本上,它们限制了您可以存储在数组列表中的对象类型,因此您最终不会将 String 对象存储在一个充满 Integer 对象的数组中。

User ArrayList instead.用户ArrayList代替。 It'll expand automatically as you add new elements.当您添加新元素时,它会自动扩展。 Later you can convert it to array, if you need.如果需要,稍后您可以将其转换为数组。

As another option (not sure what exactly you want), you can declare Object[] field and not initialize it immediately.作为另一种选择(不确定你到底想要什么),你可以声明Object[]字段而不是立即初始化它。

Its not possible,we need to specify the size of array when declaring object array;不可能,我们需要在声明对象数组时指定数组的大小;

  1. one way to declare object array一种声明对象数组的方法

     student st[]; st=new student[3];
  2. second way第二种方式

     student st[]=new student[5];

in both cases not any objects are created only the space is allocated for the array.在这两种情况下,都不会创建任何对象,只是为数组分配了空间。

st=new student[1];

this will create a new object;这将创建一个新对象;

You could declare as: Student stu[]=null;您可以声明为: Student stu[]=null; , and create it with fixed size: stu[]=new Student[10] until you could know the size. ,并以固定大小创建它: stu[]=new Student[10]直到您知道大小。 If you have to use array.如果必须使用数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM