jsan
jsan

Reputation: 1057

Manually manipulating ArrayList

I have an assignment where I have to create a deque, however I am not allowed to use any built-in classes or interfaces. I am implementing my deque using an array list. My problem is that when I have to, for instance, add to the beginning of the array list (beginning of the queue), i am not allowed to do this:

public void addFirst(ArrayList<Integer> array) 
{
    array.add(0, int);
}

Is there a way to do this without using the add() function? Such as manually adding to the front and shifting the rest of the array to the right? Or maybe creating a new array list and copying...I'm not sure. Any help would be great; I have a bunch of functions to write, and getting the first one done will definitely put me in the right direction. Thanks

Upvotes: 1

Views: 534

Answers (2)

Aubin
Aubin

Reputation: 14873

class ArrayList< T >
{
   private int _capacity;
   private int _size;
   private T   _data;

   ArrayList( int capacity )
   {
      _capacity = capacity;
      _size     = 0;
      _data     = new T[_capacity];
   }

   void add( T t )
   {
      if( _size < _capacity )
      {
         _data[_size++] = t;
      }
      else
      {
         // do it yourself
      }
   }

   void insert( int index, T t )
   {
      if( _size < _capacity )
      {
         System.arrayCopy( _data, index, _data, index + 1, _size - index );
         _data[_size++] = t;
      }
      else
      {
         // do it yourself
      }
   }

   ...
}

Upvotes: 0

Jeff Storey
Jeff Storey

Reputation: 57212

If you're not allowed to use any of the built in list classes, I suspect you should be looking at arrays, not ArrayList. There are functions like System.arrayCopy that may help you here.

Upvotes: 2

Related Questions