当前位置: 首页 > 面试题库 >

将Hashmap分配给Hashmap

淳于飞鸾
2023-03-14
问题内容

我有一个哈希图,我想复制该哈希图以用于其他用途。但是,每当我复制并重复使用它时,它也会更改原始内容。这是为什么?

    do {
            Map<Integer, Map<String, Object>> map1 = originalMap; 
            //at the second iteration originalMap is the same as map1 of the last iteration, 
            //eventhough the change was nog accepted;
            //do something with map1 (change value);
            if(change is accepted) {
               originalMap = map1;
            }
        } while(iteration < 10);

提前致谢

    public static <Integer,String, Schedule>Map<Integer, Map<String, Schedule>> deepCopy(Map<Integer, Map<String, Schedule>> original) {
    Map<Integer, Map<String, Schedule>> copy = new HashMap<Integer, Map<String, Schedule>>();

    for (Map.Entry<Integer, Map<String, Schedule>> entry : original.entrySet()) {
        copy.put(entry.getKey(), deepCopy2(entry.getValue()));
    }
    return copy;
}

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

    return copy;
}

问题答案:

您要做的不是创建地图的副本,而是创建地图的副本。当两个引用指向同一对象时,对一个对象的更改将在另一个对象中反映出来。

解决方案1:如果这是从某种简单类型到另一种类型的Map,则应改为:

Map<SomeType, OtherType> map1 = new HashMap<SomeType, OtherType>(original);

这称为复制构造函数。几乎所有标准的Collection和Map实现都有一个,通常是克隆简单结构的最简单方法。这将正常工作,只要SomeTypeOtherType是不变的(例如,Integer和其他Number类型BooleanString但不集合,日期,地图,阵列等)

否则,正如其他答复者和评论者所指出的那样,您还需要复制地图值。

解决方案2:这是一个快速而又肮脏的版本,应该是安全的:

Map<Integer, Map<String, Object>> original=new HashMap<Integer, Map<String,Object>>();
Map<Integer, Map<String, Object>> copy = 
        new HashMap<Integer, Map<String, Object>>();
for(Entry<Integer, Map<String, Object>> entry : original.entrySet()){
    copy.put(entry.getKey(), new HashMap<String, Object>(entry.getValue()));
}

但是实际上,我喜欢Hunter提供深层复制方法的想法。因此,这里是解决方案3:使用通用参数的我自己的版本:

public static <K1, K2, V> Map<K1, Map<K2, V>> deepCopy(
    Map<K1, Map<K2, V>> original){

    Map<K1, Map<K2, V>> copy = new HashMap<K1, Map<K2, V>>();
    for(Entry<K1, Map<K2, V>> entry : original.entrySet()){
        copy.put(entry.getKey(), new HashMap<K2, V>(entry.getValue()));
    }
    return copy;
}

您可以这样称呼它:

Map<Integer, Map<String, Object>> original=new HashMap<Integer, Map<String,Object>>();
// do stuff here
Map<Integer, Map<String, Object>> copy = deepCopy(original);

更新资料

我在一起学习了一个类,该类对Maps,Collections和Array(原始和其他)执行深度克隆。用法:

Something clone = DeepClone.deepClone(original);

这里是:

public final class DeepClone {

    private DeepClone(){}

    public static <X> X deepClone(final X input) {
        if (input == null) {
            return input;
        } else if (input instanceof Map<?, ?>) {
            return (X) deepCloneMap((Map<?, ?>) input);
        } else if (input instanceof Collection<?>) {
            return (X) deepCloneCollection((Collection<?>) input);
        } else if (input instanceof Object[]) {
            return (X) deepCloneObjectArray((Object[]) input);
        } else if (input.getClass().isArray()) {
            return (X) clonePrimitiveArray((Object) input);
        }

        return input;
    }

    private static Object clonePrimitiveArray(final Object input) {
        final int length = Array.getLength(input);
        final Object copy = Array.newInstance(input.getClass().getComponentType(), length);
        // deep clone not necessary, primitives are immutable
        System.arraycopy(input, 0, copy, 0, length);
        return copy;
    }

