views:

226

answers:

1

I am a newbe to J2ME. I have a vector called locations which prints out

[{X=NM0001-1, ccc=1327_10}, 
{X=NM0001-2, ccc=1329_10}, 
{X=NM0001-3, ccc=691_10}] 

when I put System.out.println(locations); I set "X", and "ccc" are the keys. In my program I wanted to query for certain value of "ccc" what is the "X" value. Any help would be much appreciated.

A: 

Do you need to structure your data like that?

There are several things to consider:

  • For each value of ccc is there only one associated value X?
  • Is the order of items in the Vector important here?
  • Is the content of the data structure static, i.e. are you adding data to the structure during program execution, or is it write-once at start up?
  • Are you removing data from the structure.

If associated values are unique, you could hold the data in a single Hashtable with the ccc values as keys, then retrieval of a value for a specific key is trivial. If the order of keys is important you could maintain a separate Vector of keys.

Otherwise you would have to iterate over the Vector, retrieve the value from each Hashtable for the ccc key, if that matches your search value, retrieve the value for the X key as your result. Something like this:

for ( int i = 0; i < locations.size( ); i++ ) {
    Hashtable ht = (Hashtable) locations.elementAt( i );
    if ( key.equals( ht.get( "ccc" ) ) ) {
        System.out.println( "Value for key " + key + "=" + ht.get( "X" ) );
    }
}
martin clayton
1. ccc is unique but X is not.2. Order does nto matter.3. data is static; idea is to load it once when the program starts from a text file (which is working so far).4. No.I will try this. What I am having issue is how to search for "NM0001-2" when you I have the variable "1329_10". Sorry for my ignorance; to test your example do I need to define "key" as Enumerator? Can I do the search out side the loop of loading the hashtable? Thanks for your time.
Imran kader
Thanks it worked.
Imran kader