在这里,我将单词存储在一个arraylist中,并将相应的电话号码存储在另一个arraylist中。我希望能够输入一个数字并返回其他列表中对应的所有单词。我让我的arraylists设置得像这样。
List<String> listWords = new ArrayList<String>(); // An ArrayList which stores all added words.
List<String> listNum = new ArrayList<String>();// An ArrayList which stores all phone numbers that correspond to all the added words
单词按照在电话键盘上的转换(即2 = a,b,c 3 = d,e,f等)。
此外,我正在添加这样的词语;
public void readWords()
{
PhoneWords ph = new PhoneWords();
try
{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
String phNum = ph.word2Num(strLine);
listWords.add(position, strLine);
listNum.add(position, phNum);
position++; // index position, only used when initally adding the words
}
}catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
答案 0 :(得分:1)
在您的情况下,我宁愿使用以下数据结构将电话号码映射到单词列表
HashMap<String, List<String>> phoneNumbersMap = new HashMap<String, List<String>>();
HashMap的参考在这里http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
如果您的名单将来增长,它还可以更快地检索单词!
要将数据添加到HashMap,您可以执行以下操作:
if (map.containsKey(phNum)) {
List<String> words = map.get(phNum);
words.add(strLine);
} else {
List<String> words = new ArrayList<String>();
words.add(strLine);
map.put(phNum, words);
}