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


say array defined this:

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

i know use arraylist , not worry resizing, want know how 1 find index of last element (7) in array. tried , failing because can't compare int null. how else go doing this?

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

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; < 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 can see print array, int array initialised zeros. tail 2 in case. if want have elements value of zero in array , don't want use arraylist, initialise elements value (e.g. integer.max_value or integer.min_value) , do checks accordingly.

by way, line of code wrong:

 if(a[i]==null){ 

not because of incomparable types: int , <null>, because array called p , not a. hope helps !


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -