0

I have a map from X to Y, and I'd like to create a deep-copy of the ranges.

So a normal copy can be done by:

public<X,Y> Map<X,Y> duplicateMapToObject(Map<X,Y> map)
    {
        Map<X,Y> newMap = new HashMap();
        for(X x : map.keySet())
        {
            newMap.put(x,map.get(x));
        }
        return newMap;
    }

And I've tried to make a deep copy of Y (assuming Y has a constructor that can create a new Y-object by using an existing Y object):

public<X,Y> Map<X,Y> duplicateMapToObject(Map<X,Y> map)
    {
        Map<X,Y> newMap = new HashMap();
        for(X x : map.keySet())
        {
            Y y = map.get(x);
            Y newY = new Y(y);
            newMap.put(x,newY);
        }
        return newMap;
    }

However, I get an error "Type of parameter 'Y' cannot be instantiated directly". I'm assuming this is because the compiler doesn't know whether Y has a constructor that can create a new Y-object by using an existing Y-object, which is my assumption. However, I'd expect this to be a runtime error, in the case I call this method on a function without the appropriate constructor.

Is there a way to bypass this?

TheEmeritus
  • 429
  • 1
  • 6
  • 18
  • 1
    This is a more general design of generics and not with your specific requirements about the nature of the constructor. Although that might be one of the reasons this particular design was chosen. See the link I put at the top of your question for details. – Code-Apprentice Jul 14 '22 at 07:07
  • Consider calling `clone()` on the items to copy them. – Olivier Jul 14 '22 at 07:09
  • @Olivier I tried calling clone, but it seems to be working on the class I'm within right now, and not on the Y-class. Or maybe I got the syntax wrong? – TheEmeritus Jul 14 '22 at 07:22
  • If `Y` implements [`Cloneable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html), then you can write `Y newY = (Y)y.clone();`. – Olivier Jul 14 '22 at 07:31
  • @Olivier Compilation error "'clone()' has protected access in 'java.lang.Object'" – TheEmeritus Jul 14 '22 at 07:58

0 Answers0