• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using an ArrayList to store many different kinds of objects.  RSS feed

 
Daniel Gallant
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's the requirments:

I need to store, save and reload program settings, specifcly:

1. String (default save directory)
2. String[] (some user defined options in a drop down box)
3. Font[][] (a list of the various fonts used in different printed forms)

I also want to make this a flexible solution, allowing me to add different types of items to be saved as user requirements demand it.

My current solution:

I use and ArrayList "" and add each item to be saved to it, for example:


My current problem:

When trying to read to read the datafile, what do I cast it to? When i use this:

I get the following error:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.util.ArrayList


Can anyone suggest a way to fix this or a better way to handle these options?

Thanks!!
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think using a single list for different kinds of objects is generally poor programming, if you have to cast the objects afterwards. Avoid casting objects.
Use separate lists for different kinds of objects, or if your settings can be represented as strings, use the Properties class.
 
Paul Clapham
Sheriff
Posts: 22844
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, frankly, I would use a Map to store the data. That way each of the data items you store would have a name, rather than just an index in an array. Less confusing to work with in the long run.

But as for your actual problem here, the message says that you just read an array of objects from the file, and therefore you can't cast that to an ArrayList. This means that you must have written an array of objects to the file, not an ArrayList. You didn't post the code which allegedly writes the ArrayList to the file, but that's my best guess.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!