动态arraylist的问题

时间:2014-12-13 16:46:20

标签: android dynamic arraylist

在我的项目中,我使用了动态数组,但输出结果有误: 我的代码:

for (int i = 0; i < save; i++) {
    a[i] = (double) db.get_a("loc", i);
    b[i] = (double) db.get_b("loc", i);
    for (int j = 0; j < 6; j++) {
        numbers.add(a[i] + b[i]);
    }
    Log.i("LOG", "Array Index #" + i + " = " + numbers.get(i));
}
Log.i("LOG", "Array size #" + numbers.size());

在我的logcat中:

11-23 15:35:07.443: I/LOG(1880): Array Index #0 = 7.0
11-23 15:35:07.473: I/LOG(1880): Array Index #1 = 7.0
11-23 15:35:07.535: I/LOG(1880): Array Index #2 = 7.0
11-23 15:35:07.583: I/LOG(1880): Array Index #3 = 7.0
11-23 15:35:07.693: I/LOG(1880): Array Index #4 = 7.0
11-23 15:35:07.763: I/LOG(1880): Array Index #5 = 7.0
11-23 15:35:07.774: I/LOG(1880): Array size #36

1 个答案:

答案 0 :(得分:0)

您尝试做的事情似乎不是您想要的。

您提供的代码如下

save似乎是6。在(isave)的第一次迭代中,您得到a和b

然后在(j6)迭代中,您在numbers

中插入6次结果

代码可以重写为

for (int i = 0; i < save; i++) {
    a[i] = (double) db.get_a("loc", i);
    b[i] = (double) db.get_b("loc", i);
    double sum = a[i] + b[i];
    for (int j = 0; j < 6; j++) {
        numbers.add(sum); // Inserting the same value 6 times
        int cal_index = i * 6 + j;
         // Printing all the ArrayList positions
        Log.i("LOG", "* Array Index #" + cal_index + " = " + numbers.get(cal_index));
    }
     // printing the first 6 positions
    Log.i("LOG", "Array Index #" + i + " = " + numbers.get(i));
}
Log.i("LOG", "Array size #" + numbers.size());