Skip to content

Commit

Permalink
#457: Add 'Seq.toArray' method.
Browse files Browse the repository at this point in the history
  • Loading branch information
jenetics committed Feb 18, 2019
1 parent 29fd80f commit b523386
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
21 changes: 20 additions & 1 deletion jenetics/src/main/java/io/jenetics/util/Seq.java
Expand Up @@ -577,7 +577,7 @@ public default Object[] toArray() {
* @throws ArrayStoreException if the runtime type of the specified array is
* not a super type of the runtime type of every element in this
* array
* @throws NullPointerException if the given array is {@code null}.
* @throws NullPointerException if the given {@code array} is {@code null}.
*/
@SuppressWarnings("unchecked")
public default <B> B[] toArray(final B[] array) {
Expand All @@ -602,6 +602,25 @@ public default <B> B[] toArray(final B[] array) {
return array;
}

/**
* Returns an array containing the elements of this sequence, using the
* provided generator function to allocate the returned array.
*
* @since !__version__!
*
* @param generator a function which produces a new array of the desired
* type and the provided length
* @param <B> the element type of the resulting array
* @return an array containing the elements in {@code this} sequence
* @throws ArrayStoreException if the runtime type of the specified array is
* not a super type of the runtime type of every element in this
* array
* @throws NullPointerException if the given {@code generator} is {@code null}.
*/
public default <B> B[] toArray(final IntFunction<B[]> generator) {
return toArray(generator.apply(length()));
}

/**
* Returns a view of the portion of this sequence between the specified
* {@code start}, inclusive, and {@code end}, exclusive. (If {@code start}
Expand Down
10 changes: 10 additions & 0 deletions jenetics/src/test/java/io/jenetics/util/SeqTest.java
Expand Up @@ -184,4 +184,14 @@ public void toArray4() {
final Integer[] array = mseq.toArray(new Integer[]{1, 2, 3, 4});
}

@Test
public void toArray5() {
final Seq<String> mseq = MSeq.of("1", "2");
final String[] array = mseq.toArray(String[]::new);

Assert.assertEquals(array.length, 2);
Assert.assertEquals(array[0], mseq.get(0));
Assert.assertEquals(array[1], mseq.get(1));
}

}

0 comments on commit b523386

Please sign in to comment.