Search This Blog

17 June, 2011

Resizing an array


Array in java part 1

Array in java part 2




Resizing an array:- 


In C/C++ an array can't be resized since concept of array is not the same in java can't be technically but can be logically resized.


Consider the following example in which it can be said that an array of 5 elements has been resized to an array of 10 elements.


class ppp
{
public static void main(String hh[])
{
int x[];
x=new int[5];
x[0]=33;
x[1]=14;
x[2]=44;
x[3]=56;
x[4]=493;


/*Till now x is pointing to an array type object with 5 elements.*/


int t[];
t=new int[10];
 /*a new array type object is created with 10 elements and pointer t points to it.*/


int e;
e=0;
while(e<x.length)
{
t[e]=x[e];
e++;
}
/* In the above looping construct all the values that are in the object to which pointer x points have been copied to the new array with 10 elements. */


x=t;


/*Pointer x now starts pointing to an array type object with 10 elements. */


x[5]=34;
x[6]=45;
x[7]=123;
x[8]=7623;
x[9]=939;
e=0;
while (e<x.length)
{
System.out.println(x[e]);
e++;
}
/* The above loop will get executed 10 times. */
}
}
----------------------------------------------------------------------------------

No comments:

Post a Comment

Meetme@