|
3 | 3 | import java.util.ArrayList; |
4 | 4 | import java.util.Arrays; |
5 | 5 | import java.util.HashMap; |
| 6 | +import java.util.LinkedHashSet; |
6 | 7 | import java.util.LinkedList; |
7 | 8 | import java.util.List; |
8 | 9 | import java.util.Map; |
@@ -88,7 +89,6 @@ void range(int at, int len) { |
88 | 89 | private static final class Import extends Occurrence { |
89 | 90 | final LinkedList<String> packageSegments = new LinkedList<>(); |
90 | 91 | final LinkedList<String> classSegments = new LinkedList<>(); |
91 | | - final StringBuilder name = new StringBuilder(); |
92 | 92 | boolean isStatic; |
93 | 93 | boolean isStar; |
94 | 94 |
|
@@ -170,30 +170,34 @@ private String replace() { |
170 | 170 | // these blocks were kept inline to better see overall work done |
171 | 171 | // and preserve context/state of result content and sourceAt pointer |
172 | 172 |
|
173 | | - // append useful (non-skipped) imports to the end of our newImports set |
| 173 | + // copy all generated imports preserving their sorted ordering |
| 174 | + // this new set will maintain insertion order |
| 175 | + Set<String> rewrittenImports = new LinkedHashSet<>(newImports); |
| 176 | + |
| 177 | + // append useful (non-skipped) imports to the end of our rewrittenImports set |
174 | 178 | for (Import imp : imports) { |
175 | 179 | if (imp.isStatic |
176 | 180 | || imp.isStar |
177 | 181 | || imp.classSegments.size() != 1 |
178 | 182 | || !imp.packageSegments.equals(JAVA_LANG)) { |
179 | 183 |
|
180 | | - newImports.add(imp.toString()); |
| 184 | + rewrittenImports.add(imp.toString()); |
181 | 185 | } |
182 | 186 | } |
183 | 187 |
|
184 | 188 | // Run import modifiers if present on the classpath |
185 | 189 | for (GeneratedImportsModifier modifier : importsModifiers) { |
186 | | - modifier.modify(thisPackage, newImports); |
| 190 | + modifier.modify(thisPackage, rewrittenImports); |
187 | 191 | } |
188 | 192 |
|
189 | | - // Insert new imports |
190 | | - if (!newImports.isEmpty()) { |
| 193 | + // Insert rewritten imports |
| 194 | + if (!rewrittenImports.isEmpty()) { |
191 | 195 | int insertAt = Math.max(beforeImportPosition, afterPackagePosition); |
192 | 196 | // append all header and package declaration before insert position |
193 | 197 | result.append(source, sourceAt, insertAt); |
194 | 198 | sourceAt = insertAt; |
195 | 199 |
|
196 | | - for (String n : newImports) { |
| 200 | + for (String n : rewrittenImports) { |
197 | 201 | result.append("import ").append(n).append(";\n"); |
198 | 202 | } |
199 | 203 |
|
|
0 commit comments