From 9444cad7d84be6c18bba0ac44ed992feb1f8ec14 Mon Sep 17 00:00:00 2001 From: Ray Greenwell Date: Tue, 23 Feb 2010 22:27:30 +0000 Subject: [PATCH] Check our preconditions for fast failure, and added toArray(). --- .../com/samskivert/depot/util/Sequence.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/java/com/samskivert/depot/util/Sequence.java b/src/java/com/samskivert/depot/util/Sequence.java index e70290a..ad95f78 100644 --- a/src/java/com/samskivert/depot/util/Sequence.java +++ b/src/java/com/samskivert/depot/util/Sequence.java @@ -20,11 +20,14 @@ package com.samskivert.depot.util; +import java.lang.reflect.Array; + import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import com.google.common.base.Function; +import com.google.common.base.Preconditions; import com.google.common.collect.Iterators; /** @@ -43,6 +46,8 @@ public abstract class Sequence implements Iterable public static Sequence map (final Collection source, final Function func) { + Preconditions.checkNotNull(source); + Preconditions.checkNotNull(func); return new Sequence() { public Iterator iterator () { return Iterators.transform(source.iterator(), func); @@ -60,6 +65,15 @@ public abstract class Sequence implements Iterable } return list; } + public T[] toArray (Class clazz) { + @SuppressWarnings("unchecked") + T[] array = (T[]) Array.newInstance(clazz, source.size()); + int index = 0; + for (F elem : source) { + array[index++] = func.apply(elem); + } + return array; + } }; } @@ -80,4 +94,10 @@ public abstract class Sequence implements Iterable * Converts this sequence into an array list. */ public abstract ArrayList toList (); + + /** + * Converts this sequence into an array. + * I wish this were S[] toArray (Class clazz); }