Skip to content

Commit 904347c

Browse files
committed
Refine NamedTuple
1 parent 9af8bf8 commit 904347c

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/NamedTuple.groovy

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,17 +32,24 @@ import groovy.transform.stc.POJO
3232
@POJO
3333
class NamedTuple<E> extends Tuple<E> {
3434
private static final long serialVersionUID = -5067092453136522209L
35-
private final Map<String, E> data = new LinkedHashMap<>()
35+
private final Map<String, E> data
3636

3737
NamedTuple(List<E> elementList, List<String> nameList) {
3838
super(elementList as E[])
3939

40-
int nameListSize = nameList.size()
40+
final int nameListSize = nameList.size()
41+
final int elementListSize = elementList.size()
42+
43+
if (nameListSize != elementListSize) {
44+
throw new IllegalArgumentException("elements(size: $elementListSize) and names(size: $nameListSize) should have the same size")
45+
}
4146
if (nameListSize != new HashSet<>(nameList).size()) {
4247
throw new IllegalArgumentException("names should be unique: $nameList")
4348
}
4449

45-
for (int i = 0, n = nameListSize; i < n; i += 1) {
50+
data = new LinkedHashMap<>((int) (nameListSize / 0.75) + 1)
51+
52+
for (int i = 0; i < nameListSize; i += 1) {
4653
data.put(nameList.get(i), elementList.get(i))
4754
}
4855
}

subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/provider/collection/runtime/NamedTupleTest.groovy

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,15 @@ class NamedTupleTest {
4141

4242
assert err.toString().contains('names should be unique')
4343
}
44+
45+
@Test
46+
void testElementsAndNamesSizeMismatch() {
47+
def err = shouldFail '''
48+
import org.apache.groovy.ginq.provider.collection.runtime.NamedTuple
49+
50+
new NamedTuple([1, 2, 3], ['a', 'b'])
51+
'''
52+
53+
assert err.toString().contains('elements(size: 3) and names(size: 2) should have the same size')
54+
}
4455
}

0 commit comments

Comments
 (0)