1

I am trying to clone an array and return as an object, not an array type. z

 public IntVector clone()
 {

     IntVector cloneVector = new IntVector(3);

     int[] newItems = new int[10];
     for(int i=0 ; i<itemCount_; ++i)
      {
      newItems[i] = items_[i];
      }

     cloneVector = newItems; // is there a way to do something like this??

    return cloneVector;
 }

Main method looks like this

  public static void main(String[] args)
  {

   IntVector vector = new IntVector(5);

   vector.push(8);
   vector.push(200);
   vector.push(3);
   vector.push(41);

   IntVector cloneVector = vector.clone();
  }

*there are two other methods which makes an array:IntVector() and puts value into array:push()

2
  • 1
    What's the class IntVector look like? Commented Sep 16, 2012 at 7:45
  • 1
    You should call the cloneVector.push(newItems[i]). Show us your code please. Commented Sep 16, 2012 at 7:50

1 Answer 1

1

Declare a new constructor for IntVector which takes an int array and a count:

IntVector(int[] data, int n) {
  items_ = data.clone();
  itemCount_ = n;
}

Then you can write clone like this:

public IntVector clone() {
  return new IntVector(items_, itemCount_);
}

You can make that new constructor private if you like, so only clone can use it.

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

2 Comments

This works, but I can't understand how it is working. What does the constructor doing?
The constructor makes a new IntVector by copying the array and count from the old IntVector.

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.