简体   繁体   中英

Should we use type cast for the object.toArray()?

String[] a = c.toArray(new String[0]);

First: Do I need type cast here? (I think we should write like (String[])c.toArray(); BUT I have seen it as just c.toArray() without using type cast. Is this valid?

Second: Also why we write new String[0] ?

The type cast is usually only needed if you're using pre-generics Java. If you look at the docs for Collection.toArray(T[]) you'll see that it knows that the type of the array which is returned is the same as the type of array passed in. So, you can write:

List<String> list = new ArrayList<String>();
list.add("Foo");
String[] array = list.toArray(new String[0]);

You pass in the array to tell the collection what result type you want, which may not be the same as the type in the collection. For example, if you have a List<OutputStream> you may want to convert that to an Object[] , a Stream[] or a ByteArrayOutputStream[] - obviously the latter is only going to work if every element actually is a ByteArrayOutputStream . It also means that if you already have an array of the right type and size, the contents can be copied into that instead of creating a new array.

A previous version of this answer was inaccurate, by the way - if you use the overload which doesn't take any parameters, you always get back an Object[] which can't be cast:

List<String> list = new ArrayList<String>();
list.add("Foo");

// toArray doesn't know the type of array to create
// due to type erasure
Object[] array = list.toArray();

// This cast will fail at execution time
String[] stringArray = (String[]) arrray;

EDIT: I've just noticed this is also mentioned in erdemoo's answer, but it can't hurt to have it here too :)

if you are using list.toArray(), it will return you Object array. Casting to String array will throw exception even if elements stored in list are String type.

if you are using list.toArray(Object[] a), it will store elements in list to "a" array. If the elements inside the list are String and you give String array then it will store elements inside String array, if given array is not large enough to store elements inside the list, then it will expand given list.

  1. Yes you need the downcast since toArray's returns type is Object[].

  2. You need to pass (new String[0]) as a parameter since the method needs to know what kind of array it should return (array of strings, Dates, etc.) Internally all list elements are actually objects so the list does not know the type of elements it is holding and therefore it does not know which kind of array it should return, unless you provide it as a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM