[英]How do I find the index of multiple objects in an ArrayList when they are identitcal
In this I am storing words in one arraylist and the respective phone-number that corresponds to it in another arraylist. 在此,我将单词存储在一个数组列表中,并将与之对应的相应电话号码存储在另一数组列表中。 I want to be able to enter a number and return all words in the other list that correspond.
我希望能够输入一个数字并返回其他对应列表中的所有单词。 I have my arraylists setup like this.
我有这样的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
The words are converted as they would on a phone keypad (ie 2 = a,b,c 3 = d,e,f etc). 单词将像在电话键盘上一样进行转换(即2 = a,b,c 3 = d,e,f等)。
Also I am adding the words simply like this; 我还要添加这样的词:
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());
}
In your case I would rather use the following data structure that maps a phone number to a list of words 在您的情况下,我宁愿使用以下将电话号码映射到单词列表的数据结构
HashMap<String, List<String>> phoneNumbersMap = new HashMap<String, List<String>>();
Reference for HashMap is here http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html HashMap的参考位于http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
It will also make retrieving the words much faster if your list grows in the future! 如果您的列表将来会增加,它也将使检索单词的速度更快!
To add data to the HashMap you can do: 要将数据添加到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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.