java - 当 ArrayList 中多个对象相同时,如何找到它们的索引

标签 java arraylist indexof

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

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/

相关文章:

java - 由于值被清除,无法从使用数组列表的 HashMap 中获取值

java - 将新对象添加到数组列表

c# - 在两个已知字符串之间提取未知字符串

javascript - 返回模板表中行和列的索引

java - spring boot Jar to war【同学-1.3.3.jar(系统找不到指定路径)】

Java 9 替换 Class.newInstance

java - NullPointerException - 从数据库中检索数据并将数据存储到数组时出现数据库锁定问题

java - 如何修复 Eclipse 中的 Maven、Maven 配置和 Maven 依赖性问题

java - 高效的Java列表合并算法

java - 动态引用不同的 JLabel