如何在容量不足的数组中找到最后一个元素?

时间:2015-03-28 18:45:13

标签: java arrays null capacity

假设我的数组定义如下:

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;
    }

}

2 个答案:

答案 0 :(得分:2)

结帐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,并且不想使用ArrayListinitialise 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。希望有所帮助!

答案 1 :(得分:1)

初始化特定大小的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

如上所示,代码将从最后一个索引迭代,直到找到非零值并返回索引。