On 02/26/2013 06:37 PM, sebb wrote:
> On 26 February 2013 17:04, Jörg Schaible <[email protected]> wrote:
>> sebb wrote:
>>
>>> On 26 February 2013 10:27, Simone Tripodi <[email protected]>
>>> wrote:
>>>>> it is not safe, and it will throw an ArrayStoreException in this case,
>>>>> which is documented in the throws clause.
>>>>>
>>>>
>>>> OK I just read the commit, unless it is documented it is fine for me
>>>
>>> Should still be documented on the @SuppressWarnings line please, but
>>> can refer to Javadoc.
>>
>> In that case I typically prefer the suppression as close as possible, i.e.:
>>
>> =========== %< =========
>> if (array.length < size)
>> {
>> @SuppressWarnings("unchecked")
>> T[] unchecked = Array.newInstance(array.getClass().getComponentType(),
>> size);
>> array = unchecked;
>> }
>> =========== %< =========
>>
>> Otherwise you might suppress more than wanted.
>
> +1
Well, normally I am quite open for such suggestions, but I did this
change after looking at the openjdk code. The change would look like this:
/**
* Returns an array of all of this bag's elements.
* If the input array has more elements than are in the bag,
* trailing elements will be set to null.
*
* @param <T> the type of the array elements
* @param array the array to populate
* @return an array of all of this bag's elements
* @throws ArrayStoreException if the runtime type of the specified
array is not
* a supertype of the runtime type of the elements in this list
* @throws NullPointerException if the specified array is null
*/
public <T> T[] toArray(T[] array) {
final int size = size();
if (array.length < size) {
@SuppressWarnings("unchecked") // safe as both are of type T
final T[] unchecked = (T[])
Array.newInstance(array.getClass().getComponentType(), size);
array = unchecked;
}
int i = 0;
final Iterator<E> it = map.keySet().iterator();
while (it.hasNext()) {
final E current = it.next();
for (int index = getCount(current); index > 0; index--) {
// unsafe, will throw ArrayStoreException if types are
not compatible, see javadoc
@SuppressWarnings("unchecked")
final T unchecked = (T) current;
array[i++] = unchecked;
}
}
while (i < array.length) {
array[i++] = null;
}
return array;
}
Any other toArray(T[]) method does not have this level of detail, but at
least this one now.
Thomas
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]