Search code examples
javaarraysnullcapacity

How to find the last element in an under capacity array?


Say my array is defined like this:

int [] p = new int[10];
p[0] = 1;
p[1] = 4;
p[2] = 7;

I know I could use an ArrayList and not worry about resizing, but I just want to know how one could find the index of the last element (7) in that array. This is what I tried and it was failing because obviously I can't compare int to null. how else would you go about doing this?

int tail=0;
for(int i= 0; i < p.length; i++){
    if(a[i]==null){
       tail= i-1;
       break;
    }

}

Solution

  • check out 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;
            }
           }
         }
        }
    

    OUTPUT:

    [1, 4, 7, 0, 0, 0, 0, 0, 0, 0]
    tail : 2
    

    as you can see where I print the array, the int array is initialised with zeros. The tail is 2 in this case. If you also want to have elements with the value of zero in your array and don't want to use ArrayList, initialise all elements to another value (e.g. Integer.MAX_VALUE or Integer.MIN_VALUE) and then do your checks accordingly.

    By the way, this line of code is wrong:

     if(a[i]==null){
    

    not only because of incomparable types: int and <null>, but also because your array is called p and not a. Hope that helps !