The first way compiles for me in JDK 6 and IntelliJ:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class DataSet
{
private Set<DataObject> data;
public DataSet(DataObject obj)
{
this.data = new HashSet<DataObject>();
data.add(obj);
}
public DataSet(DataObject[] objs)
{
data = new HashSet<DataObject>();
data.addAll(Arrays.asList(objs));
}
public DataObject[] getDataObjects( )
{
return (DataObject[]) data.toArray();
}
}
class DataObject
{
// just a dummy to satisfy the compiler.
}
Here are the two implementations from Sun's JDK 6 source code:
public Object[] toArray() {
Object[] a = c.toArray();
for (int i=0; i<a.length; i++)
a[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)a[i]);
return a;
}
public <T> T[] toArray(T[] a) {
// We don't pass a to c.toArray, to avoid window of
// vulnerability wherein an unscrupulous multithreaded client
// could get his hands on raw (unwrapped) Entries from c.
Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
for (int i=0; i<arr.length; i++)
arr[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)arr[i]);
if (arr.length > a.length)
return (T[])arr;
System.arraycopy(arr, 0, a, 0, arr.length);
if (a.length > arr.length)
a[arr.length] = null;
return a;
}
If you look in the javadocs for the java.util.Collection interface, you'll see this:
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* Note that <tt>toArray(new Object[0])</tt> is identical in function to
* <tt>toArray()</tt>.