如何在Java中声明动态对象数组?
我想问一个关于Java的问题。我有一个用户定义的对象类,student,它有 2 个数据成员:name 和 id。在另一个类中,我必须声明该 object[](例如 student Stu[?];
)。但是,我不知道对象数组的大小。是否可以声明一个对象数组但不知道大小?谢谢。
I want to ask a question about Java. I have a user-defined object class, student, which have 2 data members, name and id. And in another class, I have to declare that object[], (e.g. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您现在可能已经了解到,Java 中的常规数组具有固定大小(数组的大小无法更改),因此为了将项目动态添加到数组中,您需要一个可调整大小的数组。在 Java 中,可调整大小的数组是作为 ArrayList 类 (
java.util.ArrayList
) 实现的。一个简单的使用示例:
括号(Java 中称为泛型的功能)是可选的;但是,您应该使用它们。基本上,它们限制了可以存储在数组列表中的对象类型,因此您最终不会将 String 对象存储在充满 Integer 对象的数组中。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. In Java, resizable arrays are implemented as the ArrayList class (
java.util.ArrayList
).A simple example of its use:
The
<Student>
brackets (a feature called generics in Java) are optional; 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.请改用
ArrayList
。当您添加新元素时,它会自动扩展。如果需要的话,稍后您可以将其转换为数组。作为另一种选择(不确定您到底想要什么),您可以声明
Object[]
字段而不立即初始化它。User
ArrayList
instead. 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.这是不可能的,我们需要在声明对象数组时指定数组的大小;
声明对象数组的一种方法
第二种方法
在这两种情况下都不会创建任何对象,只为数组分配空间。
这将创建一个新对象;
Its not possible,we need to specify the size of array when declaring object array;
one way to declare object array
second way
in both cases not any objects are created only the space is allocated for the array.
this will create a new object;
您可以声明为:
Student Stu[]=null;
,并使用固定大小创建它:stu[]=new Student[10]
,直到您知道大小为止。如果一定要用数组的话。You could declare as:
Student stu[]=null;
, and create it with fixed size:stu[]=new Student[10]
until you could know the size. If you have to use array.