Java 搜索字符串数组

Java 搜索字符串数组,java,android,arrays,Java,Android,Arrays,我有这个字符串数组 public static final String[][] cardNames = { {"10","Blah"}, ... } 以下所有记录的数据结构都是相同的,并且所有记录的开头都有一个唯一的数值(与其索引无关)。我想通过该值快速找到一条记录,而不必循环整个过程。这可能吗?您应该将此数据存储在映射或映射(因为您的键是数字字符串)。这将使搜索变得微不足道 然后,使用给定的唯一键搜索值将非常简单: if (map.containsKey("

我有这个字符串数组

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

以下所有记录的数据结构都是相同的,并且所有记录的开头都有一个唯一的数值(与其索引无关)。我想通过该值快速找到一条记录,而不必循环整个过程。这可能吗?

您应该将此数据存储在
映射
映射
(因为您的键是数字字符串)。这将使搜索变得微不足道

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

if (map.containsKey("504")) {
    String value = map.get("504");
}
搜索将在预期的
O(1)
时间内执行。

您正在查找,因为它是一个
唯一的数值
,您可以将其用作,并使用
HashMap
get方法直接获取值,而无需对其进行迭代

示例:

    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.
Map s=newhashmap();
s、 放入(“10”,“诸如此类”)//把数据
如果(s.get(“10”)!=null)
s、 获得(“10”)//无需迭代即可获取数据。
如果您的值是字符串数组

    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.
    }
Map s=newhashmap();
s、 put(“10”,新字符串[]{“Blah”,“Blah2”})//要放置字符串数据数组
如果(s.get(“10”)!=null)
{
字符串s1=s.get(“10”)[0];//在不迭代的情况下获取索引0中的数据。
字符串s2=s.get(“10”)[1];//在不迭代的情况下获取索引1中的数据。
}

使用
Map似乎会让您受益
您可以做
Map=new HashMap()
因为Java 7:)@Reimeus:)是的。