[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2004-11-09
14
Medium Priority
?
239 Views
Last Modified: 2010-03-31
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( ) );
        }
    }

========================
0
Comment
Question by:tyweed420
  • 5
  • 4
  • 3
  • +1
13 Comments
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 200 total points
ID: 12540083
You need to make a deep copy, going into the object graph of the target
0
 
LVL 6

Expert Comment

by:CodingExperts
ID: 12540986
I agree to what CEHJ has suggested. for more detailed reading please see

http://javatechniques.com/public/java/docs/basics/faster-deep-copy.html
0
 

Author Comment

by:tyweed420
ID: 12541200
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());
       }

   }
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 6

Expert Comment

by:CodingExperts
ID: 12541906
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>

0
 
LVL 6

Expert Comment

by:CodingExperts
ID: 12541948
<<  <=== 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.


0
 
LVL 6

Accepted Solution

by:
CodingExperts earned 600 total points
ID: 12541965
Slight change in the clone function ....
  public Object clone()
  {
    QueueArray copyQueue = null;
    try
    {
      copyQueue =  (QueueArray) super.clone();
      copyQueue.theArray = new int[this.DEFAULT_CAPACITY];
      for(int i=0;i<copyQueue.currentSize;i++)
        copyQueue.theArray[i] = theArray[i];
      copyQueue.back = back;
      copyQueue.front = front;
    }
    catch (CloneNotSupportedException ignore)
    {
      //This will never happen because this class is Clonable
      return null;  //Never get here
    }
    return copyQueue;
  }
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12542754
>>
for(int i=0;i<copyQueue.currentSize;i++)
        copyQueue.theArray[i] = theArray[i];
>>

It would actually be more efficient to use System.arraycopy
0
 

Author Comment

by:tyweed420
ID: 12546834
Thank you, very much! i can move forward with my work!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12547464
tyweed420 can you explain why i got none of the points there to a question i answered?
0
 

Author Comment

by:tyweed420
ID: 12548147
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 :)




0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12548196
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 ;-)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12549126
8-)
0
 
LVL 92

Expert Comment

by:objects
ID: 12570969
tyweed420,

Could you also then award me points in the following two questions which I answered and you ignored my comments:
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21158761.html
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21154430.html
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month20 days, 2 hours left to enroll

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question