Security Type: Untested Throw and Generics

I have a very simple map

private Map<String,T> map = Collections.synchronizedSortedMap(new TreeMap<String,T>());

I would like to define the following method

public T[] values(){
    return (T[])map.values().toArray();
}

And obviously, I have a problem with an uncontrolled release ... My problem: I can not call toArray(new T[size]).

What to do to avoid this warning (without using @SuppressedWarning)

thank

+3
source share
4 answers

Avoid arrays. Bring it back List<T>.

Arrays are essential building blocks, but they are rather strange in the type system. Better to avoid them in the API. Almost everywhere, an array can be replaced with an ArrayList. The performance is the same.

+4
source

, , - , T (i. e. a T []). , . toArray (T []).

0

, ? ( @SuppressedWarning)

- , . , -, , ClassCastException.

Java , . -, T, Object[]

0

, Class , Object [].

public T[] values(Class<T> cl){
    return (T[])map.values().toArray((T[])Array.newInstance(cl,0));
}

You still need to use SuppressdWarning for this code, but it will not throw at runtime. In addition, if you need to implement Collection.values ​​(), you must pass the class to your ctor. Arrays and generics just don't mix, so you should prefer to use collections.

0
source

All Articles