0

G'day,

I've been trying to finish an assignment and am learning a lot about OO and Java. Nearing the end of this project so very happy but thought I'd try get an interesting question out there, at least for me because of my lack in understanding.

Some background to help clarify, I've used 2D ArrayLists to model a map. I've made a "copy" of the original so that I can update movements and locations, some are permitted some are not.

I use a method to determine which movement is okay and to then update the "copy". There are two classes involved here.

Class GameEngine {

   void runGameLoop(ArrayList<ArrayList<String>> map) {  
      World w = new World();
      w.setOriginalMap(map);
      while(1) {
         w.checkMovement;
      }
}

Class World {
   ArrayList<ArrayList<String>> originalMap;
   void setOriginalMap(ArrayList<ArrayList<String>> map) {
      originalMap = new ArrayList<>(map);
   }
   void checkMovement (String keyEvent, Player obj1) {
      ArrayList<ArrayList<String>> copyMap = originalMap;
      obj1.setPlayer();
      printMap(copyMap, obj1);
   }

The issue is that the movement is updated on the map, but the player is now in multiple locations being the ones previous... my map has turned into more of a route. Does this has something with using the same object reference? I make a "copy" inside of the Class method so isn't this local?

Would appreciate some insight.

Xhyub
  • 11
  • 4
  • 2
    `ArrayList> copyMap = originalMap;` is **not** a copy. `originalMap = new ArrayList<>(map);` **is** a copy. – Elliott Frisch May 18 '22 at 00:55
  • 2
    All variables in Java are either _primitive_ (like `int`, `boolean` and so on), or _reference_ variables. So when you copy object variable values around, you're actually just copying references, not the objects themselves. And inside an `ArrayList`, even the object itself just contains a bunch of references. If you want to make a completely independent copy of an `ArrayList>`, you're going to have to explicitly make copies of all the lower level lists. – Dawood ibn Kareem May 18 '22 at 01:17
  • Here are some helpful explanations on how object references work: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – sorifiend May 18 '22 at 01:44
  • As Dawood said, to truly make a copy, you need to copy each of the ArrayLists inside the ArrayList. You can do this with `ArrayList> copyMap = new ArrayList<>(originalMap); copyMap.replaceAll(ArrayList::new);` – VGR May 18 '22 at 13:44
  • So can I word this as, instantiate a new object copyMap with a constructor that is passed originalMap? @VGR – Xhyub May 26 '22 at 02:12
  • Yes, that is the first step. The second step is making a copy of each element in the copy. – VGR May 26 '22 at 10:50
  • @VGR Just re-read this, completely missed the second step! – Xhyub Oct 03 '22 at 03:00

0 Answers0