Java类变量个数
我正在学习java,现在我有这个问题。
我创建了一个名为“Driver”的类,它将保存驾驶员的信息(姓名和生日)。
要创建一个新的驱动程序,我只需要执行以下操作:
Driver d1 = new Driver("John", "01/01/1980");
现在假设我有一个程序可以从文件中读取 x 驱动程序信息。如何创建 x 驱动程序?
我的问题是我认为我需要 x 驱动程序的 x 变量,但变量只能由我硬编码......
I'm learning java and now I have this question.
I created a class named "Driver" and it will hold a driver's information (name and birthday).
To create a new driver I just need to do:
Driver d1 = new Driver("John", "01/01/1980");
Now imagine I have a program that will read x drivers information from a file. How can I create x drivers?
My problem is that i'm thinking I need x variables for x drivers but variables can only be hard-coded by me...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
或者您可以使用数组或集合(
List
或Set
):从文件读取时,通常使用循环。因此,在每次迭代时将对象添加到列表中。
Or you can use an array or collection (
List
orSet
):When reading from a file you usually use a loop. So on each iteration add the object to the list.
本质上,您需要的是逐一读取每个驱动程序,并将它们存储在集合中。 Java 中有多个集合类,但 ArrayList 应该适合您的情况:
What you need, essentially, is to read each driver one by one, and store them in a collection. There are multiple collection classes in Java, but
ArrayList
should do just fine in your case:您将创建一个
List
(或其他一些集合,例如Map
)来存储所有驱动程序。you would create a
List<Driver>
(or some other collection, e.g.Map
) in which to store all the Drivers.使用简单数组:
但是数组一旦创建就有固定的大小。因此,您可以使用 ArrayList 代替:
Use simple array:
But array has fixed size once you create it. So, you can use
ArrayList
instead: