Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating objects from a file  RSS feed

 
Dariush Rasi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I need to create thousands of objects but there is a limit on the number of lines in a Java class.
Basically I need to be able to read from a file in which, each record includes the variable name, in this case name of cities, and then use the objects to add a relationship between them in an arraylist.
Please note that I don't have a problem defining the cities because there is a limited number of them but the combination of each pair of city becomes a large number for example, 100 by 100 cities becomes 10,000 lines of code to add them to the array which is impossible.

I would appreciate if anyone could help me on this. I have seen some examples that use Class.forName(name) but I don't know how to make it to work for this.

The input file for example contains the following cities:
Paris
London
NewYork


For each item, I like to create an object such as:
Resource Paris = city.createResource("Paris");
Resource London = city.createResource("London");
..

ArrayList myCities = new ArrayList();
l.add(new SimilarCities(Paris, London, 0.5);
l.add(new SimilarCities(Paris, NewYork, 0.2);

Thank you.
Dariush
 
fred rosenberger
lowercase baba
Bartender
Posts: 12541
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you will not be able to dynamically name your variables, but you could use a map to store things. Each time you read in a city name from your file, you create the Resource object, then put it in the map using the name as your key.

Once the map is populated, you can get a list of all the keys (city names), and iterate through it however you see fit to then build your arrayList
 
Dariush Rasi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Fred, your help did certainly help. I realized that the variable names themselves were of no significance.
 
Campbell Ritchie
Marshal
Posts: 55672
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and welcome to the Ranch
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!