Re: Converting a HashMap<String, Thing> into a sorted array
On Sun, 22 Oct 2006 00:51:59 +0100, Lew <lew@nowhere.com> wrote:
Daniel Dyer wrote:
There's a more concise way:
public Thing[] convert(HashMap<String, Thing> things)
{
Thing[] tArray = things.values().toArray(new =
Thing[things.size()]);
Arrays.sort(tArray);
return tArray;
}
Another way to express the toArray() call is
Thing [] tArray = things.values().toArray( new Thing [0] );
If this is called often, you can create a static final:
private static final Thing [] ARRAY_TEMPLATE = new Thing [0];
that is used in the call:
Thing [] tArray = things.values().toArray( ARRAY_TEMPLATE );
Whether this provides any benefit is questionable in the particular =
example, but it's good to know your alternatives.
The version I posted will copy the contents into the array that is passe=
d =
in. With your version, a new array will be created since the argument =
array is not big enough (unless the map happens to be empty).
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html#toArra=
y(T[])
"If the collection fits in the specified array, it is returned therein. =
=
Otherwise, a new array is allocated with the runtime type of the specifi=
ed =
array and the size of this collection."
This is not the neatest method in the API.
Dan.
-- =
Daniel Dyer
http://www.uncommons.org