Skip to content

Commit

Permalink
Fix Array.appendAll() arraycopy type mismatch (#2795)
Browse files Browse the repository at this point in the history
Internal `Array.appendAll` optimizations sometimes would result in returning arrays of the wrong type.

```java
private interface SomeInterface {
}

enum OneEnum implements SomeInterface {
    A1, A2, A3;
}

enum SecondEnum implements SomeInterface {
    A1, A2, A3;
}

public static void main(String[] args) {
    Array<SomeInterface> empty = Array.empty();
    Array<SomeInterface> copy1 = empty.appendAll(Array.<SomeInterface>of(OneEnum.values()));
    Array<SomeInterface> copy2 = copy1.appendAll(Array.<SomeInterface>of(SecondEnum.values()));
}
```

----
fixes: #2781
  • Loading branch information
pivovarit authored Aug 17, 2024
1 parent 8b933a5 commit 1425b74
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion vavr/src/main/java/io/vavr/collection/Array.java
Original file line number Diff line number Diff line change
Expand Up @@ -621,7 +621,7 @@ public Array<T> appendAll(Iterable<? extends T> elements) {
if (source.length == 0) {
return this;
} else {
final Object[] arr = copyOf(delegate, delegate.length + source.length);
final Object[] arr = copyOf(delegate, delegate.length + source.length, Object[].class);
System.arraycopy(source, 0, arr, delegate.length, source.length);
return wrap(arr);
}
Expand Down
20 changes: 20 additions & 0 deletions vavr/src/test/java/io/vavr/collection/AbstractSeqTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,16 @@ public void shouldAppendAllNonNilToNonNil() {
assertThat(actual).isEqualTo(expected);
}

@Test
public void shouldAppendAllWhenUsedWithTypeHierarchy() {
final Seq<SomeInterface> empty = of();
final Seq<SomeInterface> all = empty
.appendAll(of(OneEnum.values()))
.appendAll(of(SecondEnum.values()));

assertThat(all).isEqualTo(this.<SomeInterface>of(OneEnum.A1, OneEnum.A2, OneEnum.A3, SecondEnum.A1, SecondEnum.A2, SecondEnum.A3));
}

@Test
public void shouldReturnSameSeqWhenEmptyAppendAllEmpty() {
final Seq<Integer> empty = empty();
Expand Down Expand Up @@ -2276,4 +2286,14 @@ public void shouldTestIndexedSeqEndsWithNonIndexedSeq() {
assertThat(of(1, 2, 3, 4).endsWith(Stream.of(2, 3, 5))).isFalse();
}

private interface SomeInterface {
}

enum OneEnum implements SomeInterface {
A1, A2, A3;
}

enum SecondEnum implements SomeInterface {
A1, A2, A3;
}
}

0 comments on commit 1425b74

Please sign in to comment.