如何在 Java 中声明动态对象数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3887476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare a dynamic object array in Java?
提问by Questions
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.
我想问一个关于Java的问题。我有一个用户定义的对象类,student,它有 2 个数据成员,name 和 id。在另一个类中,我必须声明该对象[],(例如student stu[?];
)。但是,我不知道对象数组的大小。是否可以声明一个对象数组但不知道大小?谢谢你。
采纳答案by Nikita Rybak
User ArrayList
instead. It'll expand automatically as you add new elements. Later you can convert it to array, if you need.
用户ArrayList
代替。当您添加新元素时,它会自动扩展。如果需要,稍后您可以将其转换为数组。
As another option (not sure what exactly you want), you can declare Object[]
field and not initialize it immediately.
作为另一种选择(不确定您到底想要什么),您可以声明Object[]
字段而不是立即初始化它。
回答by agentbanks217
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:
正如您现在可能已经发现的那样,Java 中的常规数组的大小是固定的(数组的大小不能更改),因此为了向数组动态添加项目,您需要一个可调整大小的数组。在 Java 中,可调整大小的数组实现为 ArrayList 类 ( java.util.ArrayList
)。其使用的一个简单示例:
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; 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.
该<Student>
支架(功能称为Java泛型)是可选的; 但是,您应该使用它们。基本上,它们限制了您可以存储在数组列表中的对象类型,因此您最终不会将 String 对象存储在一个充满 Integer 对象的数组中。
回答by u290629
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.
您可以声明为:Student stu[]=null;
,并以固定大小创建它:stu[]=new Student[10]
直到您知道大小。如果必须使用数组。
回答by Lijo Joseph
Its not possible,we need to specify the size of array when declaring object array;
不可能,我们需要在声明对象数组时指定数组的大小;
one way to declare object array
student st[]; st=new student[]3;
second way
student st[]=new student[5];
一种声明对象数组的方法
student st[]; st=new student[]3;
第二种方式
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;
这将创建一个新对象;