Java 如何从 1 而不是零开始索引数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18484509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:03:47  来源:igfitidea点击:

How I can index the array starting from 1 instead of zero?

java

提问by Anna89

for (int i = 0; i < reports.length; i++) {

  Products[] products = reports[i].getDecisions;

  for (int j = 0; j < products.length; j++) {

  }
}

Here I want to index the inner for loop starting from 1 , but it is not working as expected, I also changed the j

在这里,我想索引从 1 开始的内部 for 循环,但它没有按预期工作,我还更改了 j

采纳答案by MicSim

Java arrays are always 0-based. You can't change that behavior. You can fill or use it from another index, but you can't change the base index.

Java 数组总是从 0 开始的。你无法改变这种行为。您可以从另一个索引填充或使用它,但不能更改基本索引。

It's defined in JLS §10.4, if you are interested in it.

如果您对它感兴趣,它在JLS §10.4 中定义。

A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].

All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.

数组的组件由数组访问表达式(第 15.13 节)访问,该表达式包含一个表达式,其值为数组引用,后跟一个由 [ 和 ] 括起来的索引表达式,如 A[i]。

所有数组都是 0-origin。长度为 n 的数组可以由整数 0 到 n-1 进行索引。

回答by Peter Jaloveczki

Just like in most languages arrays are indexed from 0. You better get used to it, there is no workaround.

就像在大多数语言中数组从 0 开始索引一样。你最好习惯它,没有解决方法。

回答by r3ap3r

Base Index of Java arrays is always 0. It cannot be changed to 1.

Java 数组的基本索引始终为0。它不能更改为 1。

回答by Mahesh Gosemath

You can't do that as array index in Java starts from 0. But you can access array with index 1 with little modifications.

您不能这样做,因为 Java 中的数组索引从 0 开始。但是您可以访问索引为 1 的数组,只需稍作修改。

Example: Consider an integer array "a" with length n

示例:考虑一个长度为 n 的整数数组“a”

for(int i=0;i<n;i++) {
    System.out.println(a[i]);
}

This can be modified as:

这可以修改为:

int a[] = new int[n+1];
for(int i=1;i<n+1;i++) {
    System.out.println(a[i]);
}

回答by Animesh Pathak

You can use pointers, to jump to a certain point of the array and start the array from there.

您可以使用指针跳转到数组的某个点并从那里开始数组。

For example:

例如:

char str[20];
str={'H', 'E' ,'L' ,'L', 'O','W' ,'O ','R','L',' D'};
char *ptr;
*ptr=str[0];
//right now its pointing to the starting.
ptr=ptr+3;
//Now pointing at 3rd unit.

This doesn't work in every compiler.This is the closest thing that can be done for your question.

这不适用于每个编译器。这是可以为您的问题做的最接近的事情。