简体   繁体   English

是否可以制作不可修改地图的可修改副本?

[英]Is it possible to make a modifiable copy of an unmodifiable map?

Description:描述:

One of my problem sets is provided with test cases to check if the typed code works correctly.我的问题集之一提供了测试用例来检查输入的代码是否正常工作。 I won't go into much detail, but basically these tests take a map as input.我不会详细介绍,但基本上这些测试以地图作为输入。 My code worked perfectly for all test cases except for one: when I took a look at the test, I saw that the input map gets changed into an unmodifiable map ( Collections.unmodifiableMap(numbers) ) and this unmodifiable map is passed on to the method that I wrote.我的代码适用于所有测试用例,除了一个:当我查看测试时,我看到输入映射被更改为不可修改的映射( Collections.unmodifiableMap(numbers) )并且这个不可修改的映射被传递到我写的方法。 This is the only test that does it, so I was wondering if it is possible to make a copy of this unmodifiable map such that it can be modified within my method?这是唯一一个这样做的测试,所以我想知道是否可以制作这个不可修改的地图的副本,以便可以在我的方法中修改它? The most important modification that I'll have to make is updating the value of a key ( map.put(key, map.get(key)-1 ).我必须进行的最重要的修改是更新键的值( map.put(key, map.get(key)-1 )。

Extension:延期:

An additional question, are there similar ways to do this for other data structures such as Lists or Sets?另一个问题,是否有类似的方法可以为其他数据结构(例如列表或集合)执行此操作?

The easiest way is creating a new map:最简单的方法是创建一个新地图:

final Map<?, ?> unmodifiable = Collections.unmodifiableMap(new HashMap<>());
final Map<?, ?> modifiable = new HashMap<>(unmodifiable);

Both maps reference the same values.两个映射引用相同的值。

Extension延期

For collections like lists and sets, it works similarly.对于列表和集合之类的集合,它的工作原理类似。 They usually have constructors that you can pass another collection to.他们通常有构造函数,你可以将另一个集合传递给它。

It isn't necessary to create a new List or Map to update the state of their objects.没有必要创建一个新的 List 或 Map 来更新它们对象的状态。 It's the collections that are unmodifiable, not the objects in them.是不可修改的集合,而不是其中的对象。

      List<Foo> mod = IntStream.range(1, 10).mapToObj(Foo::new).collect(
            Collectors.toList());
      List<Foo> unmod = Collections.unmodifiableList(mod);
      // unmod.add(new Foo(20)); <-- can't do this

      List<Foo> subList = unmod.subList(2, 4);
      //  subList.remove(0); <-- or this
      Foo f = unmod.get(3); 
      f.v = 99; // <-- but this is allowed
      System.out.println(unmod);


      class Foo {
          int v;

          Foo(int v) {
              this.v = v;
          }
          public String toString() {
              return v + "";
          }
       }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM