-3

I use the code in this link link

This is the code that i used on my project

 public static Map<Coordinate, Field> copy(Map<Coordinate, Field> original) {
    Map<Coordinate, Field> copy = new HashMap<>();
    for (Map.Entry<Coordinate, Field> entry : original.entrySet()) {
        copy.put(entry.getKey(), entry.getValue());
    }
    return copy;
}

but it did not work so I used the other one

Map<Coordinate, Field> temp = board.entrySet().stream()
            .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

but it still did not work, so I want to ask if there is other way to copy a Map<Obeject, Object>? or did I do something wrong?

Maxkw
  • 11
  • 1
  • What does "Does not work" mean? – QBrute Mar 21 '21 at 18:18
  • Provide the sources in a cut-down example that we can run easily. Reduce the problem to its core https://meta.stackexchange.com/questions/22754/sscce-how-to-provide-examples-for-programming-questions (all the downvotes you get are because your question is too broad, has no SSCCE, does not show you tried, and thus we cannot provide a good solution. Update your question). – JayC667 Mar 21 '21 at 18:25
  • I want to make a deep copy of the map, but even when i use the code from this link it was still shallow copy. When i change an element of one map this element will also be changed in the other map – Maxkw Mar 21 '21 at 18:27
  • Sorry i'm not very familiar with stackoverflow – Maxkw Mar 21 '21 at 18:31

1 Answers1

1

You need to create a copy of the Field object (and, possibly, a copy of the Coordinate object too), instead of putting into a new map the same keys and values.

How to create a copy of your objects depends on the design of your classes. Make a copy constructor, for example.

public static Map<Coordinate, Field> copy(Map<Coordinate, Field> original) {
    Map<Coordinate, Field> copy = new HashMap<>();
    for (Map.Entry<Coordinate, Field> entry : original.entrySet()) {
        Field newField = new Field(entry.getValue()); // make copy here
        copy.put(entry.getKey(), newField);
    }
    return copy;
}

Using StreamAPI

Map<Coordinate, Field> copy = original.entrySet().stream()
            .collect(Collectors.toMap(e -> e.getKey(), e -> new Field(e.getValue)));
chptr-one
  • 600
  • 2
  • 15