views:

652

answers:

1

Currently I'm implementing a Persistant Storage Object for my Blackberry Application.
It contains a Vector of Setting Objects.

My current implemention to get specific settings value looks like this

public String getSettingByName(String key)
{
 String value = "";
    for ( Enumeration e = _appSettings.elements(); e.hasMoreElements();)
    {
     if(((AppSettingsObject)e.nextElement()).get_key() == key)
     {
      value = ((AppSettingsObject)e.nextElement()).get_value();
     }
    }
 return value;
}

Is there a better way to access that value than looping the enumeration?

Thanks!

+1  A: 

A Vector is basically just a growable array, so you have to search through it to find any specific element. You could make sure that the vector is sorted, which would allow you to perform a binary search. I doubt it would make much difference here, since it seems unlikely that you'll have enough elements in your vector to justify the slight increase in performance over the complexity of the code.

It seems like you want to be able to map keys to values, however. In that case, the java.util.Hashtable class might be better:

Hashtable appSettings = new Hashtable();

appSettings.put("key1", "value1");
appSettings.put("key2", "value2");

String value1 = (String)appSettings.get("key1");
String value2 = (String)appSettings.get("key2");
IRBMe
Great thing, what's your option on the overhead / management overhead comparison?
Henrik P. Hessel
I meant opinion =)
Henrik P. Hessel
Overhead in what way? In terms of running cost, a Hashtable is more efficient than a Vector for finding keys. You can look up a key in O(1), constant, time using a Hashtable where it would take O(n), linear, with a Vector, or O(logn), logarithmic, if it were sorted and you did a binary search. Running time won't matter for the small number of elements you're likely to store in it. In terms of space, you probably don't need to worry about it. In terms of ease of use, that's the main reason you'd choose a Hashtable here. it's far easier to use for mapping keys to values, as you can see.
IRBMe