【问题标题】:Accessing a string before and after another string in an arrayList在arrayList中访问另一个字符串之前和之后的字符串
【发布时间】:2013-01-07 23:17:38
【问题描述】:

如果我在我的 arrayList 中搜索第 5 项,我还想获得第 4 项和第 6 项。最终的 if 语句中提供了此代码,并定义为 (i - 1) 和 (i + 1)。到目前为止,这是我的代码:

import java.util.ArrayList;

public class PlanetsList {
public static void main(String args[]) {

    ArrayList<String> planets = new ArrayList<String>();
    String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranis", "Neptune", "Pluto"};

    for (int i = 0, n = names.length; i < n; i++) {
        planets.add(names[i]);
        String value = (String) planets.get(i);

        if(value.contains("Mars")) {
            String newNum = value.replace(value, "Red planet ");
            planets.set(i,newNum);     
        }
        if(value.contains("Uranis")) {
            String wordBefore = (String) planets.get(i-1);
            String wordAfter = (String) planets.get(i+1);
            String newNum = value.replace(value, "Uranus ");
            planets.set(i,newNum);
            System.out.println("This is the word before " + wordBefore);
            System.out.println("This is the word after " + wordAfter);
            planets.remove(i-1);  
        }
    }
    System.out.println(planets);
}
}

这样我得到了一个 indexoutofbounds 异常,这显然是由最终 if 语句中的 wordAfter 行引起的,并且因为 for 循环没有遍历整个 arrayList。最后的 if 语句不需要和另一个 if 语句在同一个 for 循环中,但如果它在不同的循环中,replace 方法必须能够将被替换的单词放回正确的位置。

问候

【问题讨论】:

  • 使用泛型类型来避免强制转换:ArrayList&lt;String&gt; planets = new ArrayList&lt;&gt;();,另外,为什么在检查相等性时在字符串上使用contains()?这就是equals() 的用途;)另外,我不认为你的问题是不言自明的。你真正想做什么?
  • 这只是我的程序的一部分,而不是实际的东西。需要 contains 方法用于其他目的。将调整为通用类型并查看我的问题。

标签: java for-loop arraylist indexoutofboundsexception


【解决方案1】:

完成将字符串添加到您的列表中,然后根据您的逻辑再次尝试迭代列表。当i 是添加到您列表中的最大值时,您正在尝试get(i+1)

【讨论】:

  • 嗨,很抱歉再次提出这个问题。我通过在最后的 if 语句中添加一个 remove 方法对问题进行了调整。这一直有效,直到我的问题得到解决。关于它为什么停止工作的任何想法,因为它以前工作过?
  • remove 如果您在第一个循环中添加项目后使用第二个循环来迭代您的列表,也应该可以工作。
【解决方案2】:

planets.add(names[i]);...在这一行中,只有你向arraylist添加一个值。此时,你的arraylist的大小是i。不增加i或向arraylist添加任何值,您正在尝试访问 i+1 处的元素..所以它肯定会抛出 IOB 异常

【讨论】:

    【解决方案3】:

    我想这会解决你的问题

    您的代码出现异常

    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 7, Size: 7
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at PlanetsList.main(PlanetsList.java:20)
    

    这是一个有效的方法:

    import java.util.ArrayList;
    
    public class PlanetsList {
    public static void main(String args[]) {
    
    ArrayList planets = new ArrayList();
    String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranis", "Neptune", "Pluto"};
    
    for (int i = 0, n = names.length; i < n; i++) {
    planets.add(names[i]);
    }
    for (int i = 0, n = names.length; i < n; i++) {
    String value = (String) planets.get(i);
    
    if(value.contains("Mars")) {
    String newNum = value.replace(value, "Red planet");
    planets.set(i,newNum);     
    }
     if(value.contains("Uranis")) {
    String wordBefore = (String) planets.get(i-1);
    String wordAfter = (String) planets.get(i+1);
    String newNum = value.replace(value, "Uranus");
    planets.set(i,newNum);
    System.out.println("This is the word before " + wordBefore);
    System.out.println("This is the word after " + wordAfter);   
     }
    }
    System.out.println(planets);
    }
    }
    

    我对你的代码做了两处改动:

    1. 采用两个 for 循环
    2. 从以下两行中删除spaces

      String newNum = value.replace(value, "Red planet ");
      String newNum = value.replace(value, "Uranus ");
      

    【讨论】:

    • 谢谢,只需 planets.addAll(Arrays.asList(names));
    • 嗨,很抱歉再次提出这个问题。如果我想通过在最后的 if 语句中添加 planets.remove(i-1);planets.remove(i+1); 来删除项目,我将如何让它工作。也得到了 indexoutofbounds,这只是在我更改了问题中的代码后才出现。
    • @Digitalwolf 只需在关闭您的最后一个 if 声明之前添加 break;,我已经在我的机器上尝过,它正在工作
    • 只需要再做一次调整,但是中断确实解决了错误 =D 谢谢
    【解决方案4】:

    此行导致问题。

     String wordAfter = (String) planets.get(i+1);
    

    因为最大索引是i。

    如果你做如下检查会更好。

    public static void main(String args[]) {
    
        ArrayList planets = new ArrayList();
        String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranis", "Neptune", "Pluto"};
    
        for (int i = 0, n = names.length; i < n; i++) {
            planets.add(names[i]);
    
        }
        for (int i = 0, n = names.length; i < n; i++) {
    
            String value = (String) planets.get(i);
    
            if(value.contains("Mars")) {
                String newNum = value.replace(value, "Red planet ");
                planets.set(i,newNum);     
            }
            if(value.contains("Uranis")) {
                String wordBefore = (String) planets.get(i-1);
                String wordAfter = (String) planets.get(i+1);
                String newNum = value.replace(value, "Uranus ");
                planets.set(i,newNum);
                System.out.println("This is the word before " + wordBefore);
                System.out.println("This is the word after " + wordAfter);   
            }
        }
        System.out.println(planets);
    }
    

    【讨论】:

      【解决方案5】:

      您可以使用 Arrays.asList 将数组转换为列表,然后遍历列表进行处理。无论如何,您都应该检查 wordBefore 和 wordAfter 的索引是否在列表限制内。

      【讨论】:

        【解决方案6】:

        我也觉得这个问题不是不言自明的......但是如果您需要获取数组列表中特定项目之前和之后的元素,您可以这样做。

        我的假设是您已经有一个预先填充了值的列表。

        String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranis", "Neptune", "Pluto"};
        
        List<String> planets = java.util.ArrayList.asList(names);
        
        if (planets.contains("Uranis") ) {
           int currentIndex = planets.indexOf("Uranis");       
           String previousItem = planets.get(currentIndex-1);
           // To ensure that we have an element next to the current one. 
           if (currentIndex < (planets.size() - 1 )) {
            String nextItem = planets.get(currentIndex+1); 
           }
        }
        

        希望对你有帮助

        ~拉格什

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多