Link to home
Start Free TrialLog in
Avatar of tyweed420
tyweed420

asked on

trying to ake a clone of my queueArray however it is not cloning the entire array?

I have implemented a QueueArray and now i'm simply trying to make a clone , however there is something missing in my clone() in order to get the complete copy of my existing queueArray.

  public Object clone()
                 {
                QueueArray queue = null;

                    try
                    {
                     queue =  (QueueArray) super.clone();
                    }
                    catch (CloneNotSupportedException ignore)
                    {
                    //This will never happen because this class is Clonable
                    return null;  //Never get here
                    }
                //i need something here to somehow clone the array portion as well yes?
               return queue;

                }


============ entire code=====
  /**
     * Array-based implementation of the queue.
     * @author Mark Allen Weiss
     */
    public class QueueArray implements Cloneable
    {
        /**
         * Construct the queue.
         */
        public QueueArray( )
        {
            this( DEFAULT_CAPACITY );
        }

        /**
         * Construct the queue.
         */
        public QueueArray( int capacity )
        {
            theArray = new int[ capacity ];
            makeEmpty( );
        }

        /**
         * Test if the queue is logically empty.
         * @return true if empty, false otherwise.
         */
        public boolean isEmpty( )
        {
            return currentSize == 0;
        }

        /**
         * Test if the queue is logically full.
         * @return true if full, false otherwise.
         */
        public boolean isFull( )
        {
            return currentSize == theArray.length;
        }

        /**
         * Make the queue logically empty.
         */
        public void makeEmpty( )
        {
            currentSize = 0;
            front = 0;
            back = -1;
        }

        /**
         * Get the least recently inserted item in the queue.
         * Does not alter the queue.
         * @return the least recently inserted item in the queue, or null, if empty.
         */
        public int getFront( )
        {
            if( isEmpty( ) )
                return -1;
            return theArray[ front ];
        }

        /**
         * Return and remove the least recently inserted item from the queue.
         * @return the least recently inserted item in the queue, or null, if empty.
         */
        public int dequeue( )
        {
            if( isEmpty( ) )
                return -1;
            currentSize--;

            int frontItem = theArray[ front ];
            theArray[ front ] = -1;
            front = increment( front );
            return frontItem;
        }

        /**
         * Insert a new item into the queue.
         * @param x the item to insert.
         * @exception Overflow if queue is full.
         */
        public void enqueue( int x )
        {
            if( isFull( ) )
           System.out.println("queue is full");
           back = increment( back );
            theArray[ back ] = x;
            currentSize++;
        }

        /**
         * Internal method to increment with wraparound.
         * @param x any index in theArray's range.
         * @return x+1, or 0, if x is at the end of theArray.
         */
        private int increment( int x )
        {
            if( ++x == theArray.length )
                x = 0;
            return x;
        }

          public Object clone()
                 {
                QueueArray queue = null;

                    try
                    {
                     queue =  (QueueArray) super.clone();
                    }
                    catch (CloneNotSupportedException ignore)
                    {
                    //This will never happen because this class is Clonable
                    return null;  //Never get here
                    }
               
               return queue;

                }



        private int [ ] theArray;
        private int        currentSize;
        private int        front;
        private int        back;

        static final int DEFAULT_CAPACITY = 10;


        public static void main( String [ ] args )
        {
            QueueArray q = new QueueArray( );
                        QueueArray temp = new QueueArray( );


            try
            {
                    q.enqueue( 1 );
                    q.enqueue( 2 );
                    q.enqueue( 3 );
                    temp = (QueueArray) q.clone();
                    temp.enqueue(4);


                   System.out.println( q.getFront()  + "test") ;
            }
            catch( Exception e ) { System.out.println( "Unexpected overflow" ); }

                while( !q.isEmpty( ) )
                System.out.println( q.dequeue( ) );
                System.out.println("=");
                 while( !temp.isEmpty( ) )
                System.out.println( temp.dequeue( ) );
        }
    }

========================
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CodingExperts
CodingExperts

I agree to what CEHJ has suggested. for more detailed reading please see

http://javatechniques.com/public/java/docs/basics/faster-deep-copy.html
Avatar of tyweed420

ASKER

Ok, im trying to do a deep clone and having no luck. I'v done research on this site and tried using a class cloner() . however the cloner method is throwing my catch statement in main? could someone please help me get this queue to become deep cloned ! i'll increase points.


