搜索字符串数组

时间:2014-08-15 20:27:15

标签: java android arrays

我有这个字符串数组......

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

对于以下所有记录的数据结构是相同的,并且所有记录在开头都具有唯一的数字值(与其索引无关)。我喜欢通过该值快速查找记录,而无需遍历整个事物。这可能吗?

2 个答案:

答案 0 :(得分:8)

您应该将此数据存储在Map<String,String>Map<Integer,String>中(因为您的键是数字字符串)。这将使搜索变得微不足道。

然后使用给定的唯一键搜索值将非常简单:

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

搜索将在预期的O(1)时间内执行。

答案 1 :(得分:4)

您正在寻找HashMap,因为它是unique number value您可以将其用作并使用get method HashMap直接获取值而不迭代它。

<强>样品:

    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.

如果您的值是String数组

    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.
    }
相关问题