# array.length – 1 在数组末尾是如何可视化理解的？

go评论50阅读模式

Can someone help me visually understand how array.length - 1 is at the end of the array?

# 问题

I am trying to solve a binary sort problem in Java. I can't wrap my head around why the end of the array would be array.length - 1.

if

``````int[] array = [0,1,2,3,4]

int start = 0;
int end = array.length - 1;
``````

Wouldn't end return 3?

I am trying to solve a binary sort problem in Java. I can't wrap my head around why the end of the array would be array.length - 1.

if

``````int[] array = [0,1,2,3,4]

int start = 0;
int end = array.length - 1;
``````

Wouldn't end return 3?

# 答案1

## Explanation

``````值：  3 6 1 8 4

``````

## 背景

``````array[i]
``````

``````sizeof(type) * i
``````

## Explanation

The term index (something like position) starts counting at `0`.

So your array, which has 5 elements, has elements at indices `0, 1, 2, 3, 4`. So the last element is indeed at index `4`, which is `length - 1`.

So visualized, for an array like `{ 3, 6, 1, 8, 4 }` we have

``````values:  3 6 1 8 4
indices: 0 1 2 3 4
``````

## Background

I suppose one of the strongest reasons why the indices (at least in Java and many other languages) start counting at `0` has to do with how it is implemented under the hood, as in:

``````array[i]
``````

basically being computed as

``````sizeof(type) * i
``````

to get hands on the actual memory address offset. And having `0` there would result in an offset of `0`, so the beginning of the memory for this array.

There are actually languages that did not go this route, like Matlab where indices start counting at `1`.

# 答案2

Array length would be 5, since there are 5 elements in the array.

Element `0` is the 1st element (index 0), element `1` is the second (index 1), ..., element `4` is the fifth (index 4).

So the index of the last element is `5-1 = 4`.

Array length would be 5, since there are 5 elements in the array.

Element `0` is the 1st element (index 0), element `1` is the second (index 1), ..., element `4` is the fifth (index 4).

So the index of the last element is `5-1 = 4`.

# 答案3

This list is of length 5. The last index is 4, though, because the first index is 0 (not 1).

# 答案4

`array.length` 是 5。

`array.length` is 5.

In Java, you start counting arrays at 0, so `array[0]` would be 0.

Count upwards, and you'll find that the last element of that array, (as you have defined it) has index position 4, ie `array.length - 1`

# 答案5

Indexes start at 0.

Sizes/Lengths start at 1.

Array length = 5;

Last element is in Index the length - 1 (the difference between sizes/lengths indexes).

Indexes start at 0.

Sizes/Lengths start at 1.

Array length = 5;

Last elemnt is in Index the length - 1 (the difference between sizes/lengths indexes.

• 本文由 发表于 2020年7月22日 21:44:50
• 转载请务必保留本文链接：https://go.coder-hub.com/63035655.html
• arrays
• java

go 41

go 43

go 36

go 41