0

This is my first question here. So The thing is...I would like to understand, how could I reverse an array, that contains objects, without using Array.java.utils and a Temporary array.

    public void reverse() {

    Ball [] ballsTemp = new Ball[balls.length];
    for (int i = 0; i < balls.length / 2; i++) {
        ballstemp[i] = balls[i];
        balls[i] = balls[balls.length -1 - i];
        balls[balls.length -1 - i] = ballstemp[i];
    }
}

So this is not what I want ^

6
  • 2
    What is notas? Why is your temporary variable an array? Commented Oct 27, 2015 at 18:50
  • 2
    without a temporary variable or without a temporary array? Commented Oct 27, 2015 at 18:56
  • My bad sorry. it was mean to be balls. So we are working with a balls[ ] ; Commented Oct 27, 2015 at 18:56
  • Why don't you wan't to use a temporary variable? Commented Oct 27, 2015 at 18:57
  • 3
    You don't need a temporary array, but you do need a temporary variable. With an integer array it can be done without one, due to bit-trickery, but you can't do that with objects. Commented Oct 27, 2015 at 18:59

3 Answers 3

2

Use a temp variable instead of a temp array.

for (int i = 0; i < balls.length / 2; i++) {
    Object temp = balls[i];
    balls[i] = balls[balls.length -1 - i];
    balls[balls.length -1 - i] = temp;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think, You helped a lot! Ty. That easy.
1

Use a Stack instead, here is a very simple example:

  Integer[] intArray = new Integer[5];
  intArray[0] = 3;
  intArray[1] = 6;
  intArray[2] = 9;
  intArray[3] = 12;
  intArray[4] = 15;

  Stack<Integer> intStack = new Stack<Integer>();
  for(int i = 0; i < intArray.length; i++) {
      intStack.push(intArray[i]);
  }

  for(int i = 0; i < intArray.length; i++) {
      intArray[i] = intStack.pop();
  }

Comments

1

If you don't want to use a temporary array, you could use a Stack instead.

Stack ballsTemp = new Stack();
for (int i=0; i<balls.length; i++) {
    ballsTemp.push(balls[i]);
}
for (int i=0; i<balls.length; i++) {
    balls[i] = ballsTemp.pop();
}

Comments

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.