How To Create An Array Class in Java
In this post, I created an Array class from scratch in Java. This topic is not a data structure lesson. It is only about how to create an array class.
I created an Array class with methods such as add(), removeAt, indexOf, and size.
I assumed the items in the array are integers. The image below is the initialization of the Array class.
The properties are pretty self explanatory. I created a constructor since by default, arrays in Java needs to be initialized with a length.
print() method
This print() method is just for printing items in the console. As you can see, I used the count variable for iterating over the items.
add() method
This add() method has a value parameter. Before we insert the value into the items, we expand it if the items are full.
First, we check if the current count is equals to our items length. If full, we create another items doubled to its size. Then we copy the old items to the new items.
If it is all set and done, we add the item in our items array. We increment the count after we add the item.
removeAt() method
In the removeAt method, it has an index parameter and it will be used for removing an item based on its index.
First, we validate the index by throwing an IllegalArgumentException() when the index is less than 0 or greater than the count.
Then, we shift the items to the left since removing an item will create a ‘hole’. After the shifting, we decrement the count property.
You might ask why we need to subtract one from the count. Since we are ‘shifting’ items to the left, the item[i + 1] might be out of bounds and would throw ArrayIndexOutOfBoundsException. To prevent that from happening, we subtract 1 from the count.
indexOf() method
In the indexOf method, we iterate over our items then check to see if the current item in the iteration is equals to the item parameter.
It returns the i or the current iteration number if found.
If not, it returns -1.
size() method
Remember the count property we had? The size property is useful because we don’t need to iterate over the items then store the count number in a variable.
Overall, this is just the basics of creating an Array class from Java. You can extend the class as you like. Thank you for reading this. I hope you learned something. You can message me via Twitter, and Instagram. You can also visit my GitHub account.