Title: ArrayList
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

ArrayList

Although we do have some software (java.util.Arrays.java) to support Arrays, we would like something with more functionality and flexibility:

java.util.ArrayList.java

We don't need to know the size of the array up front.

We get some useful software methods.

We will start with the non-generic version of ArrayList which has been around the longest (generics were added around release 1.5). The following is a subset of the features of ArrayList:

- ArrayList(int size)
- ArrayList( ) - default size of 10
- int size( )
- Object get(int index)
- add( Object)
- add(int index, Object)
- Object set(int index, Object)
- index indexOf(Object)
- Object remove(int index)
- boolean remove(Object )
- String toString( )

Simple Example using some of these methods

package arrayListNonGeneric;

import java.util.ArrayList;


class Dog
{
    String name;
    int age;
    Dog (String n, int a)
    {
        name = n;
        age = a;
    }
    public String toString()
    {
        return name + " age ="+ age;
    }
    void bark()
    {
        System.out.println(name + " says bark");
    }
}

public class ArrayListDemo1 {


    public static void main(String[] args) {
        ArrayList arr = new ArrayList();

        arr.add("Red");
        arr.add(new Integer(5));
        arr.add(5);
        arr.add(new Dog("Fido", 4));

        for (int i=0; i < arr.size(); i++)
        {
            Object ob = arr.get(i);
            if (ob instanceof Dog)
            {
                Dog dog = (Dog)ob;
                dog.bark();
            }
            else if (ob instanceof String)
            {
                System.out.println("String: " + ob);
            }
            else if (ob instanceof Integer)
            {
                Integer intClass =(Integer) ob;
                int x = intClass;
                System.out.println("Integer object: "+ x);
            }
        }


    }

}




Another example


package arrayListNonGeneric;

import java.util.ArrayList;

public class ArrayListDemo2 {


    public static void main(String[] args) {
        ArrayList arr = new ArrayList(20);

        arr.add("one");
        arr.add("three");

        arr.add(1, "two");
        System.out.println("after 3 adds: " + arr);

        arr.add("abc");
        System.out.println("after adding abc: " + arr);
        arr.set(3, "four");
        System.out.println("after set(3,four): " + arr);

        try
        {
            arr.set(4, "five");
        }
        catch (IndexOutOfBoundsException e)
        {
            System.out.println("Can't do a set on an index that doesn't exist yet: "+e);
        }

        arr.add(4, "five");
        System.out.println("after 5 adds: " + arr);

        try
        {
            arr.add(6, "seven");
        }
        catch (IndexOutOfBoundsException e)
        {
            System.out.println("Can't do an add in such a way as to leave a gap: "+e);
        }
        System.out.println("after all successful adds: " + arr);

        // Note that using indexOf requires implementing "equals".
        // If we were adding our dog class, we would need an equals method otherwise it
        // won't find what we are looking for.
        int index = arr.indexOf("three");
        System.out.println("The index of three is :" + index);

        index = arr.indexOf("seven");
        System.out.println("The index of seven is :" + index);

        // The following will require the implementation of "equals"
        arr.remove("two");
        System.out.println("after removing two: " + arr);

        arr.remove(0);
        System.out.println("after removing index 0: " + arr);

        System.out.println("Final size="+ arr.size());

    }

}



MyArrayList.java

In order to get an idea of what is underneath the hood we will provide an implementation of a class that is similar to ArrayList


package arrayListNonGeneric;


public class MyArrayList {
    Object[] container;
    int numElements =0;

    public MyArrayList(int initialSize)
    {
        container = new Object[initialSize];
    }
    public MyArrayList()
    {
        this(10);
    }

    public int size()
    {
        return numElements;
    }
    public void add(Object ob)
    {
        if (numElements >= container.length)
        {
            resize();
        }
        container[numElements++] = ob;
    }
    public Object get(int index)
    {
        if (index < 0 || index >= numElements)
            throw new IndexOutOfBoundsException("Index out of bounds");
        return container[index];
    }

    private void resize()
    {
        int currSize = container.length;
        Object[] nextContainer = new Object[currSize*2];
        for (int i=0; i < numElements; i++)
            nextContainer[i] = container[i];

        container = nextContainer;
    }
    Object set(int index, Object ob)
    {
        if (index < 0  || index >= numElements)
            throw new IndexOutOfBoundsException("Index out of bounds: "+ index);
        Object replacedObject = container[index];
        container[index] = ob;

        return replacedObject;
    }
    // Inserts object at desired location
    void add(int index, Object ob)
    {
        if (index < 0  || index > numElements)
            throw new IndexOutOfBoundsException("Index out of bounds: "+ index);
        add(ob); // This will increase our size by 1
        // Shift objects to make room for the new addition
        for (int i= numElements-1; i > index; i--)
        {
            container[i] = container[i-1];
        }
        container[index] = ob;
    }

    // For this to work, the objects need to implement equals
    int indexOf(Object ob)
    {
        for (int i=0; i < numElements; i++)
        {
            if (ob.equals(container[i]))
                return i;
        }
        return -1;
    }

    Object remove(int index)
    {
        if (index < 0  || index >= numElements)
            throw new IndexOutOfBoundsException("Index out of bounds: "+ index);

        // Shift everything down
        Object removedObject = container[index];
        for (int i= index; i < numElements-1; i++)
        {
            container[i] = container[i+1];
        }
        numElements -= 1;
        return removedObject;
    }

    // for this to work, the objects need to implement equals
    boolean remove (Object ob)
    {
        int index = indexOf(ob);
        if (index < 0)
            return false;

        remove(index);
        return true;
    }

    public String toString()
    {
        StringBuilder sb= new StringBuilder();
        sb.append("[ ");
        for (int i=0; i < numElements; i++)
        {
            sb.append(container[i].toString());
            if (i < numElements-1)
                sb.append(",");
        }
        sb.append(" ]");
        return sb.toString();
    }

}




Try out the MyArrayList in the above Demos

Last Updated: October 22, 2013 12:55 PM