java - Various ways of accessing an array -


today did learn 2 ways of accessing array, know various ways of accessing array element , best practice of it. student learning algorithm.

int [] arr; long [] arr; 

advantages of long datatype declaration on int.

class arrayapp{      public static void main(final string[] args){   long [] arr;      arr= new long[2];  int i;  arr[0]=112;  arr[1]=111;      **// way one**   for(long l:arr)   {  system.out.println(l);  }      **// way two**   for(i=0;i<arr.length;i++) {  system.out.println(arr[i]);  }      }  }  

we've 1 declaration of array:

long[] values = new long[100]; 

this creates array 100 long type values. each value has index (position) inside array, first index (an int value!) 0, last 1 99.

the traditional loop increments integer value generate index position numbers. int values used access long values of array:

for (int index=0; index < values.length; index++) {   // index int   long value = values[index];                         // value long   // value } 

the "enhanced" loop hides index , gives access long values less code:

for (long value:values) {   // value } 

that's all. if don't need index variable in code, use enhanced loop (second version in answer)


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -