5

Possible Duplicate:
why does List<String>.toArray() return Object[] and not String[]? how to work around this?

See this code example :

    List<String> list = new ArrayList<String>();
    list.add("hello");
    list.add("world");
    Object [] array = list.toArray();

Why does the method toArray() return an array of Object ? Other List methods such as get() , remove() are able to return the type of objects in the list.

3
  • 1
    @SuperChafouin please do some research before posting a question. Commented Jun 13, 2012 at 4:03
  • 1
    Ok, this answers to my question : http://stackoverflow.com/a/7909755/1075341 I mark my question as duplicate. Commented Jun 13, 2012 at 4:20
  • For those interested in that question, i found the best way to understand is to try to program your own implementation of toArray using generics or to look at ArrayList code, for example. Commented Jun 13, 2012 at 4:34

4 Answers 4

1

you can use toArray(String[] a) which will return array of string type or basically array of specified type. the toArray method returns object as it acts as bridge between Collection based and List based API.

Sign up to request clarification or add additional context in comments.

Comments

0

I believe is returns Object in order to be generic Most likely it has to deal with memory allocation issues. The system doesn't have to know your exact type inorder to allocate an array of Objects. You don't run into this with get and remove since it's only returning one item.

But I will upvote your question in hope someone can confirm my answer or correct me.

Comments

0

The Java List#toArray explains it.

2 Comments

The answer was accidentally formatted as code -- fixed!
From now on, please refer to a valid documentation. The link was pointing to Java 1.4, there is new documentation in Java 6 and Java 7.
0

toArray() has to construct new array object and fill it up. But because of runtime generic type erasure toArray() does not know what is the actual type of the elements. because of that creates array of Object (Object[]). Use <T> T[] toArray(T[] a) if you want typed array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.