当index真正在边界内时IndexOutOfBounds异常

时间:2012-11-11 21:34:42

标签: java arraylist indexoutofboundsexception

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 175, Size: 175
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.remove(Unknown Source)
    at GetData.main(GetData.java:42)

这是我列在l列表中的例外情况,但当我致电l.size()时,它会返回188!

这是一个SSCCE(好吧,尽可能简洁):

import java.io.*;
import java.util.*;
import java.util.regex.*;


public class GetData {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws Exception {
        //optimize();
        BufferedReader r = new BufferedReader(new FileReader(new File("countrydata - optimized.txt")));
        String str = "";
        String line = null;
        int x = 0;
        while ((line = r.readLine()) != null) {
            str += line;
            x ++;
            if (x % 20 == 0) System.out.println("Reading file... // " + x / 20 + " of 18");
        }
        Pattern p = Pattern.compile("<strong>(.*?)</strong><br/>(.*?)<");
        Matcher m = p.matcher(str);
        //PrintWriter w = new PrintWriter(new BufferedWriter(new FileWriter(new File("countrydata - verbose.xml"))));
        //w.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        ArrayList<HashMap<String, String>> l = new ArrayList<>(188); //This is one ugly line of code right here
        HashMap<String, String> a = null;
        String[] countries = "Afghanistan/Albania/Andorra/Angola/Antigua and Barbuda/Antigua and Barbuda 2/Argentina/Argentina 2/Australia/Astria/Azerbaijan/Bahamas/Bahrain/Bangladesh/Barbados/Barbados 2/Belgium/Belize/Benin/Bhutan/Bolivia/Bosnia and Herzegovina/Botswana/Brazil/Brunei/Bulgaria/Burkina Faso/Burundi/Cambodia/Cameroon/Canada/Cape Verde/Central African Republic/Chad/Chile/China/Colombia/Comoro Islands/Congo/Costa Rica/Cote d'Ivoire/Croatia/Cuba/Cyprus/Czech Republic/Denmark/Djibouti/Dominica/Dominican Republic/Dominican Republic 2/Ecuador/El Salvador/El Salvador 2/Eritrea/Estonia/Ethiopia/Fiji/Finland/French/Gabon/Gambia/Georgia/Germany/Ghana/Greece/Greece 2/Grenada/Guatemala/Guinea/Guinia-Bissau/Guyana/Haiti/Honduras/Hungary/Iceland/India/Indonesia/Iran/Iraq/Ireland/Israel/Italy/Jamaica/Jamaica 2/Jordan/Kazahkstan/Kenya/Kiribati/Kuwait/Kyrgyzstan/Laos/Latvia/Lebanon/Lebanon 2/Lesotho/Libya/Liechtenstein/Lithuania/Luxembourg/Macedonia/Madagascar/Malawi/Malaysia/Maldives/Mali/Mali 2/Malta/Mauritania/Mexico/Moldova/Monaco/Mongolia/Morocco/Mozambique/Myanmar/Namibia/Nepal/New Zealand/Nicaragua/Niger/North Korea/Norway/Oman/Oman 2/Panama/Papua New Guinea/Prarguay/Peru/Phillippines/Poland/Portugal/Qatar/Romania/Russia/Russia 2/St. Kitts and Nevis/St. Lucia/St. Vincent and the Grenedines/San Marino/Sao Tome and Principe/Saudi Arabia/Senegal/Seychelles/Sierra Leone/Singapore/Slovakia/Slovenia/Soloman Islands/Somalia/South Africa/South Korea/Spain/Spain 2/Sudan/Suriname/Swaziland/Sweden/Switzerland/Switzerland 2/Tawian/Tajikistan/Tanzania/Thailand/Togo/Tonga/Trinidad & Tobago/Tunisia/Turkey/Turkmenistan/Tuvalu/Uganda/Ukraine/United Arab Emirates/United Kingdom/United States/United States 2/Marshall Islands/Micronesia/Uruguay/Uzbekistan/Vanuatu/Vietnam/Samoa/Yemen/Zimbabwe/East Timor/???/Serbia".split("/");
        int ci = 0;
        while (true) {
            if (m.find()) {
                //System.out.println((m.group(1).equals("Internet Users") ? "NEW COUNTRY\nInternet Users" : m.group(1)) + "|" + m.group(2));
                if (m.group(1).equals("Internet Users")) {
                    if (a != null) l.add(a);
                    if (ci == 188) break;
                    a = new HashMap<String, String>();
                    a.put("Country Name", countries[ci++]);
                    a.put("Internet Users", m.group(2));
                } else {
                    a.put(m.group(1), m.group(2));
                }
            } else break;
        }
        for (int i = 0; i < countries.length; i ++) {
            if (countries[i].matches(".*2")) l.remove(i);
        }
        String[] data = "".split("\\.");
        for (Object map : l.toArray()) {
            a = (HashMap<String, String>) (map);
            System.out.println(a.get("School System"));
            System.out.println(a.get("Country Name"));
        }
        r.close();
    }

文件countrydata - optimized只是<strong>(name of data)</strong><br/>(the data)<div id="...形式的一堆数据行,但这可能对此问题并不重要。

为什么l.size()在异常显示大小为175时返回188?

2 个答案:

答案 0 :(得分:5)

ArrayList<HashMap<String, String>> l = new ArrayList<>(188);

188initial capacity of the list,而不是它的大小。

您无法确定i是否超出以下列表的大小:

for (int i = 0; i < countries.length; i ++) {
    if (countries[i].matches(".*2")) l.remove(i);
}

答案 1 :(得分:1)

如果(countries[i].matches(".*2"))为真,则从l中删除元素,因此其大小会减小。 l的大小现在小于countries的大小,因此您无法将countries的索引映射到l并希望获得相应的对象。< / p>