1 2 Previous Next 22 Replies Latest reply: Oct 18, 2010 9:51 AM by 796440 RSS

    Acting java as if it's C problem - Java Pointer Problem

    806067
      Hello All!
      I'm surprised when I debugged my program. I was expecting a sequential assigning between values like in C, but it didn't work, and all my efforts are about to go if I don't solve this issue. Here is a code snippet:
       private ArrayList<Game> generateMoves (Game game) {
      
              ArrayList<Game> moves = new ArrayList<Game>();
              Game tempGame = game;
      
              for (int generatedNumber = 0; generatedNumber < 7; generatedNumber++) {
                  for (int row = 0; row < 6; row++) {
                      if (tempGame.board[row][generatedNumber] != 0) {
                          continue;
                      }else {
                          tempGame.board[row][generatedNumber] = 1;
                          tempGame.position = generatedNumber;
                          //tempGame.who = game.who; // ???
                          moves.add(tempGame);
                          tempGame = game;
                      }
                  }
              }
              return moves;
          }
      I create a new Game object named tempGame, it get's it's value from parameter. Afterwards I modify this tempGame inside the for loop, BUT same modification is reflected to "game" object coming from parameter.

      My expectation was it won't change until I assign it, and therefore when I say "tempGame = game;" tempGame will get the very first value of game.

      I can just say that I didn't understand pointers in Java, but how can I reflect the thought I have. Thank you very much.
        • 1. Re: Acting java as if it's C problem - Java Pointer Problem
          803324
          user9515301 wrote:
          Hello All!
          I'm surprised when I debugged my program. I was expecting a sequential assigning between values like in C, but it didn't work, and all my efforts are about to go if I don't solve this issue. Here is a code snippet:
          private ArrayList<Game> generateMoves (Game game) {
          
          ArrayList<Game> moves = new ArrayList<Game>();
          Game tempGame = game;
          
          for (int generatedNumber = 0; generatedNumber < 7; generatedNumber++) {
          for (int row = 0; row < 6; row++) {
          if (tempGame.board[row][generatedNumber] != 0) {
          continue;
          }else {
          tempGame.board[row][generatedNumber] = 1;
          tempGame.position = generatedNumber;
          //tempGame.who = game.who; // ???
          moves.add(tempGame);
          tempGame = game;
          }
          }
          }
          return moves;
          }
          I create a new Game object named tempGame, it get's it's value from parameter. Afterwards I modify this tempGame inside the for loop, BUT same modification is reflected to "game" object coming from parameter.

          My expectation was it won't change until I assign it, and therefore when I say "tempGame = game;" tempGame will get the very first value of game.

          I can just say that I didn't understand pointers in Java, but how can I reflect the thought I have. Thank you very much.
          Game tempGame = game; Is telling Java to treat tempGame and game as the same object. Any change to one, will change the other.
          • 2. Re: Acting java as if it's C problem - Java Pointer Problem
            796440
            user9515301 wrote:
            Hello All!
            I'm surprised when I debugged my program. I was expecting a sequential assigning between values like in C
            Why? Were you under the impression that Java == C?
            [ code ] and [ /code ], lowercase, without the spaces inside the brackets. Use the Preview tab to see how your post will look before submitting.
            I create a new Game object named tempGame,
            1. Objects don't have names.

            2. There's nothing in your code that creates a new Game object.
            it get's it's value from parameter.
            You mean here?
            private ArrayList<Game> generateMoves (Game game) {
            
              ArrayList<Game> moves = new ArrayList<Game>();
              Game tempGame = game;
            It's just like passing a pointer in C. You have passed a reference to a Game object, in the game variable, and then you copy that reference to the tempGame variable. You now have two references (pointers) pointing to the same Game object.
            Afterwards I modify this tempGame inside the for loop, BUT same modification is reflected to "game" object coming from parameter.
            Because both the tempGame reference variable and the game reference variable point to the same Game object.
            • 3. Re: Acting java as if it's C problem - Java Pointer Problem
              806067
              How can I clone the game object as tempGame object?
              • 4. Re: Acting java as if it's C problem - Java Pointer Problem
                796440
                Kamilon LLC wrote:
                Game tempGame = game; Is telling Java to treat tempGame and game as the same object.
                No it's not. It's telling Java to copy the reference value from the game variable into the tempGame variable, so that both varaibles point to the same object
                Any change to one, will change the other.
                Incorrect. There is only one object. Two references point to it. Any change to that object can be seen through both references because they both point to that single object. Any change to one reference, however (that is, pointing it at a different object, or giving it a value of null) will not be seen by the other reference.
                • 5. Re: Acting java as if it's C problem - Java Pointer Problem
                  796440
                  user9515301 wrote:
                  How can I clone the game object as tempGame object?
                  First, note that the other respondent's answer was rubbish.

                  Second, note that game and tempGame are not objects. They are variables. Those variables hold references (very much like C pointers, not at all like C++ references) that point to objects. The variables do not hold objects.

                  If you want to copy a Game object, one way is to provide a copy constructor.
                  public class Game {
                    
                    public Game(Game otherGame) {
                      this.someField = otherGame.someField;
                      // ... and so on for all fields
                    }
                  }
                  • 6. Re: Acting java as if it's C problem - Java Pointer Problem
                    806067
                    ooh Thanks, now quickly try it. Until I encounter the problem, Copy Constructor was meaningless for me.
                    • 7. Re: Acting java as if it's C problem - Java Pointer Problem
                      tschodt
                      jverd wrote:
                      If you want to copy a Game object, one way is to provide a copy constructor.
                      public class Game {
                      public Game(Game otherGame) {
                      this.someField = otherGame.someField;
                      }
                      }
                          this.someField = otherGame.someField; 
                      this works for primitives and references to immutable class objects.
                      For references to mutable class objects that are going to change
                      clone() or a copy constructor is needed.
                      • 8. Re: Acting java as if it's C problem - Java Pointer Problem
                        806067
                        I'm a little confused all about this, and still couldn't apply the idea to my code.

                        I created a Game object right after my main class definition to allow it to be accessed form all the methods of my Main class:
                        public class Main {
                        
                            Game currentGame = new Game();
                        
                            public static void main(String[] args) throws IOException {
                        I used this Game object in a method in Main class like below, which is resulted as I wanted:
                          private void whoGoesFirst() {
                                try {
                                    Scanner in = new Scanner(System.in);
                                    int turn = in.nextInt();
                        
                                    if (turn == 2) {
                                        currentGame.who = -1;
                                        getNumber();
                        and next method use one of the member field(?don't sure how it's called) of Game object by assigning it to an array:
                            private void getNumber() {
                        
                                int[][] tempBoard = new int[6][7];
                                tempBoard = currentGame.board;
                                tempBoard[0][0] = 1;
                        The above code was first trying of mine. After the copy constructor idea I tried this:
                              tempBoard = new Game(currentGame).board;
                        but again didn't work (currently I'm in a depressed mood and have high temperature). My expectation was that after *"tempBoard[0][0] = 1;"* part, only tempBoard's values will change, but it again affected currentGame's board array. What can I do for this situation?

                        My Game class is here after copy constructor modification at the end :
                        public class Game {
                            int[][] board;
                            int position;
                            int who;
                        
                            public Game () {
                                board = new int[6][7];
                                position = 0;
                                who = 1;
                            }
                        
                            public Game (int c) {
                                board = new int[6][7];
                                who = c;
                            }
                            public Game (int[][] a, int b, int c) {
                                board = new int[6][7];
                                board = a;
                                position = b;
                                who = c;
                            }
                        
                            public Game (Game otherGame) {
                                this.board = otherGame.board;
                                this.position = otherGame.position;
                                this.who = otherGame.who;
                        
                            }
                        }
                        • 9. Re: Acting java as if it's C problem - Java Pointer Problem
                          796440
                          It's the same exact thing.
                          public Game(Game otherGame) {
                            this.board = otherGame.board;
                          }
                          Just like when you did tmpGame = game, here you're doing the same thing--pointing this.board reference variable at the same Board object as otherGame.board points to. There's still only one Board object.

                          As tschodt pointed out, for mutable member variables, if you want each Game object to reference it's own "contained" object, then you need a copy constructor for those as well (or the clone() method).
                          • 10. Re: Acting java as if it's C problem - Java Pointer Problem
                            796367
                            OP wrote:
                            public class Main {
                            
                            Game currentGame = new Game();
                            
                            public static void main(String[] args) throws IOException
                            OP, For starters, I think you would be better off not to throw the IOException from the <tt>static main()</tt> method. Instead, put in a TRY/CATCH block to deal with the IOException.

                            Edited by: pierrot_2 to include the OP message.

                            It also appears to me OP that your understanding of the application in general is not fully realized -- that is, do you even understand what it is you're trying to do? That is the real trick.
                            • 11. Re: Acting java as if it's C problem - Java Pointer Problem
                              796440
                              pierrot_2 wrote:
                              OP wrote:
                              public class Main {
                              
                              Game currentGame = new Game();
                              
                              public static void main(String[] args) throws IOException
                              OP, For starters, I think you would be better off not to throw the IOException from the <tt>static main()</tt> method. Instead, put in a TRY/CATCH block to deal with the IOException.

                              Edited by: pierrot_2 to include the OP message.
                              That has nothing to do with the OP's problem. Additionally, if this is just a school assignment, unless the instructor explicitly prohibits it, there's nothing wrong with throwing any exception from main. There's not likely much he can do to handle it anyway, so he'd just end up logging it an exiting, which is exactly what he gets by throwing it.
                              • 12. Re: Acting java as if it's C problem - Java Pointer Problem
                                796367
                                jverd wrote:
                                That has nothing to do with the OP's problem. Additionally, if this is just a school assignment, unless the instructor explicitly prohibits it, there's nothing wrong with throwing any exception from main. There's not likely much he can do to handle it anyway, so he'd just end up logging it an exiting, which is exactly what he gets by throwing it.
                                That's what makes this so difficult... By looking at all OP's code, poor design is what slaps me in the face. If the program was designed in another fashion, he would have had a completely different problem! AND after that issue is addressed, he's still stuck with a poor design... uh.
                                • 13. Re: Acting java as if it's C problem - Java Pointer Problem
                                  796440
                                  pierrot_2 wrote:
                                  jverd wrote:
                                  That has nothing to do with the OP's problem. Additionally, if this is just a school assignment, unless the instructor explicitly prohibits it, there's nothing wrong with throwing any exception from main. There's not likely much he can do to handle it anyway, so he'd just end up logging it an exiting, which is exactly what he gets by throwing it.
                                  That's what makes this so difficult... By looking at all OP's code, poor design is what slaps me in the face.
                                  Throwing exceptions from main is not necessarily bad design. I certainly don't think it is here. And even if it were, it's one small point on the fringe of the program that doesn't really affect anything else.
                                  • 14. Re: Acting java as if it's C problem - Java Pointer Problem
                                    806067
                                    pierrot_2 wrote:
                                    OP wrote:
                                    public class Main {
                                    
                                    Game currentGame = new Game();
                                    
                                    public static void main(String[] args) throws IOException
                                    OP, For starters, I think you would be better off not to throw the IOException from the <tt>static main()</tt> method. Instead, put in a TRY/CATCH block to deal with the IOException.

                                    Edited by: pierrot_2 to include the OP message.

                                    It also appears to me OP that your understanding of the application in general is not fully realized -- that is, do you even understand what it is you're trying to do? That is the real trick.
                                    I catch some other exception like (InputMismatchException, ArrayIndexOutOfBoundsException) inside the Main class's methods by using try&catch statement, i think my exceptions level don't reach to that much common level. So it justs stay there. It's even automatically created by IDE, to quick fix the error until to focus come on to the exception's of the problem rather than the problem itself :)

                                    It's school assigment, trying to do connect four game. Cause of less expereince I stuck on the copy constructor part instead of heuristic part of the game :) but besides the copy constructor problem it will be a nice AI app.
                                    1 2 Previous Next