    private static <E> E[] deepCloneObjectArray(final E[] input) {
        final E[] clone = (E[]) Array.newInstance(input.getClass().getComponentType(), input.length);
        for (int i = 0; i < input.length; i++) {
            clone[i] = deepClone(input[i]);
        }

        return clone;
    }

    private static <E> Collection<E> deepCloneCollection(final Collection<E> input) {
        Collection<E> clone;
        // this is of course far from comprehensive. extend this as needed
        if (input instanceof LinkedList<?>) {
            clone = new LinkedList<E>();
        } else if (input instanceof SortedSet<?>) {
            clone = new TreeSet<E>();
        } else if (input instanceof Set) {
            clone = new HashSet<E>();
        } else {
            clone = new ArrayList<E>();
        }

        for (E item : input) {
            clone.add(deepClone(item));
        }

        return clone;
    }

    private static <K, V> Map<K, V> deepCloneMap(final Map<K, V> map) {
        Map<K, V> clone;
        // this is of course far from comprehensive. extend this as needed
        if (map instanceof LinkedHashMap<?, ?>) {
            clone = new LinkedHashMap<K, V>();
        } else if (map instanceof TreeMap<?, ?>) {
            clone = new TreeMap<K, V>();
        } else {
            clone = new HashMap<K, V>();
        }

        for (Entry<K, V> entry : map.entrySet()) {
            clone.put(deepClone(entry.getKey()), deepClone(entry.getValue()));
        }

        return clone;
    }
}


 类似资料:
  • 问题内容: 假设我有一个功能 现在,我想将函数分配给一个名为的变量,这样,如果我使用,它将再次调用该函数。如果我只是做作业,它就会返回。 问题答案: 您根本不调用该函数。 括号告诉蟒蛇,你调用的函数,所以当你把它们放在那里,它调用的功能,并指定值 返回 的(在这种情况下)。

  • 目前,我遇到了一个与将Golang变量分配给Javascript变量相关的问题。我正在使用Golang模板,因此,我从后端发送了一个JSON变量,就像这样: 如您所见,我有一个切片,将其转换为Json,然后将Json转换为string,并将其发送到模板。然后,在前端我需要把它赋给一个变量,它应该是有效的JSON,我有这个: 但是,我得到的是语法错误:预期的属性名,得到的是“{” 所以,我的问题是:

  • 我使用的是Kafka流,具有无状态的简单处理器拓扑结构。 我有一个主题,有100个分区,有2台机器,每台机器有50个线程,运行同一个流媒体应用程序,因此最终我将在它们之间进行1-1映射。 主题中的消息已是键控消息。 我有一个逻辑约束,一旦线程连接到一个或多个分区,它应该继续处理这些分区(当然,直到重新启动发生,它会重新洗牌) 我从日志中看到线程反复(重新)加入消费者组。 我的问题,kafka 流

  • 问题内容: 在目标c中,可以通过init方法完成 但是当我迅速这样做时 不能在方法中分配给自身,将显示错误。现在,我的方法是创建一个视图,并将从笔尖加载的视图添加到其中。有人有更好的主意吗? 问题答案: 对于Swift 4 对于Swift 3 您可以在UIView上创建扩展: 注意 :使用UINib更快,因为它可以为您缓存。 然后,您可以执行以下操作: 您将能够在任何视图上重用该方法。

  • 我发现jQuery代码打印出在网格内点击的div,我如何修改这段代码,使它只向点击的div.grid_item添加类“.active”,有人能帮助我理解如何做到这一点吗? 我在下面添加了html和js。 null null

  • 您好,我正在开发一个swing聊天应用程序,其中聊天历史记录存储在一个xml文件中。在NetBeans项目中完成后,我能够获取xml文件并将其显示在表中 但是当转换成jar文件时,我无法使用xml文件。我尝试过各种方法,比如getClass()。getResource()方法,但它检索URL而不是字符串,如果使用toString()方法将其转换为字符串,则无法将其用作解析xml文件的有效路径。 下