1

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

9
  • 9
    Well ArrayList is also a built-in class. Commented Oct 19, 2012 at 16:18
  • Also, you can add elements in the front of your arraylist. Why are you inserting int?? That is a reserved keyword. Commented Oct 19, 2012 at 16:19
  • Do you remember the lecture your teacher gave on linked lists? Or possibly...a fixed size circular array buffer/queue? Both of those data structures provide efficient ways to add and remove from both the front and end of a list. Commented Oct 19, 2012 at 16:21
  • also, I suspect you mean a queue, not a "deque"? Commented Oct 19, 2012 at 16:23
  • 'int' refers to any integer I want to insert. I am supposed to use array lists... Commented Oct 19, 2012 at 16:23

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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
      }
   }

   ...
}

2 Comments

This is a homework problem, and we shouldn't be posting full solutions to homework here. We should be helping guide in the right direction but not doing the OPs homework.
This is because I add some "..." and "do it yourself" ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.