在此,我将单词存储在一个数组列表中,并将与其对应的相应电话号码存储在另一个数组列表中。我希望能够输入一个数字并返回其他列表中对应的所有单词。我的数组列表设置如下。
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());
}
最佳答案
在您的情况下,我宁愿使用以下数据结构将电话号码映射到单词列表
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);
}
关于java - 当 ArrayList 中多个对象相同时,如何找到它们的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15606374/