0

I'm trying to create a method that can exchange the location/reference of two class variables, but I can't change the reference of the class variable that is calling the method (this), so I'm wondering is there any way to get around this.

public void exchange(Card x) {
    Card y = this;
    this = x;  //this doesn't work
    x = y;

}
Jason
  • 15
  • 1
  • 5
  • Java is always pass-by-value, so I doubt there is a way... – Sweeper Jan 26 '18 at 17:46
  • 1
    Why would that be needed? – Andrew S Jan 26 '18 at 17:50
  • You can't change the reference, but you _could_ swap the contents... However it would probably be poor design. – Alnitak Jan 26 '18 at 17:50
  • It is possible if you have all cards in an array or something similar and pass the array and the references or indices which should be swapped. – maraca Jan 26 '18 at 17:54
  • 1
    You can't change `this`. Your `exchange` method seems to appear in a class `Card` since `Card y = this;` is legal. From a design standpoint, a Card shouldn't be swapping itself with another Card -- something outside that _contains_ Cards should do the swap. Maybe you have a `Game` that is maintaining 4 `Hand`s which each have 9 `Card`s, and there is a `Deck` of remaining Cards. What class would handle swapping a Card in one Hand with a Card from the Deck? – Stephen P Jan 26 '18 at 18:01
  • @StephenP that's the poor design I was alluding to in my comment – Alnitak Jan 28 '18 at 13:16

1 Answers1

0


Java doesn't pass method arguments by reference; it passes them by value.

The method will fail since Java passes object references by value as well.
You can read more here.

Liadco
  • 414
  • 4
  • 12