Array Operations
Initializing the array
Following syntax can be used to create arrays in java. The array is initialized to hold 5 integers. Currently all values of the array are set to 0.
int[] intArray= new int[5];
Please note that once the size of array is initialized it cannot be changed. Also arrays can be single dimensional or multidimensional. In this chapter we will cover only single dimensional arrays. The next chapter will cover multidimensional arrays. If we want to set the value of all the positions/indexes of above array, we can use below code:
intArray[0]=63; intArray[1]=51; intArray[2]=99; intArray[3]=48; intArray[4]=11; intArray[5]=42;
Another way to initialize an array of integers is shown below. The size of the array is 7 and value at all positions/indexes has been initialized to the values in the curly brackets.
int[] intArray = {1,2,3,4,3,2,1};
Please note that array indices start from 0 and go up to one less that length of the array. So,for above intArray, below are the values at various array index. Please note that the length of the array is 7, but the index goes up to 6 only. If you try to access index 7, the program will throw an exception.
Data at index 0 = 1
Data at index 1 = 2
Data at index 2 = 3
Data at index 3 = 4
Data at index 4 = 3
Data at index 5 = 2
Data at index 6 = 1
Arrays of other java data types can also be created. Below arrays of type float and String have been created. If you have a custom created class called Invoice, you can create and array that holds objects of type Invoice as shown below
String[] strArray=new String[10]; float[] floatArray=new float[5]; Invoice[] invArray=new Invoice[100];
Length of the array
The length of the array be accessed using the length function as shown below:
int intArrayLength= intArray.length; int strArrayLength= strArray.length;
Accessing the array elements
To access particular element in the array we can simply use its index. Below we are printing the value at index 3:
int[] intArray = {1,2,3,4,3,2,1};
System.out.println(intArray[3]);
To iterate through all the array element we can use For loops. For loop example is shown below. We could have uses while loops also if needed.
int[] intArray = {1,2,3,4,5,6,7};
for (int arrayIndex=0; arrayIndex < intArray.length; arrayIndex++) {
System.out.println("Data at index "+arrayIndex +" = "+ intArray[arrayIndex]);
}
Changing array element values
To change the value at any index you can simply use the code as shown below, where we are changing the value stored at index 3:
intArray[3]=22;
If you have intArray initialized as shown in code below, you may need to overwrite or insert a new data to the array. Overwriting new data to a particular index is easy as shown below. “4” was the data at index 3 initially. Using code below we can update data at index 3 to “9”.
int[] intArray = {1,2,3,4,5,6,7};
intArray[3]=9;
Inserting a new element in an existing array
If we want to “insert” a new value “9” to index 3, it means data already at index 3 will be shifted to index 4, original data at index 4 will be shifted to index 5 and so on. The array elements will look as shown below after the insertion of “9” at index 3
{1,2,3,9,4,5,6};
The size of array is fixed, when a new element is inserted to index 3, all data from index 3 to index 5 is shifted one index to the right. How ever there is no space in the array for data “7” originally at index 6, so this data is now lost. Below is the code for a java method to insert an element at a particular index in an existing integer array:
Pseudocode:
| The java method should accept following input parameters: arr (int array), data (data to be inserted), idx (index at which data is to be inserted). |
| Iterate in reverse direction from last index of array to one index greater than the index at which new element is to be inserted
For each iteration above set data at index n to data at index n-1
|
| Set data at index idx to data |
| Return arr, as the element that needed to be inserted has been inserted to arr. |
Reference code is given below. For sake of brevity, code for validation for the method’s input parameters is not provided. To ensure that the code works properly, ensure input parameters are valid before calling the method.
Code:
public int[] insertElement(int[] arr, int data, int idx) throws Exception{
for (int currIdx=arr.length-1; currIdx >= idx+1; currIdx--) {
arr[currIdx]=arr[currIdx-1];
}
arr[idx]=data;
return arr;
}
Deleting an element in the array
To delete element from an array, we need to shift all elements from next index of the element left by 1 index. The last index can be filled with 0 in case on integer array, or null in case of char, String, Object arrays. The below code searches for index of the data to be deleted and then shifts all elements beyond the searched index left by 1 place:
Pseudocode:
| The java method should accept following input parameters: arr (int array), toDelete (data to be deleted). |
| Initialize int data variable named dataIndex to -1. We will use this variable to store the index at which data is stored in arr. |
| Iterate on arr, from first index of array to one index lesser than array length, using idx as the loop variable:
If data at current index idx is equal to toDelete , set dataIndex to idx.
|
| If dataIndex is not -1, this means we have found index of toDelete in arr:
Iterate on arr, from index dataIndex to two index lesser than array length, using idx as the loop variable:
Set arr[idx] to arr[idx+1], this will delete element at index dataIndex and shift all data elements to one index left.
Set arr[length-1] to 0. This will set data at last index to 0 as data at last index has been shifted left and so the last index is empty.
|
| Return arr, as the element that needed to be deleted has been deleted from arr. |
Reference code is given below. For sake of brevity, code for validation for the method’s input parameters is not provided. To ensure that the code works properly, ensure input parameters are valid before calling the method..
Code:
public static int[] arrayDeleteElement(int[] arr, int data) throws Exception{
int dataIndex=-1;
for (int idx=0; idx < arr.length; idx++) {
if (arr[idx]==data) {
dataIndex=idx;
break;
}
}
if (dataIndex != -1) {
for (int idx=dataIndex; idx < arr.length-2; idx++) {
arr[idx]=arr[idx+1];
}
arr[arr.length-1]=0;
}
return arr;
}
Note:
for sorting and searching algorithms using arrays, please refer to the chapters dedicated to sorting and searching. Sorting and searching are not included in current chapter to avoid duplication.
| About Us | Privacy Policy | Contact us |