jcaruso
jcaruso

Reputation: 2494

Searching String Array

I have this string array....

public static final String[][] cardNames = {
        {"10","Blah"},
        ...
}

The data structure is the same for all records below that and all have a unique number value at the beginning (not related to their index). Id like to quickly find a record by that value without having to loop through the entire thing. Is that possible?

Upvotes: 0

Views: 65

Answers (2)

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

You are looking for HashMap, since it is a unique number value you can use that as a key and use the get method of the HashMap to directly get the value without iterating on it.

sample:

    Map<String,String> s = new HashMap<String,String>();
    s.put("10","Blah"); //to put the data

    if(s.get("10") != null)
      s.get("10"); //to get the data without iterating.

If your value is a String array

    Map<String,String[]> s = new HashMap<String,String[]>();
    s.put("10",new String[]{"Blah","Blah2"}); //to put the String data array


    if(s.get("10") != null)
    {
        String s1 = s.get("10")[0]; //to get the data in index 0 without iterating.
        String s2 = s.get("10")[1]; //to get the data in index 1 without iterating.
    }

Upvotes: 4

Eran
Eran

Reputation: 393841

You should store this data in a Map<String,String> or Map<Integer,String> (since your keys are numerical Strings). That would make searching trivial.

Then searching for a value with a given unique key would be as simple as :

if (map.containsKey("504")) {
    String value = map.get("504");
}

And the search would be performed in expected O(1) time.

Upvotes: 8

Related Questions