user5461057
user5461057

Reputation:

Creating an Array List from scratch

I was wondering if anyone would be able to point me in the correct direction in regards to creating my own array list methods. For instance, the current project I am assigned to does not allow for me to use the methods given to me for free like in the following example.

    package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {

   // create an empty array list with an initial capacity
   ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

   // use add() method to add elements in the list
   arrlist.add(15);
   arrlist.add(22);
   arrlist.add(30);
   arrlist.add(40);

   // adding element 25 at third position
   arrlist.add(2,25);

   // let us print all the elements available in list
   for (Integer number : arrlist) {
   System.out.println("Number = " + number);
   }  
   }
}   

This example shows the add() method. For my project I have to create this method myself and call it from a different file within my package.

Upvotes: 2

Views: 8727

Answers (3)

Uddhav P. Gautam
Uddhav P. Gautam

Reputation: 7636

This is very easy to understand; However, I explained a little bit in comments.

public class MyArrayList<E extends Object> {


    private static int initialCapacity = 5;
    private static int currentSize;
    private Object[] myArrayList = {}, temp = {};

    private static int currentIndex = 0;

    public static void main(String[] args) {
        MyArrayList arrList = new MyArrayList();
        arrList.add("123"); //add String
        arrList.printAllElements();
        arrList.add(new Integer(111)); //add Integer
        arrList.printAllElements();

        arrList.add(new Float("34.56")); //add Integer
        arrList.printAllElements();

        arrList.delete("123");
        arrList.printAllElements();

        arrList.delete(123);
        arrList.printAllElements();
        arrList.delete(123);

        arrList.printAllElements();

    }

    public MyArrayList() {  //creates default sized Array of Objects
        myArrayList = new Object[initialCapacity]; //generic expression

        /* everytime I cross my capacity, 
    I make double size of Object Array, copy all the elements from past myObject Array Object
         */
    }

    public MyArrayList(int size) { //creates custom sized Array of Objects
        myArrayList = new Object[size];
    }

    public void add(Object anyObj) {
        //add element directy
        myArrayList[currentIndex] = anyObj;
        currentSize = myArrayList.length;
        currentIndex++;
        if (currentIndex == currentSize) {
            createDoubleSizedObjectArray(currentSize);
        }
    }

    //print all elements
    public void printAllElements() {
        System.out.println("Displaying list : ");
        for (int i = 0; i < currentIndex; i++) {
            System.out.println(myArrayList[i].toString()); 
        }
    }

    private void createDoubleSizedObjectArray(int currentSize) {
        temp = myArrayList.clone();
        myArrayList = new MyArrayList[2 * currentSize];  //myObject pointer big size data structure

//         myObject = temp.clone(); //probably I can do this here as well. Need to check this
        System.arraycopy(temp, 0, myArrayList, 0, currentSize);

    }

    void delete(Object object) {
        //if already empty 
        if (currentIndex == 0) {
            System.out.println("Already empty!");
            return;
        }
        //you don't need to delete anything. I can simply override the storage
        currentIndex--;
    }
}

Upvotes: 1

You
You

Reputation: 177

I find this as an interesting problem. I am always curious about how things work at the raw level.

If you think about it, an ArrayList is basically just an array that you can expand. So you can either have a really big array (which would take a lot of memory for one ArrayList) or every time you add something, you make a new bigger array and copy the contents and add the new item (which I think the performance is O(N)).

This is my attempt without using any libraries:

public class MyArrayList<T>
{
    private T[] asArray;

    @SuppressWarnings("unchecked")
    public MyArrayList()
    {
        asArray = (T[]) new Object[0];
    }

    public void add(T t)
    {
        @SuppressWarnings("unchecked")
        T[] temp = (T[]) new Object[asArray.length + 1];

        // copy everything over to the new array
        for (int i = 0; i < asArray.length; i++)
        {
            temp[i] = asArray[i];
        }

        // add the new element
        temp[asArray.length] = t;
        asArray = temp;
    }

    public void remove(int index)
    {
        if (index < 0 || index >= asArray.length) return;
        @SuppressWarnings("unchecked")
        T[] temp = (T[]) new Object[asArray.length - 1];

        boolean found = false;
        // copy everything over to the new element
        for (int i = 0; i < asArray.length; i++)
        {
            // don't copy if the indices are the same
            if (i == index)
            {
                found = true;
                continue;
            }
            temp[i - (found ? 1 : 0)] = asArray[i]; // it's i - 1 after the removed object so then it doesn't leave a gap and it doesn't go over the array's length
        }
        asArray = temp;
    }

    public T get(int index)
    {
        return asArray[index];
    }
}

I am quite proud of this code. :) I consider Short_Teeth's code cheating because the class is a subclass and, well, doesn't add anything. I hope I helped.

Upvotes: 3

Monroy
Monroy

Reputation: 430

import java.util.ArrayList;

public class MyArrayList<E> extends ArrayList<E>{

    private static final long serialVersionUID = -5164702379587769464L;

    public void newMethod(){
        // No implementation
    }

}

This is a class which extends from ArrayList and a method called newMethod() was added to this class.

Below we are calling this newly created method in your case you must implement the add to this newly created method.

public class Hello {

    public static void main(String args[]) {

        MyArrayList<Integer> myList = new MyArrayList<Integer>();

        // It has the ArrayList add() method as this new class extends from ArrayList (all the ArrayList methods are included)
        myList.add(2);

        // The newly created method in your case you need to implement the add yourself
        myList.newMethod();
    }
}

This could also be a good link for what you need.

http://www.java2novice.com/java-interview-programs/arraylist-implementation/

I also recomend that you try to implement and solve your problems first and then ask questions about a specific problem, and only after you done a good research about what may be causing this problem (There are lots of resources out there). If you done some research before you asked this question, I'm pretty sure that you would have been able to solve everything on your own.

Hope you find this information useful. Good luck.

Upvotes: 0

Related Questions