如何在容量不足的数组中找到最后一个元素?
How to find the last element in an under capacity array?
假设我的数组是这样定义的:
int [] p = new int[10];
p[0] = 1;
p[1] = 4;
p[2] = 7;
我知道我可以使用 ArrayList 而不必担心调整大小,但我只想知道如何找到该数组中最后一个元素 (7) 的索引。这是我尝试过的,但失败了,因为显然我无法将 int 与 null 进行比较。你还会怎么做?
int tail=0;
for(int i= 0; i < p.length; i++){
if(a[i]==null){
tail= i-1;
break;
}
}
查看 this code
:
import java.util.Arrays;
class IntArrayExample {
public static void main(String[] args) {
int[] p = new int[10];
p[0] = 1;
p[1] = 4;
p[2] = 7;
System.out.println(Arrays.toString(p));
int tail=0;
for(int i= 0; i < p.length; i++){
if(p[i]==0){
tail= i-1;
System.out.println("tail : " + tail);
break;
}
}
}
}
输出:
[1, 4, 7, 0, 0, 0, 0, 0, 0, 0]
tail : 2
如你所见,我print the array
,int array
是用zeros
初始化的。在这种情况下,尾巴是 2
。如果您还想在数组中包含 elements with the value of zero
并且不想使用 ArrayList
、initialise all elements to another value (e.g. Integer.MAX_VALUE or Integer.MIN_VALUE)
然后 do your checks accordingly
.
对了,这行代码是错误的:
if(a[i]==null){
不仅因为 incomparable types: int and <null>
,还因为你的数组被称为 p
而不是 a
。希望对您有所帮助!
当您初始化特定大小的 int
array
时,它将默认值设置为零,直到它被设置新的非零值替换。
示例:
问题中提到的数组将具有如下默认值。
[1, 4, 7, 0, 0, 0, 0, 0, 0, 0]
现在如果你想找到数组的最后一个非零值,下面的解决方案可以帮助你实现它。
使用下面提到的代码获取索引值。
public static void main(String[] args) {
int [] p = new int[10];
p[0] = 1;
p[1] = 4;
p[2] = 7;
System.out.println(getLastFilledIndex(p));
}
private static int getLastFilledIndex(int[] p) {
for(int i=p.length-1;i>0;i--){
if(p[i]!=0){
return i;
}
}
return 0;
}
输出:
2
如上所示,代码将从最后一个索引开始迭代,直到找到非零值和 return 索引。
假设我的数组是这样定义的:
int [] p = new int[10];
p[0] = 1;
p[1] = 4;
p[2] = 7;
我知道我可以使用 ArrayList 而不必担心调整大小,但我只想知道如何找到该数组中最后一个元素 (7) 的索引。这是我尝试过的,但失败了,因为显然我无法将 int 与 null 进行比较。你还会怎么做?
int tail=0;
for(int i= 0; i < p.length; i++){
if(a[i]==null){
tail= i-1;
break;
}
}
查看 this code
:
import java.util.Arrays;
class IntArrayExample {
public static void main(String[] args) {
int[] p = new int[10];
p[0] = 1;
p[1] = 4;
p[2] = 7;
System.out.println(Arrays.toString(p));
int tail=0;
for(int i= 0; i < p.length; i++){
if(p[i]==0){
tail= i-1;
System.out.println("tail : " + tail);
break;
}
}
}
}
输出:
[1, 4, 7, 0, 0, 0, 0, 0, 0, 0]
tail : 2
如你所见,我print the array
,int array
是用zeros
初始化的。在这种情况下,尾巴是 2
。如果您还想在数组中包含 elements with the value of zero
并且不想使用 ArrayList
、initialise all elements to another value (e.g. Integer.MAX_VALUE or Integer.MIN_VALUE)
然后 do your checks accordingly
.
对了,这行代码是错误的:
if(a[i]==null){
不仅因为 incomparable types: int and <null>
,还因为你的数组被称为 p
而不是 a
。希望对您有所帮助!
当您初始化特定大小的 int
array
时,它将默认值设置为零,直到它被设置新的非零值替换。
示例:
问题中提到的数组将具有如下默认值。
[1, 4, 7, 0, 0, 0, 0, 0, 0, 0]
现在如果你想找到数组的最后一个非零值,下面的解决方案可以帮助你实现它。
使用下面提到的代码获取索引值。
public static void main(String[] args) {
int [] p = new int[10];
p[0] = 1;
p[1] = 4;
p[2] = 7;
System.out.println(getLastFilledIndex(p));
}
private static int getLastFilledIndex(int[] p) {
for(int i=p.length-1;i>0;i--){
if(p[i]!=0){
return i;
}
}
return 0;
}
输出: 2
如上所示,代码将从最后一个索引开始迭代,直到找到非零值和 return 索引。