【问题标题】:How do I find the index of multiple objects in an ArrayList when they are identitcal当它们相同时,如何在 ArrayList 中找到多个对象的索引
【发布时间】:2013-03-25 01:38:19
【问题描述】:

在此,我将单词存储在一个数组列表中,并将与其对应的相应电话号码存储在另一个数组列表中。我希望能够输入一个数字并返回另一个列表中对应的所有单词。我的数组列表设置是这样的。

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());
    }

【问题讨论】:

  • 请不要对文本使用 DataInputStream。

标签: java arraylist indexof


【解决方案1】:

在您的情况下,我宁愿使用以下将电话号码映射到单词列表的数据结构

HashMap&lt;String, List&lt;String&gt;&gt; phoneNumbersMap = new HashMap&lt;String, List&lt;String&gt;&gt;();

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);
}

【讨论】:

    猜你喜欢
    • 2017-05-06
    • 1970-01-01
    • 2016-08-05
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 2019-08-13
    • 1970-01-01
    相关资源
    最近更新 更多