Reputation: 1331
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...
Upvotes: 0
Views: 110
Reputation: 117627
Use simple array:
Driver[] drivers = {new Driver("John", "01/01/1980"),
new Driver("Smith", "02/02/1990")};
// or
Driver[] drivers = new Driver[2];
drivers[0] = new Driver("John", "01/01/1980");
drivers[1] = new Driver("Smith", "02/02/1990");
But array has fixed size once you create it. So, you can use ArrayList
instead:
List<Driver> drivers = new ArrayList<Driver>();
drivers.add(new Driver("John", "01/01/1980"));
drivers.add(new Driver("Smith", "02/02/1990"));
// ...
Upvotes: 0
Reputation: 53694
you would create a List<Driver>
(or some other collection, e.g. Map
) in which to store all the Drivers.
Upvotes: 0
Reputation: 36984
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:
ArrayList<Driver> drivers = new ArrayList<Driver>();
Driver d1 = new Driver("John", "01/01/1980");
drivers.add(d1);
Upvotes: 2
Reputation: 597234
Or you can use an array or collection (List
or Set
):
List<Driver> drivers = new ArrayList<Driver>();
drivers.add(new Driver(..));
drivers.add(new Driver(..));
When reading from a file you usually use a loop. So on each iteration add the object to the list.
Upvotes: 2