|
1 | 1 | /*
|
2 |
| - * Copyright 2002-2011 the original author or authors. |
| 2 | + * Copyright 2002-2012 the original author or authors. |
3 | 3 | *
|
4 | 4 | * Licensed under the Apache License, Version 2.0 (the "License");
|
5 | 5 | * you may not use this file except in compliance with the License.
|
|
16 | 16 |
|
17 | 17 | package org.springframework.core.convert.support;
|
18 | 18 |
|
| 19 | +import java.util.ArrayList; |
19 | 20 | import java.util.Collections;
|
| 21 | +import java.util.List; |
20 | 22 | import java.util.Map;
|
21 | 23 | import java.util.Set;
|
22 | 24 |
|
@@ -62,18 +64,25 @@ public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor t
|
62 | 64 | if (!copyRequired && sourceMap.isEmpty()) {
|
63 | 65 | return sourceMap;
|
64 | 66 | }
|
65 |
| - Map<Object, Object> targetMap = CollectionFactory.createMap(targetType.getType(), sourceMap.size()); |
| 67 | + List<MapEntry> targetEntries = new ArrayList<MapEntry>(sourceMap.size()); |
66 | 68 | for (Map.Entry<Object, Object> entry : sourceMap.entrySet()) {
|
67 | 69 | Object sourceKey = entry.getKey();
|
68 | 70 | Object sourceValue = entry.getValue();
|
69 | 71 | Object targetKey = convertKey(sourceKey, sourceType, targetType.getMapKeyTypeDescriptor());
|
70 | 72 | Object targetValue = convertValue(sourceValue, sourceType, targetType.getMapValueTypeDescriptor());
|
71 |
| - targetMap.put(targetKey, targetValue); |
| 73 | + targetEntries.add(new MapEntry(targetKey, targetValue)); |
72 | 74 | if (sourceKey != targetKey || sourceValue != targetValue) {
|
73 | 75 | copyRequired = true;
|
74 | 76 | }
|
75 | 77 | }
|
76 |
| - return (copyRequired ? targetMap : sourceMap); |
| 78 | + if(!copyRequired) { |
| 79 | + return sourceMap; |
| 80 | + } |
| 81 | + Map<Object, Object> targetMap = CollectionFactory.createMap(targetType.getType(), sourceMap.size()); |
| 82 | + for (MapEntry entry : targetEntries) { |
| 83 | + entry.addToMap(targetMap); |
| 84 | + } |
| 85 | + return targetMap; |
77 | 86 | }
|
78 | 87 |
|
79 | 88 | // internal helpers
|
@@ -102,4 +111,19 @@ private Object convertValue(Object sourceValue, TypeDescriptor sourceType, TypeD
|
102 | 111 | return this.conversionService.convert(sourceValue, sourceType.getMapValueTypeDescriptor(sourceValue), targetType);
|
103 | 112 | }
|
104 | 113 |
|
| 114 | + private static class MapEntry { |
| 115 | + |
| 116 | + private Object key; |
| 117 | + private Object value; |
| 118 | + |
| 119 | + public MapEntry(Object key, Object value) { |
| 120 | + this.key = key; |
| 121 | + this.value = value; |
| 122 | + } |
| 123 | + |
| 124 | + public void addToMap(Map<Object, Object> map) { |
| 125 | + map.put(key, value); |
| 126 | + } |
| 127 | + } |
| 128 | + |
105 | 129 | }
|
0 commit comments