OutOfBoundsException麻烦,Java

Mar*_*cos 1 java arraylist indexoutofboundsexception

我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

我看了很多遍的代码,我似乎无法找到我在arraylist索引的位置...

这是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;
}
Run Code Online (Sandbox Code Playgroud)

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

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

raz*_*ebe 6

第72行的问题是a get(),而不是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);
}
Run Code Online (Sandbox Code Playgroud)

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

sum = sum + (pureRatingsList.get(index).get(j)) 
     * (pureRatingsList.get(i).get(j));
Run Code Online (Sandbox Code Playgroud)

大于,大小pureRatingsList,导致您看到的例外.