permaculture playing cards*
The moose likes Beginning Java and the fly likes Creating an array using ArrayList() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Creating an array using ArrayList()" Watch "Creating an array using ArrayList()" New topic
Author

Creating an array using ArrayList()

Shweta Pershad
Greenhorn

Joined: Sep 08, 2004
Posts: 23
Hi,

I need to store the names and values of attributes from an XML document. I feel an ArrayList will be right for it. But will Arraylist store both names and values? I need to retrive names and values from it later on.
Or will a hashtable be better for it? Or maybe just a two dimensional array?

Shweta
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
It would seem to me by putting it into an ArrayList or Map or some other collection that you will lose some of the scope information. You won't be able to distinguish which element belongs to which other element. If you are using XML you probably want to look at an XML parser. Or if the data is not complex enough for that a simple properties file might be a better choice.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
It depends on how you need to use those names and values. If as Steven suggests you need to relate those back to the Elements that created them, you'll want to use a more detailed structure.

However, if all you need are the names and values extracted from the XML file, an ArrayList or HashMap would suffice, but again it depends on the nature of how they'll be used.

Do you want to be able to find the values for a given name? In other words, do you need to perform a lookup from name to values? This is precisely what the various Map subclasses give you. While you can still iterate over the names or values individually, the key concept is looking up values using keys, the names in this case.

If instead you just want a list of name/value pairs, you can create a simple class that holds a single name/value pair and store those classes inside an ArrayList. This is obviously a little more work than using a HashMap, and it gives you less functionality (no lookup). However, if you need to pass name/value pairs to other parts of your program, this extra class could provide benefit.

Without knowing more, I'd say that HashMap is probably what you want in this case. Also, don't use Hashtable as it's been replaced by HashMap (as ArrayList has replaced Vector).
 
jQuery in Action, 2nd edition
 
subject: Creating an array using ArrayList()