Monday 4 July 2016

Add elements to an existing Array without creating new Array

Hi, Today I'm going to talk about Arrays class. Because this question is asked by few people in Interviews. As usual Array is indexed collection of  fixed nu number of elements. So, how can we add an element to an existing array? For this we go for Arrays class, which provides some utility methods for arrays. By using this class we can add element to array like below,

int[] intArray={1,2,3};
intArray = addElement(intArray, 4);
......
public int[] addElement(int[] existingArray, int element){
  existingArray= Arrays.copyOf(existingArray, existingArray.length +1);
  existingArray[existingArray.length - 1] = element;
}

Like above, Arrays class provides some other utilities also.