0

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?

1
  • Seems like you'd benefit from using a Map Commented Aug 15, 2014 at 20:29

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.
    }

2 Comments

you can do Map<String,String> map = new HashMap<>() since Java 7 :)
@Reimeus :)) yes indeed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.