Certain data structures in Java can be created by you (yes you). In this example, we’ll go ahead and create an ArrayList data structure that has some of the methods that the built-in ArrayList class has.
We’ll create 2 constructors:
- The default constructor that creates an ArrayList with a default size of 10.
- Constructor that allows an initial size to be passed to the array.
We’ll also create a number of methods:
- void add(Object x); A method that allows you to place an Object at the end of the ArrayList.
- void add(int index, Object x); A method that allows you to place a value at a given location.
- Object get(int index): Allows you to retrieve a value of the arrayList array from a given location.
- int size(); Allows you to get the number of elements currently in the Arraylist.
- boolean isEmpty(); Tests to see if the Arraylist is empty.
- boolean isIn(Object x); A method that sees if a particular object exist in the arrayList.
- int find(Object x); Returns the location of first occurrence of an Object starting from location 0.
- void remove(Object x); Removes the first occurrence of an Object starting from location 0.
I encourage you not to look at the ArrayList built-in class. See if you can figure it out on your own. The only other restriction will be to store the Objects in an array data field. Create a test class to test the ArrayList class. Name your ArrayList class ArrayList.java so that it overwrites the built in class.
Read the notes above each method. There is a precondition that states the requirements that you’ll need to abide by before the method is called. For example, if the method requires an array of integers to be passed to it, you will need to have an array of integers ready. After the method is called, there is the post-condition. This explains what the expected output of the method will be and the steps the method takes to achieve that output.
We’ll start off with the ArrayList class. The methods that were outlined above will be added to this class.
What good is the code if you’re not going to test it. We’ll create a Driver class that’s going to test the ArrayList code.
And that’s really all their is too it. With basic Java skills, you too can create your ArrayList data structure.