简体   繁体   English

For循环创建的数组的值比预期的少

[英]For loop creating an array with one less value than expected

I am sure this is something really simple but I have not been able to work out what is going on for a while now. 我敢肯定这确实很简单,但是我暂时无法弄清楚正在发生的事情。

I have a List I get from shared preference: 我有一个从共享首选项中获得的列表:

// Access the shared preferences to see if the user has saved any alarms yet
    SharedPreferences sharedPreferences = context.getSharedPreferences("AppData", Context.MODE_PRIVATE);
    String alarmsstring = sharedPreferences.getString("AlarmsStringSP", "None");

// Split the the main alarm string into array of strings values for alarm objects
    List<String> alarmObjectsArray = Arrays.asList(alarmsstring.split("\\s*;\\s*"));

I check the size of that list using: 我使用以下方法检查该列表的大小:

System.out.println("Testing"+ alarmObjectsArray.size());

And I get: 我得到:

I/System.out: Testing3

Which is what I expect so fine up to there. 我所期望的到那为止都很好。

I then create a new array list and put each element of the old list into the new one converted to an object. 然后,我创建一个新的数组列表,并将旧列表的每个元素放入转换为对象的新列表中。

Like this: 像这样:

   // Iterate through the alarm objects, and place each item into the alarms array
    for (int i = 0; i < alarmObjectsArray.size()-1; i++){
        // For each of the alarm objects split them into their induvidual items so they can be
        // converted back to the correct type.
        List<String> alarmItems = Arrays.asList(alarmObjectsArray.get(i).split("\\s*,\\s*"));
        Alarm alarm = new Alarm(Integer.parseInt(alarmItems.get(0)),Integer.parseInt(alarmItems.get(1)),
                Boolean.parseBoolean(alarmItems.get(2)), Boolean.parseBoolean(alarmItems.get(3)),
                Boolean.parseBoolean(alarmItems.get(4)),Boolean.parseBoolean(alarmItems.get(5)),
                Boolean.parseBoolean(alarmItems.get(6)), Boolean.parseBoolean(alarmItems.get(7)),
                Boolean.parseBoolean(alarmItems.get(8)));
        alarms.add(alarm);
    }

The only thing is when it comes out of the for loop I check the new array size with: 唯一的事情是当它退出for循环时,我使用以下命令检查新的数组大小:

System.out.println("Testing"+ alarms.size());

And I get: 我得到:

I/System.out: Testing2

Somehow it has lost one when it was taken from the list into the array. 当它从列表中被带入数组时,它以某种方式丢失了一个。 I know there is a lot text in the for loop but I can't see any reason for having one less. 我知道for循环中有很多文本,但是我看不出有什么原因少了一些。

for (int i = 0; i < alarmObjectsArray.size(); ++i/*I'm an old-fashioned cat*/){ will index over every element in the array. for (int i = 0; i < alarmObjectsArray.size(); ++i/*I'm an old-fashioned cat*/){将在数组中的每个元素上进行索引。 ( i will start at 0, and finish at and including a value one less than the size of the array). i将从0开始,到并包括一个小于数组大小的值)。

Drop the -1 term. 删除-1项。

For the avoidance of doubt, Java arrays are zero-based . 为避免疑问,Java数组从零开始 Java ain't Fortran you know. 您知道Java不是Fortran。

Finally, < size() is more idiomatic than the equivalent <= size() - 1 . 最后, < size()比等效的<= size() - 1更习惯。 Futhermore size() - 1 can yield sheer devilry in C++ if size() is an unsigned type - as it often is - and happens to be zero! 此外, size() - 1如果size()是无符号类型(通常是无符号类型size()并且恰好为零,则size() - 1可以在C ++中产生纯粹的魔鬼现象!

Let's analyze this code: 让我们分析一下这段代码:

for (int i = 0; i < alarmObjectsArray.size()-1; i++)
  • for means that the code inside the loop is done until the condition is true. for表示循环内的代码完成,直到条件成立为止。

  • The first loop will run with i = 0 , as you correctly set. 正确设置后,第一个循环将以i = 0运行。

  • Every loop will add 1 to i since you wrote i++ . 自从您编写i++以来,每个循环都会为i加1。

  • Your exit condition is i < size-1 . 您的退出条件是i < size-1 Since size = 3 , it means i < 3-1 , equals to i < 2 so the code will run for i = 0 and i = 1 由于size = 3 ,这意味着i < 3-1 ,等于i < 2因此代码将在i = 0和i = 1的情况下运行

This means the code will run only 2 times. 这意味着代码将仅运行2次。

In for loop, if you want to avoid the foreach , use i < size or i <= size-1 , otherwise you will lose an item. 在for循环中,如果要避免使用foreach ,请使用i < sizei <= size-1 ,否则将丢失一个项目。

Hope you understood the explaination. 希望您理解说明。

As I see you do not certainly understand the for loop, so let's focus on it. 如我所见,您不一定了解for循环,因此让我们集中精力。

int[] array = new int[5];
System.out.println(array.size());
for (int i = 0; i < array.size(); i++) {
    System.out.println(i);
}

The above code will print: 上面的代码将打印:

>5
>0
>1
>2
>3
>4

The array has 5 cells. 该阵列有5个单元。 The're 0-indexed so the indexes start from 0 . The're 0-indexed ,因此指数从开始0 It results in last cell having the index of array.size() - 1 . 结果是最后一个单元格的索引为array.size() - 1 So if you want to loop through all indexes you have to loop from 0 to array.size()-1 . 因此,如果要遍历所有索引,则必须从0array.size()-1进行循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM