0

In one of my class, I wrote these lines:

String[] score = {"2","3","4","5"};
player = new otherClass(score);
host = new otherClasee(score);
player.shuffle();
host.shuffle()

System.out.println("player is: " + Arrays.toString(player.point));
System.out.println("host is: " + Arrays.toString(host.point));

And the otherClass is:

public class otherClass {
   String[] point;
   public otherClass(String[] something){
      point = something;
   }
   public void shuffle(){
       int ind;
       String change;
       Random rand = new Random();
       for (int i = point.length - 1; i > 0; i--){
            ind = rand.nextInt(i+1);
            if (ind != i){
            change = point[i];
            point[i] = point[ind];
            point[ind] = swap;

  }
}

The "shuffle()" is the method inside class "otherClass" to swap elements of point[]. But the result I receive is that "player" and "host" are shuffled in the exact same way. Specifically, the "player" is shuffled first, then "host" is later. I was expecting the two shuffles to be different.

allicanseenow
  • 123
  • 1
  • 10
  • 1
    I'd be great if we saw the actual shuffle method. Also, if you have a static shuffling algorithm and you pass in the same initial values, you'll always get the same result – Andrew Li Sep 04 '16 at 06:54
  • It sounds like your shuffle method does not use induce any randomness – Daniel Sep 04 '16 at 06:55
  • 1
    You have to manually copy the contents of one array to the other, otherwise you are operating on the same array object in memory – OneCricketeer Sep 04 '16 at 06:59
  • arrays are passed by reference so you are playing with same array in whole program – arshid dar Sep 04 '16 at 07:01
  • `score` is a reference to an array. You can copy this reference but this doesn't copy the array. try changing `host = new otherClasee(score.clone());` – Peter Lawrey Sep 04 '16 at 07:19
  • 1
    @PeterLawrey Thanks for your reply. I find your method is the easiest way to make my code work. – allicanseenow Sep 04 '16 at 08:13

2 Answers2

0

You're passing the same array to both constructors, and shuffling it, so of course it has the same values as itself. If you want the class instances to have independent copies, give them independent copies.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

You use the same String[] object in both your objects "player" and "host". Even if they are of different classes, you give them the same object instance "score".

The solution would be to copy the "score" array.

Try

System.arraycopy(...)

You can do that in the constructor(s) or in the calling class.

Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
neo-de
  • 1