如果是 Java,您始终可以设置一个哈希表,将姓氏与矩阵行索引数组相关联,这样这些行上的人就拥有该姓氏。
或者你可以有一个多级哈希表,这样你就可以做到m[index.get(lastName).get(firstName)]。
此外,如果您想按字典顺序遍历名称,可以将哈希表替换为 TreeMap。
例子:
import java.util.*;
class Test{
public static void main(String[]args){
Object[][] m = new Object[][]{
{1, "Smith", "John"},
{2, "Stone", "Jack"},
{3, "Stein", "Robert"},
{4, "Stone", "Bob"}
};
//index.get(lastName) will return a map between
//first names and matrix row indices.
//index.get(lastName).get(firstName) returns the index
//in the matrix of the row pertaining to person (lastName, firstName)
TreeMap<String, TreeMap<String, Integer>> index =
new TreeMap<String, TreeMap<String, Integer>>();
//create index
for(int i=0;i<m.length;i++){
Object[]o = m[i];
String last = o[1].toString();
String first = o[2].toString();
TreeMap<String,Integer> index2 = index.get(last);
if (index2==null){
index2=new TreeMap<String,Integer>();
index.put(last, index2);
}
index2.put(first, i);
}
System.out.print("Smith, John -> ");
System.out.println(Arrays.toString(m[index.get("Smith").get("John")]));
System.out.print("Stone -> ");
System.out.println(index.get("Stone"));
System.out.print("Full index: ");
System.out.println(index);
}
}
输出:
Smith, John -> [1, Smith, John]
Stone -> {Bob=3, Jack=1}
Full index: {Smith={John=0}, Stein={Robert=2}, Stone={Bob=3, Jack=1}}
在我给出的示例中,将姓氏映射到行索引是不够的,因为您可能有两个姓氏相同的人。但是,我确实假设您不会有两个同名的人。否则,您将需要TreeMap<String, TreeMap<String, ArrayList<Integer>>> 之类的东西,以便能够找到具有给定(姓氏、名字)的每个人。
如果要按 ID 搜索,只需创建第二个索引,将 ID 映射到行索引,可以是 HashMap<Integer, Integer>。
对于这个小例子,拥有索引并没有什么好处,因为它们可能比矩阵本身占用更多的空间,但如果你的记录很大,它可能会得到回报。