How to resize an array in java

In General terms, As we know that we cannot resize an array once we initialized because array defination says that an array is an fixed size,sequence and collection of similar data type. But It is possible to resize an array, resizing an array is nothing but copy the content of old array to new index array as per our requirement. Following code snippets is usefull for resize an array. Java.lang.System.arraycopy() Method is responsible for resizing an array.
File Name :
What is Java.lang.System.arraycopy() Method :
The java.lang.System.arraycopy() method copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest.The number of components copied is equal to the length argument.
The components at positions srcPos through srcPos + length - 1 in the source array are copied into positions destPos through destPos + length - 1, respectively, of the destination array.
Syntax :
  • src       -- This is the source array.
  • srcPos -- This is the starting position in the source array.
  • dest -- This is the destination array.
  • destPos -- This is the starting position in the destination data.
  • length -- This is the number of array elements to be copied.
Return Value: Method does not return any value.
Exception Details:
  • IndexOutOfBoundsException  --if copying would cause access of data outside array bounds.
  • ArrayStoreException -- if an element in the src array could not be stored into the dest array because of a type mismatch.
  • NullPointerException -- if either src or dest is null.
Another Example : File Name
output : array2 = 0 10 20 30 40

posted under |


Post a Comment

Please provide your valuable comment.

Newer Post Older Post Home


Powered by Blogger.


Custom Search