my code

    /**
     * Array-based implementation of the queue.
     * @author Mark Allen Weiss
     */

         import java.io.ByteArrayOutputStream;
           import java.io.ByteArrayInputStream;
           import java.io.ObjectOutputStream;
    import java.io.ObjectInputStream;


    public class QueueArray implements Cloneable
    {
        /**
         * Construct the queue.
         */
        public QueueArray( )
        {
            this( DEFAULT_CAPACITY );
        }

        /**
         * Construct the queue.
         */
        public QueueArray( int capacity )
        {
            theArray = new int[ capacity ];
            makeEmpty( );
        }

        /**
         * Test if the queue is logically empty.
         * @return true if empty, false otherwise.
         */
        public boolean isEmpty( )
        {
            return currentSize == 0;
        }

        /**
         * Test if the queue is logically full.
         * @return true if full, false otherwise.
         */
        public boolean isFull( )
        {
            return currentSize == theArray.length;
        }

        /**
         * Make the queue logically empty.
         */
        public void makeEmpty( )
        {
            currentSize = 0;
            front = 0;
            back = -1;
        }

        /**
         * Get the least recently inserted item in the queue.
         * Does not alter the queue.
         * @return the least recently inserted item in the queue, or null, if empty.
         */
        public int getFront( )
        {
            if( isEmpty( ) )
                return -1;
            return theArray[ front ];
        }

        /**
         * Return and remove the least recently inserted item from the queue.
         * @return the least recently inserted item in the queue, or null, if empty.
         */
        public int dequeue( )
        {
            if( isEmpty( ) )
                return -1;
            currentSize--;

            int frontItem = theArray[ front ];
            theArray[ front ] = -1;
            front = increment( front );
            return frontItem;
        }

        /**
         * Insert a new item into the queue.
         * @param x the item to insert.
         * @exception Overflow if queue is full.
         */
        public void enqueue( int x )
        {
            if( isFull( ) )
           System.out.println("queue is full");
           back = increment( back );
            theArray[ back ] = x;
            currentSize++;
        }

        /**
         * Internal method to increment with wraparound.
         * @param x any index in theArray's range.
         * @return x+1, or 0, if x is at the end of theArray.
         */
        private int increment( int x )
        {
            if( ++x == theArray.length )
                x = 0;
            return x;
        }

          public Object clone()
                 {
                QueueArray queue = null;

                    try
                    {
                     queue =  (QueueArray) super.clone();
                    }
                    catch (CloneNotSupportedException ignore)
                    {
                    //This will never happen because this class is Clonable
                    return null;  //Never get here
                    }

               return queue;

                }




                         public static Object cloneObject(Object o) throws Exception
                         {
                            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                            ObjectOutputStream out     = new ObjectOutputStream(bOut);

                            out.writeObject(o);

                            ByteArrayInputStream bIn =  new ByteArrayInputStream(bOut.toByteArray());
                            ObjectInputStream in     = new ObjectInputStream(bIn);

                            return(in.readObject());
                         }




        private int [ ] theArray;
        private int        currentSize;
        private int        front;
        private int        back;

        static final int DEFAULT_CAPACITY = 10;


        public static void main( String [ ] args )
        {
            QueueArray q = new QueueArray( );
                        QueueArray temp = new QueueArray( );

            try
            {
                    q.enqueue( 1 );
                    q.enqueue( 2 );
                    q.enqueue( 3 );

          temp =    (QueueArray)Cloner.cloneObject(q);



                    temp.enqueue(4);


                   System.out.println( q.getFront()  + "test") ;
            }
            catch( Exception e ) { System.out.println( "Unexpected overflow" ); }  <=== im getting this unexpectedoverflow??

                while( !q.isEmpty( ) )
                System.out.println( q.dequeue( ) );
                System.out.println("=");
                 while( !temp.isEmpty( ) )
                System.out.println( temp.dequeue( ) );
        }
    }
class Cloner
{
       private Cloner() {}

       public static Object cloneObject(Object o) throws Exception
       {
          ByteArrayOutputStream bOut = new ByteArrayOutputStream();
          ObjectOutputStream out     = new ObjectOutputStream(bOut);

          out.writeObject(o);

          ByteArrayInputStream bIn =
                   new ByteArrayInputStream(bOut.toByteArray());
          ObjectInputStream in     = new ObjectInputStream(bIn);

          return(in.readObject());
       }

   }
The reason is that QueueArray is not serializable;

either make it serilibale or

change your clone funcion as

  public Object clone()
  {
    QueueArray copyQueue = null;
    try
    {
      copyQueue =  (QueueArray) super.clone();
      copyQueue.theArray = new int[copyQueue.currentSize];
      for(int i=0;i<copyQueue.currentSize;i++)
        copyQueue.theArray[i] = theArray[i];
    }
    catch (CloneNotSupportedException ignore)
    {
      //This will never happen because this class is Clonable
      return null;  //Never get here
    }
    return copyQueue;
  }

<CE>

<<  <=== im getting this unexpectedoverflow??
  The reason is that QueueArray is not serializable and it is throwing a java.io.NotSerializableException exception

either make it serializable (i.e write a serializer/deserializer) for out.writeObject(o) for QueueArray requires a serializer.


ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>
for(int i=0;i<copyQueue.currentSize;i++)
        copyQueue.theArray[i] = theArray[i];
>>

It would actually be more efficient to use System.arraycopy
Thank you, very much! i can move forward with my work!
tyweed420 can you explain why i got none of the points there to a question i answered?
CEHJ : You need to make a deep copy, going into the object graph of the target

A: I knew i needed a deep copy i just didn't know how to implement it.

CEHJ:

>>
for(int i=0;i<copyQueue.currentSize;i++)
        copyQueue.theArray[i] = theArray[i];
>>

It would actually be more efficient to use System.arraycopy

A: I just needed it to work and coding experts was able to write the entire clone method for me and compiled and worked great! I thought he deserved those points.


However, CEHJ you have helped me with many problems and do not want to anger you, I apologize. i'd be more than happy to give you some points for your responses. Hows a 100 points sound  fair? I'll create a quick question answer it real fast i'll send the points your way. I want your continued help in my infinitly many questions i will ask in the near future. You are a cding "god" your input isd important to me.What you think :)




Well i certainly don't object to CodingExperts getting points on this - s/he deserves them. It's just that i thought *some* points might have come my way, having answered the question ;-) I'd be happy with 50. I'll ask a page editor to help - so do nothing yet ;-)
8-)