1

我收到以下错误:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 86, Size: 86
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at Netbooks.Recommendations.getDotProduct(Recommendations.java:72)
at Netbooks.TestRecomendations.main(TestRecomendations.java:11)
Java Result: 1

我已经多次查看代码,但似乎无法找到遍历数组列表索引的位置......

这是 dotProduct ArrayList 的代码:

public List<Integer> getDotProduct() throws IOException {
    Books book = new Books();
    Ratings cust = new Ratings();
    PureRatings pureRatings = new PureRatings();


    List<String> bookList = book.readBooks();
    List<String> customerList = cust.readCustomers();
    List<List<Integer>> pureRatingsList = pureRatings.parseRatingsFile();
    List<Integer> dotProduct = new ArrayList<Integer>();
    int index = getCustIndex();

    if (index == -1) {
        return dotProduct;
    }

    for (int i = 0; i < customerList.size(); i++) {
        int sum = 0;

        for (int j = 0; j < bookList.size(); i++) {
            if (i == index) {
                dotProduct.add(0);
            } else { //Next line is line 72.
                sum = sum + (pureRatingsList.get(index).get(j)) * (pureRatingsList.get(i).get(j)); //Line 72.
            }
        }
        dotProduct.add(sum);
    }

    return dotProduct;
}

我的主要方法(在​​另一个类中)以防万一:

public class TestRecomendations {

    public static void main(String[] args) throws IOException {
        Recommendations recomm = new Recommendations();

        List<Integer> dotProduct = recomm.getDotProduct();//Line 11.

        for (int i = 0; i < dotProduct.size(); i++) {
            System.out.println(dotProduct.get(i));
        }
    }
}

它应该只打印出 dotProduct ArrayList 的元素...

我不明白第 72 行是如何导致问题的,因为我应该能够向 ArrayList 添加无限数量的项目......任何帮助将不胜感激。

4

4 回答 4

6

第 72 行的问题是 a get(),而不是 a add()

我怀疑这可能是问题的根本原因:

for (int i = 0; i < customerList.size(); i++) {
    int sum = 0;

    for (int j = 0; j < bookList.size(); i++) {  
        if (i == index) {
            dotProduct.add(0);
        } else { //Next line is line 72.
            sum = sum + (pureRatingsList.get(index).get(j)) * (pureRatingsList.get(i).get(j)); //Line 72.
        }
    }
    dotProduct.add(sum);
}

在第二个 for 循环中,您正在递增i而不是j. 这可能会导致您i在行中使用值

sum = sum + (pureRatingsList.get(index).get(j)) 
     * (pureRatingsList.get(i).get(j));

大于 的大小pureRatingsList,导致您看到的异常。

于 2012-02-03T07:54:20.887 回答
2

这条线不是问题吗?

for (int j = 0; j < bookList.size(); i++) {

我想你需要的是

for (int j = 0; j < bookList.size(); j ++) {

于 2012-02-03T08:12:40.150 回答
1

你知道有像迭代器和 foreach 这样的东西可以让遍历集合变得更简单吗?

问题是列表的索引从 0 开始,而您尝试从 1 开始。

于 2012-02-03T07:51:49.083 回答
0

这会导致问题,因为您请求的索引不存在;因此“越界”。

当大小仅为 86(即索引 0 - 85)时,您请求索引 86。数组是从零开始的。

学习使用调试器将真正帮助您解决此类问题,因为您可以单步执行您的程序并查看到底发生了什么。

于 2012-02-03T07:54:06.363 回答